how to use isdigit() in C - c

So I'm trying to use a isdigit() to check for non numeric values and for some reason when I put in a integer i get a floating exception error and my generated printf statement "invalid input". I am quite confused on why when i enter a digit it goes into my if statement where it is only true if it is NOT an integer
#include <stdio.h>
#include <ctype.h>
int main()
{
int hour=0, minute=0, total=0, maxDiveTime=0, counter=0, average=0;
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter \\0 to stop\n");
while (scanf("%d:%d",&hour, &minute) != '\0')
{
if ((!isdigit(hour)) || (!isdigit(minute)))
{
printf("Invalid Input\n");
break;
}
else
{
if (((hour*60)+minute) > (maxDiveTime))
{
maxDiveTime = ((hour*60)+minute);
}
total = total + (hour*60) + minute;
counter ++;
}
}
average = total/counter;
printf("The total divetime is %d:%d\n", total/60, total%60);
printf("The average divetime is %d:%d\n", average/60, average%60);
printf("The max divetime is %d\n", maxDiveTime );
return 0;
}

First, the reason for the floating exception is that count in expression total/count is zero when you break when entering the loop the first time or when you do not enter the loop at all. So check count before calculating something. Second, scanf returns the number of values successfully read in, which should be 2 in your case. Third, isdigit expects a character, i.e. something like '0', not an integer ranging from 0 to something. When scanf with %d succeeds, you have already successfully read in a number (and nothing else).
int main()
{
int hour=0, minute=0, total=0, maxDiveTime=0, counter=0, average=0;
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter \\0 to stop\n");
while (scanf("%d:%d",&hour, &minute) == 2)
{
if (((hour*60)+minute) > (maxDiveTime))
{
maxDiveTime = ((hour*60)+minute);
}
total = total + (hour*60) + minute;
counter ++;
}
if (count > 0) {
average = total/counter;
printf("The total divetime is %d:%d\n", total/60, total%60);
printf("The average divetime is %d:%d\n", average/60, average%60);
printf("The max divetime is %d\n", maxDiveTime );
}
return 0;
}

Related

c program regarding loops

program wherein there shouldn't be negatives in the equation and it will end when 0 as input
#include <stdio.h>
int main() {
double number, sum = 0;
int average;
int count;
do {
printf("Enter a number: ");
scanf("%lf", &number);
count++;
if (number > 0)
sum += number;
average = sum / (count);
} while (number != 0);
printf("Average is %.1lf", average);
return 0;
}
In your program you are counting all numbers independent on whether they are positive or negative
do {
printf("Enter a number: ");
scanf("%lf", &number);
count++;
//...
Also it does not make a sense to calculate the average within the do while loop.
average = sum / (count - 1);
And it is unclear why the variable average has the type float instead of double.
float average;
And you forgot to initialize the variable count.
Pay attention to that the user can enter neither positive number.
And as it follows from the title of your question you are going to enter integer numbers not double.
The program can look the following way
#include <stdio.h>
int main( void )
{
double sum = 0.0;
double average = 0.0;
size_t count = 0;
while( 1 )
{
printf( "Enter a number: " );
int number;
if ( scanf( "%d", &number ) != 1 || number == 0 ) break;
if ( number > 0 )
{
sum += number;
++count;
}
}
if ( count != 0 ) average = sum / count;
printf( "Average is %f\n", average );
return 0;
}
Firstly, you didn't initialize your count variable. That said, you should increment the count variable only when a non negative value is encountered. Unrelated but I'd recommend you calculate the average outside the loop, as below:
#include <stdio.h>
int main()
{
double number, sum = 0;
float average;
int count = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &number);
if (number > 0)
{
sum += number;
count++;
}
} while (number != 0); //should it stop with 0 or 1? assuming 0
average = sum / count;
printf("Average is %.1lf\n", average);
return 0;
}
First of all, always enable your compiler's warnings. I use -Wall -Wextra -pedantic with gcc and clang. This would have caught the first of the problems listed below if nothing else.
There are many problems.
count is not initialized.
Negative numbers aren't included in the sum as you claim, but they do affect the average because you increment count for negative numbers too.
The assignment asks for you to loop until you get zero, but you loop until you get -1.
The formula for average isn't sum / (count - 1).
average is calculated over and over again for no reason.
You don't handle the case where no inputs are entered, leading to a division by zero.
average is a float, which is odd since you it's built from double values.
You should check the value returned by scanf for errors or end of file.
You don't emit a line feed after your output.
#include <stdio.h>
int main(void) {
int count = 0.0;
double sum = 0.0;
while (1) {
printf("Enter a number: ");
double number;
if ( scanf("%lf", &number) < 1 ) // Invalid input or EOF.
break;
if ( number == 0.0 )
break;
if ( number < 0.0 )
continue;
count++;
sum += number;
}
if (count) {
double average = sum / count;
printf("Average is %.1lf\n", average);
} else {
printf("Nothng to average\n");
}
return 0;
}

Please tell me why this code is not working

This program will determine the count, minimum, maximum, sum and average of all valid numbers entered. It will stop asking for new values when zero is entered and don't accept negative values. After asking for 1st number it just stops working. I will be very happy if anyone can give me some tips how to write it more efficiently and some for just coding.
#include <stdio.h>
#include <stdlib.h>
void display(void);
void menu(void);
int main(void)
{
display();
menu();
system("pause");
return 0;
}
void display(void)
{
printf("program will determine the count, minimum, maximum, sum and average of all valid numbers entered.\n");
return;
}
void menu(void)
{
int count;
float min = 0;
float max = 0;
float sum;
float avg;
float user = 0;
int index;
printf("Please enter the number ==> ");
do
{
// I think I scew up here plz check it.
scanf("%f", user);
if (user > 0)
{
if (user > max)
{
max = user;
}
if (user < min)
{
min = user;
}
}
else
{
printf("Please enter a positive number");
}
sum += user;
count = index;
index++;
} while (user != 0);
avg = sum / count;
printf("The minimum number ==> %f", min);
printf("The maximum number ==> %f", max);
printf("The number of enteries ==> %i", count);
printf("The sum of all values ==> %f", sum);
printf("The average of all values ==> %f", avg);
}
scanf("%f", user); should be scanf("%f", &user);
You'd not want to increase these if input - user is not correct:
sum += user;
count = index;
index++;
Moreover, your count is not being computed correctly. To be specific, you're calculating 1 less than actual count. So put this block inside if statement like this
if (user > 0)
{
if (user > max)
{
max = user;
}
if (user < min)
{
min = user;
}
sum += user;
count = index + 1;
index++;
}
else
{
printf("Please enter a positive number");
}
Be cautious when using %i. %d and %i are same when used in printf but not in scanf.
printf("The number of enteries ==> %d", count); //Notice %d
This line is wrong:
scanf("%f", user);
You are not storing the input into user. You can fix it like this:
scanf("%f", &user);
Here's your error:
scanf("%f", user);
The %f format specifier to scanf expects the address of a float, i.e. a float *. All function parameters in C are pass by value, meaning that changing a parameter isn't reflected in the calling function. By passing a pointer, the function can dereference the pointer to write to the location it points to.
So change the function call to pass in the address of user:
scanf("%f", &user);

Why are my values for sum and count being lost each loop?

I'm getting a consistent divide by zero error, even though each loop should be populating the variables. Code below:
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
sum = 0;
count = 0;
grade = 0;
average = 0.0;
int coolvalue = 0;
while (coolvalue==0)
{
scanf("%d", &grade);
if (grade == -1)
{
sum, sizeof(double);
count, sizeof(double);
average = (sum / count);
printf("%lf", &average);
break;
}
else
{
if ((grade > 100) || (grade < -1))
{
printf("Error, incorrect input.\n");
break;
}
else
{
sum = +grade;
count = count + 1;
return count;
return sum;
}
}
}
coolvalue = 1;
}
int main(void)
{
while (1)
calculateAverage();
while (1) getchar();
return 0;
}
Even while using return, I'm not able to properly increment the value of sum or count.
There are multiple issues in your code.
scanf("%d", &grade); - you don't check the value returned by scanf(). It returns the number of values successfully read. If you enter a string of letters instead of a number, scanf("%d") returns 0 and it does not change the value of grade. Because of this the code will execute the rest of the loop using the previous value of grade. You should restart the loop if the value returned by scanf() is not 1:
if (scanf("%d", &grade) != 1) {
continue;
}
Assuming you enter 10 for grade this block of code executes:
sum = +grade;
count = count + 1;
return count;
return sum;
sum = +grade is the same as sum = grade. The + sign in front of grade doesn't have any effect. It is just the same as 0 + grade.
You want to add the value of grade to sum and it should be sum += grade. This is a shortcut of sum = sum + grade.
return count makes the function complete and return the value of count (which is 1 at this point) to the caller. The caller is the function main() but it doesn't use the return value in any way. Even more, your function is declared as returning void (i.e. nothing) and this renders return count incorrect (and the compiler should warn you about this).
return sum is never executed (the compiler should warn you about it being dead code) because the function completes and the execution is passed back to the caller because of the return count statement above it.
Remove both return statements. They must not stay here.
If you enter -1 for grade, this block of code is executed:
sum, sizeof(double);
count, sizeof(double);
average = (sum / count);
printf("%lf", &average);
break;
sum, sizeof(double) is an expression that does not have any effect; it takes the value of sum then discards it then takes the value of sizeof(double) (which is a constant) and discards it too. The compiler does not even generate code for it.
the same as above for count, sizeof(double);
average = (sum / count);:
the parenthesis are useless;
because both sum and count are integers, sum / count is also an integer (the integral result of sum / count, the remainder is ignored).
you declared average as double; to get a double result you have to cast one of the values to double on the division: average = (double)sum / count;
if you enter -1 as the first value when the program starts, count is 0 when this code is executed and the division fails (division by zero).
printf("%lf", &average); - you want to print the value of average but you print its address in memory. Remove the & operator; it is required by scanf() (to know where to put the read values). It is not required by printf(); the compiler generates code that passes to printf() the values to print.
break; - it passes the execution control after the innermost switch or loop statement (do, while or for). It is correct here and makes the variable coolvalue useless. You can simply remove coolvalue and use while (1) instead.
All in all, your function should look like:
void calculateAverage()
{
int sum = 0;
int count = 0;
int grade = 0;
double average = 0.0;
while (1) {
if (scanf("%d", &grade) != 1) {
// Invalid value (not a number); ignore it
continue;
}
// A value of -1 signals the end of the input
if (grade == -1) {
if (count > 0) {
// Show the average
average = (double)sum / count;
printf("Average: %lf\n", average);
} else {
// Cannot compute the average
puts("You didn't enter any value. Cannot compute the average.\n");
}
// End function
return;
}
if ((grade < -1) || (100 < grade)) {
puts("Error, incorrect input.\n");
// Invalid input, ignore it
continue;
}
sum += grade;
count ++;
}
}
Quite a few corrections need to be made.
The while loop in the calculateAverage() function. That's an infinite loop buddy, because you are not changing the value of that coolValue variable anywhere inside, instead you make it 1 only when it exits the loops, which it never will.
So, use while(1) {...}, and inside it, check for the stopping condition, i.e, if (grade == -1) { ... } and inside it calculate and print the average and return. This will automatically break the while.
You're not checking if the input grade is actually a valid integer or not. Check the value of scanf for that, i.e, use if (scanf("%d", &grade) != 1) { ... }
The expression sum = +grade; is just another way of writing sum = 0+grade which in turn is nothing but sum = grade. Replace this with sum += grade;. This is the right way to write a shorthand for addition.
Two return statements..a very wrong idea. First of all, a function can have just one return(in an obvious way I mean, at once). Secondly, the function calculateAverage() is of return-type void. there's no way how you can return double value from it. So remove these two statements.
I have attached the code below which works. Also do go through the output which I have attached.
CODE:
#include <stdio.h>
void calculateAverage()
{
int grade, count = 0, sum = 0;
double average;
printf("\nenter the grades... enter -1 to terminate the entries\n.");
while (1) {
printf("\nEnter the grade: ");
if (scanf("%d", &grade) != 1) {
printf("\nInvalid characters entered!!!");
continue;
}
else if(((grade > 100) || (grade < -1))) {
printf("\nInvalid grade entered!!!");
continue;
}
else {
if (grade == -1) {
average = sum/count;
printf("\nAverage value of grades: %.3lf",average);
return;
}
else {
sum += grade;
count++;
}
}
}
}
int main(void)
{
calculateAverage();
return 0;
}
OUTPUT:
enter the grades... enter -1 to terminate the entries.
Enter the grade: 50
Enter the grade: 100
Enter the grade: 60
Enter the grade: -1
Average value of grades: 70.000
Perhaps it is better for the function to be of type double instead of void. Although it is not my favorite solution it is close to what you want.
#include <stdio.h>
double calculateAverage(void)
{
double average;
int sum = 0, count=0, grade;
while (1)
{
scanf("%d", &grade);
if ((grade > 100) || (grade < -1))
printf("Error, incorrect input.\n");
else if (grade != -1)
{sum = sum+ grade; count = count + 1;}
else
break;
}
if (count==0)
average=-1.0; //none valid input. Notify the main()
else
average=(double)sum/count;
return average;
}
int main(void)
{
double result;
result= calculateAverage();
if (result!=-1.0)
printf("\n average= %lf",result);
else
printf("No grades to calculate average");
getchar();
return 0;
}

Receiving non-zero exit status when filling an array dynamically from user input

#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
I have attempted many things to try and stop it, and although this may come from a lack of knowledge is there really any way to do this other than creating an enormously large array?
I tried using a dynamic array with calloc() but i was met with the same errors. I am unsure what else is available as an option in this method.
The code is supposed to take the average of "n" user inputted values.
You do not need an array.
Quick & dirty but easier that you wanted to do
int number = 0;
int counter = 0;
int total = 0;
while (number != -1)
{
total += number;
++counter;
scanf("%d", &number);
}
printf("average = %d\n", total / (counter - 1) );

Writing a program to find the largest in a series of 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;
}

Resources