Another way to terminate loop? - c

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

Related

(Visual Studio)Calculation _using for sentence

Want to elicit average of entered real value,until negative value is entered.
My problem is
My calculation don't quit when negative value is entered
It keep asks printf sentence for 3 time.
What did I do wrong?
#include <stdio.h>
int main(void)
{
double total = 0.0;
double input=0.0;
int num = 0;
for (; input >= 0.0;)
{
total += input;
printf("real number(minus to quit):");
scanf_s("%1f", &input);
num++;
}
printf("average:%f \n", total / (num - 1));
return 0;
}
you have many problems with your code :
it's not %1f in the line scanf_s("%1f", &total); as %1f will give you undefined behavior , it's %lfas you are scanning a double , there is a big difference between number one and lower case L
the function called scanf returns an integer indicating how many elements could be assigned to the input that the user entered , so , you should do if(scanf_s("%lf", &input) == 1) to check if the assignment done successfully, that will help you in detecting if - is entered instead of the number
if the user entered a lonely - then sacnf will fail to convert and you have to take another approach
when you are printing the average in this line : printf("average:%f \n", total / (num - 1)); , you actually prints a double , so it's %lf instead of %f
the condition of the for loop is incorrect , you are saying for (; input >= 0.0;) but this will prevent you from entering any negative values as when entering a negative value , the for loop will break , so you could use while(1) instead of the for loop and only break when a - is entered alone
so here is my edited version of yours , I introduced a dummy string to read the buffer and check whether the input was a lonely - or not , and if not then I try to convert it to double and here is my edited solution :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char dummy[30];
double total = 0.0;
int num = 0;
double DecimalConverted = 0;
while(1)
{
printf("real number(minus to quit):");
fgets(dummy, 30, stdin); // gets the input into the buffer
if(dummy[0] == '-' && dummy[1] == '\n') // break from the loop on condition that '-' only entered
break;
// convert the string to decimal
DecimalConverted = strtod(dummy ,NULL);
if(DecimalConverted == 0)
printf("not a number\n");
else{
total += DecimalConverted;
num++;
}
}
printf("average:%lf \n", total / (num - 1));
return 0;
}
and here is the output :
real number(minus to quit):12
real number(minus to quit):-51
real number(minus to quit):-
average:-39.000000

A question about break statement in c programming

I wrote this loop to add numbers, and the break to get out of the loop if the number entered is less than zero, and in last print the calculated numbers without adding the negative number. but the problem is even I wrote the break statement before the addition when I enter 15 and 15 and -2 the output is 28 rather than 30
I found out how to fix that, what I want to know is why
and thank you.
#include <stdio.h>
void main()
{
int j = 1, num = 0, rslt = 0;
while (1) {
if (num < 0) break;
printf("enter a number : ");
scanf("%d", &num);
rslt = rslt + num;
}
printf("the resluts are %d\n", rslt);
}
Currently, you are effectively testing the input of the previous iteration, after already adding it to your result. Instead, check the number immediately after the user enters it, before you perform any calculations.
#include <stdio.h>
int main(void)
{
int num = 0, rslt = 0;
while (1) {
printf("enter a number : ");
scanf("%d", &num);
if (num < 0)
break;
rslt += num;
}
printf("the results are %d\n", rslt);
}
You might also want to check that scanf returns the number of successful conversions you were expecting (in this case one), to handle the event where the user enters invalid input.
if (1 != scanf("%d", &num))
break;

multiply numbers untill the user enters 0

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.

How i cannot ignore 0(zero) as a grade?

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.

Reading an array with floating point numbers (C programming language)

I am creating a function to read in inputs from the user and put them into a floating point array of numbers with predetermined fix size of 25. It also returns the total amount of items that the user enters. However, for some reason this code will not terminate when I enter 999. I know it is something to do with that it is an int and input is a float, but I don't really know how to fix this (only been learning C for five days).
int readArray(float a[]){
//accepts inputs and puts items in a predefined array of size 25
int index = 0;
float input;
printf("Enter 25 or less elements for array (999 to finish):\n");
scanf("%d", &input); //accept initial response; priming prompt
printf("1st Prompt accepted");
while (input != 999 && index < 25) {
printf("In while loop");
a[index] = input;
index++;
scanf("%d", &input);
}
return (index);
}
The proper format specifier matters a lot here.For float it is %f.So change your scanf() to
scanf("%f", &input);

Resources