Nyabingi
Nyabingi

Reputation: 33

c program to group students marks

Help, I can't seem to identify the problem in my code below.

Here's what I am trying to do: Input a list of marks. Input ends with 0 (0 itself is not someone's mark). Output the number of students who scored 1) greater than or equal to 85; 2) between 60 and 84; 3) strictly less than 60.

Here's my code:

#include stdio.h

int main() {
    int mark;
    int morethan85 = 0, between60and84 = 0, lessthan60 = 0;

    for (true) {
        scanf("%d", &mark);
        if (mark != 0) {
            if (mark >= 85)
                morethan85 = morethan85 + 1;
            else if (mark < 85 && mark >= 60)
                between60and84 = between60and84 + 1;
            else
                lessthan60 = lessthan60 + 1;
        } else
            break;
    }

    printf(">=85:%d, morethan85");
    printf("60-84:%d, between60and84");
    printf("<60:%d, lessthan60");

}

Upvotes: 0

Views: 920

Answers (2)

v3gard
v3gard

Reputation: 185

Whoah. Lots of stuff to comment here.

  1. First of all, "true" is not valid C. You can define a macro or constant named TRUE and set it to "1" - or simply use 1.

  2. If you are looping through something until it breaks, use while() and not for().

  3. Finally, the reason your code isn't working is because you have you have added the quote symbol after the name of your variables in your printf() functions.

Here is a working version of your code:

#include <stdio.h>

int main() {
    int mark;
    int morethan85 = 0;
    int between60and84 = 0;
    int lessthan60 = 0;

    while (1) {
        scanf("%d", &mark);
        if (mark != 0) {
            if (mark >= 85)
                morethan85 ++;
            else if (mark < 85 && mark >= 60)
                between60and84 ++;
            else
                lessthan60 ++;
        } else
            break;
    }

    printf(">=85:%d\n", morethan85);
    printf("60-84:%d\n", between60and84);
    printf("<60:%d\n", lessthan60);

}

Upvotes: 0

cnicutar
cnicutar

Reputation: 182674

printf(">=85:%d, morethan85");
                           ^

You're printing plain strings. Try this instead:

printf(">=85:%d", morethan85);
               ^

Also, strictly speaking, passing fewer arguments than required by the format string is undefined behavior.

Upvotes: 3

Related Questions