C, which counts how many missed or failed grades and will exit when a negative number is entered

I am new to C programming and we are still starting with loops. For our exercises, today we were instructed to create a do-while program that calculates how many passed and unsuccessful grades are, but the cycle is interrupted when a negative number is entered. In addition, numbers above 100 are skipped. This is my program:

#include<stdio.h> #include<conio.h> int main() { int grade, pass, fail; pass = 0; fail = 0; do { printf("Enter grade:\n"); scanf("%d", &grade); printf("Enter -1 to end loop"); } while(grade == -1){ if(grade < 100){ if(grade >= 50){ pass = pass + 1; } else if { fail = fail + 1; } } break; } printf("Pass: %d", pass); printf("Fail: %d", fail); getch (); return 0; } 

Can someone please tell me how to improve or where did I go wrong?

+4
source share
4 answers

You need to put all the code you are looping between do and while statements.

 do { printf("Enter -1 to end loop"); printf("Enter grade:\n"); scanf("%d", &grade); if(grade <= 100 && grade >= 0) { if(grade >= 50){ pass = pass + 1; } else { fail = fail + 1; } } } while(grade >= 0); 

The general structure of the do-while loop:

 do { // all of the code in the loop goes here } while (condition); // <-- everything from here onwards is outside the loop 
+3
source
 #include <stdio.h> #include <conio.h> int main() { int grade, pass, fail; pass = 0; fail = 0; do { printf("\nEnter grade:\n"); scanf("%d", &grade); printf("Enter -1 to end loop"); if (grade < 100 && grade >= 50) pass = pass + 1; else fail = fail + 1; printf("\nPass: %d", pass); printf("\nFail: %d", fail); } while (grade >= 0); getch(); } 
+2
source
 do { // stuff } while { // more stuff } 

Mixes 2 concepts together: while loop and do while loop - I will start by refactoring this part.

0
source

The logic of your problem:

  • Keep working until the input is -1. If input is -1, output / output and display output.
    • Enter a rating.
    • If the score is less than or equal to 100, or greater than or equal to 0, perform pass / fail checks:
      • If the degree is greater than or equal to 50, that person has passed. Increase the number of passes.
      • If the score is less than 50, that person has failed. Increase the number of failed exams.

jh314 layout logic is correct, but does not fix execution logic:

  int grade, pass, fail; pass = 0; fail = 0; do { printf("Enter -1 to end loop"); printf("Enter grade:\n"); scanf("%d", &grade); //you want grades that are both less than or equal to 100 //and greater than or equal to 0 if(grade <= 100 && grade >= 0){ if(grade >= 50){ pass = pass + 1; } //if the grades are less than 50, that person has failed. else { fail = fail + 1; } } } while(grade != -1); printf("Pass: %d", pass); printf("Fail: %d", fail); 
0
source

Source: https://habr.com/ru/post/1494870/


All Articles