Finding Mean value program. Variable declaration and inputs - c

The program always prompts me to give one more input, if I declare 3 vars asks 4 inputs etc... The catch here is that if i put another variable inside the program, it always prompts me to input one more from the number i declared at the first place.
It DOES show the average correctly, but always asks me to give one more input which i think program doesnt even count and probably its the last input it asks me, but its there!
//Variable declaration.
int math,pro,net;
int average;
//ask user to give 3 grades.
printf("Give me your grades from your last semester\n");
//prompt user.
scanf("%d\n %d\n %d\n",&math,&pro,&net);
// simple average.
average = (math+pro+net)/3;
// show average.
printf("Your average is :%d\n\n",average);

change
scanf("%d\n %d\n %d\n",&math,&pro,&net);
to
scanf("%d %d %d",&math,&pro,&net);
however, the real problem was the last newline character in your scanf format. scanf would keep on eating up whitespace character and won't terminate. however, if you send to stdin an EOF sign (hit ctrl+d on linux) the average will be computed with 3 variables specified.
note that newlines are treated by scanf same as other whitespace characters.

Its because extra "\n" at the end of the scanf function. You can either Do the following code:
scanf("%d %d %d",&math,&pro,&net);
or if you want to follow your coding standard then write:
scanf("%d\n %d\n %d",&math,&pro,&net);

Also note that your calculation is in itegers. If your grades are in the continental range (i.e. 1..5) you probably want to float average = (math+pro+net)/3.; printf("Your average is :%f\n\n",average); to avoid the loss of the fractional part od the result.

Related

Stop Decimal Values From Being Entered into C Program

I have a program which takes input from the user and tells the user which number is bigger num1 or num2. My problem is that i don't want to allow the user to enter a decimal number such as 1.2 etc.
Here is my program so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int num1;
int num2;
printf("enter a number: ");
scanf("%d", &num1);
printf("enter another number: ");
scanf("%d", &num2);
printf("\n");
printf("\n");
if (num1 < 0) {
printf("Enter a value which is not below 0!");
}
else if (num1 == num2) {
printf("%d and %d are equal", num1, num2);
}
else if (num1 > num2) {
printf("%d is bigger than %d", num1, num2);
}
else if (num2 > num1) {
printf("%d is bigger than %d", num2, num1);
}
return 0;
}
Currently my program displays an error message if a user enters a negative number.
But I want to deter and stop any decimal numbers from being entered at all weather below 0 as a negative number or not.
You cannot, with standard Console input, prevent the user from entering arbitrary strings. (That would require to receive every single character as it is typed, and suppress "illegal" characters, which is both system specific). So you are stuck with receiving a stream of input and checking its contents. If the input was wrong, you can prompt the user to try again.
There are two basic ways:
You do read floating point numbers with %f. This format skips any whitespace, then tries to parse a number from the following word, and stops when it encounters a character which does not let it continue parsing a number. (That is typically another whitespace separating it from the next number but could be a letter or any other non-numerical character.) Then you check whether it is a whole number. The easiest way to do that is to cut the fraction part of the parsed value and see whether it is equal to the parsed float. An easy way to cut off any decimal places is to truncate it to int: if((int)f != f) { /* user entered a number with decimal places */ }.
You read a word from the input as a string (%s) and parse it manually. That's more complicated but actually a pretty neat beginner exercise, in particular if you try to come up with all possible stupid inputs (unprintable characters, very long words, several minus sings etc.) and test and harden your routine against them.
One important advice: Whatever way you decide to go, make sure to evaluate the return value of the input routine. I see that you do not evaluate the return value of scanf in your program, but that is essential. scanf returns the number of successfully converted items (i.e. in your case 1 if a number could be read). If scanf returns 0, it could not parse a number from the input (for example because the first character in the input is a decimal point which cannot be part of an integer number), and you have to perform some kind of error handling. In particular, you must read away the offending word (or line? Depends on the strictness you want to impose on the input format) of the input.
Another advice on the side is to prepare your program for non-interactive use. This means that there is nobody sitting in front of a console entering numbers and hitting enter — instead the standard input comes from a file or another program. In order to provide input from a file one would write myprog < sometextfile.txt in a Console on Windows as well as in a Linux etc. terminal. Programs profit enormously from being "scriptable"; it also makes it easy to quickly test them against many kinds of input in a repeatable fashion. But if the input comes potentially from a file there is, for example, no need to expect every number (or every pair of numbers) to be on its own line.
1.2 is not a decimal data type. It is a float data type!
As you've used %d in the scanf, the value before . will get stored in num1 and 0 will be stored in num2;
int num1,num2;
scanf("%d%d",&num1,&num2);
printf("%d %d",num1,num2);
if entered 1.2 & 3.4
o/p:- 1 0
if entered 1 & 3.4
o/p:- 1 & 3
Try this concept - 'Scanset' or 'Negated Scanset'
scanf("%[^.]", &num1); // does not allow decimal point (.) and will accept not only number but all other characters
or
scanf("%[0-9]", &num1); // only accept positive integer

Program To Check If A Number Is Present In An Array

I wrote the below C code to check if a number is present in an array whose elements are input by the user. But weirdly it's skipping the the third printf statement, directly taking the input and printing Enter the number you wish to look for after taking that input. What is causing this? Included input and output box below code.
CODE:
#include <stdio.h>
#include <stdlib.h>
void main() {
int arr[30], size, i, num, flag=0;
printf("Enter size of array. \n");
scanf("%d",&size);
printf("Enter %d array elements one by one. \n",size);
for (i=0; i<size; i++) {
scanf("%d \n",&arr[i]);
}
printf("Enter the number you wish to look for. \n");
scanf("%d",&num);
for(i=0;i<size;i++) {
if (num == arr[i]) {
flag++;
}
}
if (flag>0) {
printf("The number %d is present in the array.",num);
} else {
printf("The number %d is not present in the array.",num);
}
}
INPUT/OUTPUT:
Enter size of array.
5
Enter 5 array elements one by one.
1
2
3
4
5
5
Enter the number you wish to look for.
The number 5 is present in the array.
You can see that Enter the number you wish to look for. should come before 5, but it is not so.
Solved
Simply fixed by removing \n from scanf.
In scanf, a space character already represents any whitespace. So in your "%d \n" the function already processes the new line right after the last digit, but then you force it to wait for another newline.
This causes the program to wait for yet another line. After it's input, the program continues and asks for the number to search, and at that point the input was already entered.
Just use only one space in scanf, it will already work for the newline, ideally before the digit itself so that you don't need one extra line to complete the operation:
scanf(" %d", arr + i);
The space in the input format string "%d \n" tells the input system to
consume... all available consecutive whitespace characters from the input
(described here)
So when you enter your last number 5, the system now tries to consume all whitespace characters. To do that, it waits for additional input, until it's not a whitespace. So, paradoxically or not, to consume spaces, the system has to read a non-space, which is the second 5 you input.
To fix this behavior, you can tell your system to input only a number, without consuming whitespace:
scanf("%d",&arr[i]);
However, this will leave the whitespace in the buffer, which may interfere with later input. To discard the whitespace, you can use various techniques, described e.g. here.
In my opinion, the most correct technique (however, maybe the most cryptic one) is
scanf("%d%*[^\n]%*c",&arr[i]);
%d - read the number
%*[^\n] - read a string, terminated by a newline byte; discard it and don't store it anywhere
%*c - read a byte (which is a newline byte); discard it and don't store it anywhere
BTW in your format string "%d \n", there are two whitespaces: a regular space and an end-of-line. They both tell scanf to consume all whitespaces in input. The effect is exactly the same as with one space "%d " or with one end-of-line "%d\n", so this particular format string may be highly confusing to whoever reads your code (including yourself).

How does scanf work in this simple program?

I have some trouble working with scanf in a while loop.
I wanted to make a program that would ask the user to write three integers and save them in an array of three positions. If the user writes something which is not an integer, the program should continue asking for an integer until (s)he enters it. But it didn't work properly.
So I tried to simplify the problem with this code:
#include <stdio.h>
int main()
{
int num1=1;
int num2=2;
int num3=3;
printf ("write a number\n");
scanf("%i", &(num1));
printf("%i\n",num1);
printf ("write a number2\n");
scanf("%i", &(num2));
printf("%i\n",num2);
printf ("write a number3\n");
scanf("%i", &(num3));
printf("%i\n",num3);
}
If the inputs are 3 integers, there's no problem. But if you write a character, for example a, for the first integer, the other 2 values are not scanned and it simply writes:
a
2
3
The last two values are the initialization values.
Can anyone tell me what I have to do?
The scanf function does not have to read after it encounters the first invalid character in the input.
The %i specifier allows a as a hexadecimal, but it MUST be preceded by 0x.
If a was the first character in the input, and it was supposed to match to %i, then scanf wouldn't have to read anything afterwards - it can stop at the first invalid character..
References:
http://www.gidnetwork.com/b-64.html
For each conversion specifier scanf tries to locate the appropriate data item. scanf reads the item, stopping when it encounters a character that can't possibly belongs to the item. If any item is not read successfully then scanf returns immediately without looking at the rest of the format string.
When you enter a 5 10, scanf finds a for the specifier %i. It immediately returns and stops reading other inputs 5 and 10.

I am reading Integer from standard input files and have to stop as user stop to enter integers . How this can be done?

I am writing an algorithm where I take a maximum of 10 inputs. The user is allowed to enter any number of inputs. The problem is I cannot tell the user that at last input you have to enter -1 or anything else. I need to find a mechanism to do this. Does anyone have some advice regarding that?
The scanf() function returns the number of objects it successfully wrote into.
Use that value!
int n, a[10];
n = scanf("%d%d%d%d%d%d%d%d%d%d", a+0, a+1, a+2, a+3, a+4, a+5, a+6, a+7, a+8, a+9);
printf("You entered %d values\n", n);
Note for the specific snippet, the user must signal the end of input with some erroneous value (like "42 13 -100 boo") or with EOF ("42 13 -100 CTRL+D CTRL+D"). Just typing ENTERs has no effect: they are ignored by the "%d" conversion specification.
pseudocode:
get count limit
saturate to 10
start loop (for count-limit times)
scanf
put value to array
end loop
or:
start loop
scanf
put value to array
increment counter
check if counter==10 or input is blank then quit
end loop

Why does scanf not terminate when I expect it to

If I write a C program then it will not automatically get out of if else like ....
#include<stdio.h>
int main ()
{
int a, b, c, d;
printf ("enter the value ");
scanf("%d %d %d ",&a,&b,&c);
d=a+b+c;
if(d==180)
printf("triangle is valid ");
else
printf("triangle is invalid ");
return 0;
}
then it will not terminate itself.....
Can anyone help to figure out what the problem in this .....
It's the space at the end of the scanf format string. Remove that space and your program will terminate.
I guess there is inconsistency between the scanf() format string and the format you enter your data in. But seriously, you should accept some old answers before asking new questions.
Omit the spaces in the scanf string
scanf("%d%d%d",&a,&b,&c);
scanf function normally skip the space between the inputs.
In your code you ask the input in the following format
scanf("%d %d %d ",&a,&b,&c);
It is represent the 1input as 1 space,1input and 1 space, 1input and 1 space.
So if you give the three input after the enter, it will skip the new line also.
Because scanf function will take the input as non white space character.
To avoid this you need to give the 4 input. So that time, the first three inputs are stored in the variable a b c, Then next space and values are stored in the buffer.
After run the program you need to give the input like the folllowing
12 12 12 12
Here the first three inputs are stored in the a b c variables.
Otherwise your scanf format should be the following format
scanf("%d%d%d",&a,&b,&c);

Resources