int main(){
char students_number[30], students_grade[30];
char *number, *value;
int flag=0, students, i, grade, a=0, b=0, c=0, d=0, f=0;
float sum=0;
while(flag==0) // This while loop exist just because to run program until the number of students will be given correct..
{
printf("Please enter the number of students (It must be between 1-100): ");
scanf("%s",&students_number); // This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
students = strtol(students_number, &number, 10); // strtol is a function of stdlib.h and checks the variable is whether int or not for this program..
if(students<=100 && students>0)
{
for(i=1;i<=students;i++)
{
printf("Please enter %d. student's grade (in integer form):",i);
scanf("%s",&students_grade);// This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
grade = strtol(students_grade, &value, 10); // This line checks the grade which was given is integer or not by using strtol which is in the stdlib.h..
if(grade<0 || grade>100 || grade=='\0')
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
else if(grade<=60 && grade>=51)
d++;
else if(grade<=73 && grade>=61)
c++;
else if(grade<=85 && grade>=74)
b++;
else if(grade<=100 && grade>=86)
a++;
sum += grade;
}
}
sum /= students; // This command divides the sum of the grades to number of the students to get the average results in the class..
printf("\nThe average result of the class is %.2f..\n",sum);
printf("\nThe letter form of the all results are:\nNumber of F: %d\nNumber of D: %d\nNumber of C: %d\nNumber of B: %d\nNumber of A: %d\n",f,d,c,b,a);
flag = 1; // As it was mentioned before, this commands exist to break the while loop because the program was done successfully..
}
else // This if command controls the number of students wheter was given right or not..
{
printf("Please enter a proper number of students.\n");
flag = 0;
}
}
return 0;
}
Hello, this is my first question. I had to create a program which calculates the average of the results. But when i enter 0(zero) as a grade then it doesn't allow it just because i tried to exclude the every types except int type.
How can i make this correct?
You can use scanf to read a number and check that scanf done correctly its work:
from man scanf:
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
So you can check that you've read an integer with scanf, without writing if (value == '\0'), which prevents you to read 0 grades...
for(i=1;i<=students;i++)
{
int ok;
printf("Please enter %d. student's grade (in integer form):",i);
/* read line from input. Why using fgets instead of scanf directly? See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html*/
if (NULL == fgets(students_grade, sizeof students_grade, stdin))
{
perror("fgets");
exit(1);
}
/* **try** to parse what have been read */
ok = sscanf(students_grade, "%d", &value);
/* check that scanf has done its work */
if (1 != ok)
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
/* ... */
}
I also advice you to read this article: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.
Related
I don't know why but the loop doesn't stop even when I enter 0. can someone help me with this?
int main(void)
{
float number,product = 1;
printf("Provide floats separated by a line: \n");
scanf("%f" , &number);
while(number != 0)
{
product *= number;
if(number == 0)
break;
}
printf("The product of your values is: %.2f" , product);
printf("\n");
}
You'll need to place the scanf call inside the loop to repeatedly ask the user for input. As it is you only ask once, and then loop forever on the same value.
Here we place the call in the predicate itself:
#include <stdio.h>
int main(void) {
float number = 0,
product = 1;
puts("Provide floats separated by a line:");
while (scanf("%f" , &number) == 1 && number)
product *= number;
printf("The product of your values is: %.2f\n" , product);
}
You should always check the return values of your I/O functions. scanf returns the number of conversions that took place, which here should be 1. On error, EOF, or number being 0 we do not continue the loop.
So, I have to write a program to ask the user for an integer, and then that integer will determine how many more entries the user gets before adding all the numbers that were entered. So, if the first entered integer is "5", then the user can enter 5 more integers. Those 5 integers are then added together at the end and displayed. I have written a program with for loops, but for some reason, it is only adding first 4 integers and not the 5th one. Here is the code:
int main() { //declare main function
int c=0,n,i; //declare integers
int sum=0;
printf("\nEnter an integer: "); //ask user for input and create a label
scanf("%d",&n);
if (n>=0) { //use if statement
for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers
{
sum+=c;
printf("Enter an integer: ");
scanf("%d",&c);
}
}
else {
printf("Wrong number. You can only enter positive integers!");
}
printf("The sum of the %d numbers entered is: %d",i,sum);
return 0;
}
Just change the position of
sum+=c;
to after the scanf it should work.
It is good to split the program. use functions. Not everything in the main function.
int getInteger(void)
{
char str[100];
int number;
while(!fgets(str, 100, stdin) || sscanf(str, "%d", &number) != 1)
{
printf("Wrong input. Try again:") ;
}
return number;
}
int main()
{
int nsamples;
long long sum = 0;
printf("Enter number of samples:");
while((nsamples = getInteger()) <= 0)
{
printf("Try again, entered number must be >= 0\n");
}
printf("Enter numbers:\n");
for(int i = 1; i <= nsamples; i++)
{
printf("Sample no %d:", i);
sum += getInteger();
}
printf("The sim is: %lld\n", sum);
}
I'm studying loops in class and for one of the labs, I have to figure out a way for the user to enter an unspecified number of integers to calculate the average. I know I can have the user enter the number of integers to be averaged in order for the loop to be terminated like below:
int count = 0, value = 0, sum = 0, numberofintegers = 0;
double avg = 0;
printf("enter the number of integers you wish to average\n");
scanf("%d",&numberofintegers);
//loop
while (count < numberofintegers)
{
printf("enter a positive integers\n");
scanf("%d",&value);
sum = sum + value;
count = count + 1;
}
avg = (double) sum/count;
So basically I could have a user input the number of integers to be averaged in order for the loop to terminate, but there has to be another way to make the loop terminate without having the user input it?
Normally you'd use a predetermined "illegal" number like (say -1)
input = read_a_value();
while(input != -1)
{
// do something with input
input = read_a_value();
}
scanf returns the number of successful entries.
This may solve your issue.
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}
A downfall is that the scanf will continue to prompt for input if a user presses the Enter Key repeatedly. In fact you might wish to replace the scanf with fgets. Have a look here.
If you are sure that the user doesn't enter too many numbers, use a string.
Length of string, you can choose according to you and split it using spaces to get the numbers
I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}
The user has to enter a number greater than 0 in order to print some stuff.
my code for when the user enters a number less than 0 uses a while loop. It then asks the user to type in a number again.
while(x<=0){
print("Must enter a number greater than 0");
printf("Enter a number: ");
scanf("%i",&x);}
How can I create an error message formatted similarly to the one above, but for a user who enters a "x" or a word. Thanks
Since the reading is done using scanf with a numeric format, it means that if you enter something that can't be read as an integer (123) or part of an integer (123x is ok, the parsing stops soon after the 3), the scanf fails (i.e. it can't parse the input as number). Scanf returns the number of successfully parsed items. So you expect 1 in your case. You can check the return value (if it's 0, scanf wasn't able to get any number from the input) but as said before you still accept thigs like 123x (and the "residual" x will be parsed in the next scanf from stdin, if you do it).
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void){
int x;
int ok=0;
do{
char buff[32], *endp;
long long num;
ok = !ok;//start true(OK)
printf("Enter a number: ");
fgets(buff, sizeof(buff), stdin);
x=(int)(num=strtoll(buff, &endp, 0));//0: number literal of C. 10 : decimal number.
if(*endp != '\n'){
if(*endp == '\0'){
printf("Too large!\n");
fflush(stdin);
} else {
printf("Character that can't be interpreted as a number has been entered.\n");
printf("%s", buff);
printf("%*s^\n", (int)(endp - buff), "");
}
ok = !ok;
} else if(num > INT_MAX){
printf("Too large!\n");
ok = !ok;
} else if(x<=0){
printf("Must enter a number greater than 0.\n\n");
ok = !ok;
}
}while(!ok);
printf("your input number is %d.\n", x);
return 0;
}