Program is not printing completely - c

I'm trying programming 1st time and not getting the output of this program.Though it looks simple but the code doesn't prints after taking the input like name, roll, marks obtained by student.
I have attached the screenshot of compiler.
Thank you!
#include<stdio.h>
int main()
{
int roll,phy,che,ca,total;
float percentage;
char name[20];
printf("enter the name of student: "); //studentname
scanf("%s",&name);
printf("enter the roll number: "); //roll number
scanf("%d",&roll);
printf("enter the marks obtained in phy,che,ca: "); //marks obtained/subject
scanf("%d%d%d ",&phy,&che,&ca);
//doesnt works from here.
total= (phy+che+ca); //calculating total marks
printf("the total marks obtained is %d\n",total);
percentage =total/3.0; //calculating percentage student got.
printf("the total percentage obtained is %d\n",percentage);
if(percentage>=80)
printf("first division\n"); //first division
else if(percentage>=60 && percentage<=80)
printf("second division\n"); //second division
else if(percentage>=60)
printf("third divison\n"); //third division
else if(percentage>=10)
printf("you failed!\n"); //failed
else
printf("invalid input\n"); //invalid input
return 0;
}
screenshot of the compiler

scanf("%d%d%d ",&phy,&che,&ca);
There is an extra blank character in format. So you should input a more character after you input 3 integers.
And you shouldn't use %d to print a float type variable, you should use %f.

Related

Using C to Find Min and Max value using Function

I need to write a program where users can input their numbers as much as many as they defined, then the program will try to find which one is the lowest value and the highest value. The problems I face are:
When the program executed, the second line will wait on user's input (number) before the printf
The error "system" seems unreliable, sometimes works, sometimes doesn't work
The program only checks the last number entry, therefore it only shows the last number in min and max
You may give hints or corrections along the answers. Thank you very much.
#include <stdio.h>
float max(float num1){
float a=0, b;
if(num1 > a){
a=num1;
}
return a;
}
float min(float num2){
float x=100, y;
if(num2 < x ){
x=num2;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
}
maxi= max(data_Input);
mini= min(data_Input);
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Output:
How many number would you like to type in? : 5
70
Type in the number :
Type in the number : 90.7
Type in the number : 99
Type in the number : 30
Type in the number : 50
The Lowest Number is 50.00
The Highest Number is 50.00
Okay, the thing is that you are not updating the data_input after every successive number is inputted. What you are doing is, comparing the last number to 0 or 100, which is logically incorrect.
How about you take the first number as input, then after every successive input, compare it with the min and max value. Here is the sample code.
#include <stdio.h>
float max(float num1, float num2){
if(num1 > num2){
return num1;
}
return num2;
}
float min(float num1, float num2){
if(num1 < num2){
return num1;
}
return num2;
}
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
// the first number will be minimum and maximum
mini = data_Input;
maxi = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
// make it a composite if condition
while(data_Input<0 || data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(maxi, data_Input);
mini= min(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The program checks the last number because you are calling the min and max function out of the for bracelets so instead you can call them inside the for bracelets like:
for(interval=2; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
and instead of rewriting the same code you can just ask for the numbers inside the for loop and to initialize your interval to 1 so your main will look like:
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : ");
scanf("%d\n",&times);
for(interval=1; interval<=times; interval++){
printf("\nType in the number: ");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:");
scanf("%f",&data_Input);
}
maxi= max(data_Input);
mini= min(data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
Solving the printf issue is easy. As stdout is line buffered (at least by default - it can be changed) it is flushed whenever a newline is inserted in the buffer. So, just add a newline after each message print, for example
printf("How many number would you like to type in ? : \n");
and you'll be fine.
Talking about the wrong calculation of min and max, your attempt has basically two big issues:
You are not acquiring times inputs, but only one. In fact, every time you call scanf you overwrite the same variable data_Input without performing any comparison with the previous inputs
You call min() and max() function only once, after the last input. Furthermore you try to compare the argument with a local variable that has local storage and a lifetime limited to the function itself so that at the next call it will be initialized again
In order to have a variable inside a function that it is initialized only the first time you can use static keyword. But it is not I suggest you to solve the issue.
In my opinion you don't need comparison functions: you can just update maxi and mini each time you get a new input (solving both the aforementioned issues at once):
int main(){
int times, interval;
float mini, maxi, data_Input;
printf("How many number would you like to type in ? : \n");
scanf("%d",&times);
printf("Type in the number: ");
scanf("%f", &data_Input);
maxi = data_Input;
mini = data_Input;
for(interval=2; interval<=times; interval++){
printf("\nType in the number: \n");
scanf("%f",&data_Input);
while(data_Input<0){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
while(data_Input>100){
printf("Invalid Input! Please re-enter the number:\n");
scanf("%f",&data_Input);
}
/* Check input and, in case, update max and min */
if(data_Input > maxi)
maxi = data_Input;
if(data_Input < mini)
mini = data_Input;
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
The comparison is performed inside the loop, so you don't need to store the inputs into an array.
You have plenty issues in your code.
Functions min & max do not make any sense
You do not check result of the scanf and you do not know if it was successfull
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int main()
{
int times, interval;
float mini, maxi, data_Input;
do
{
printf("\nHow many number would you like to type in ? : ");
}while(scanf(" %d\n",&times) != 1);
for(interval = 0; interval < times; interval++)
{
do
{
printf("\nType in the number: ");
}while(scanf(" %f",&data_Input) != 1 && (data_Input < 0 || data_Input > 100));
printf("%f\n", data_Input);
maxi = interval == 0 ? data_Input : MAX(maxi, data_Input);
mini = interval == 0 ? data_Input : MIN(mini, data_Input);
}
printf("The Lowest Number is %.2f\n", mini);
printf("The Highest Number is %.2f\n", maxi);
return 0;
}
When the program executed, the second line will wait on user's input (number) before the printf
Drop "\n" from "%d\n". It blocks until non-white space detected after the number and is not needed.
printf("How many number would you like to type in ? : ");
// scanf("%d\n",&times);
scanf("%d",&times);
printf("Type in the number: ");
If output still not seen when expected, flush it. Typically printing a '\n' will flush stdout, but not certainly.
printf("How many number would you like to type in ? : ");
fflush(stdout); // add
The error "system" seems unreliable, sometimes works, sometimes doesn't work
At least this issue: sequential check vs. checking both conditions together input validity.
Rather than
while(data_Input<0){
...
}
while(data_Input>100){
...
}
Test together.
while(data_Input<0 || data_Input>100){
...
}
The program only checks the last number entry, therefore it only shows the last number in min and max
True as code only compares values once with one call to max(). That function only compares the number to 0 rather than prior values. Likewise for min().
Consider an algorithm change
// Pseudo code for max
prompt How many number would you like to type in ? : "
get times
max_value = -INF // set to minimum possible float
for each value 1 to times
prompt "Type in the number: "
get data_Input
if data_Input > max_value
max_value = data_Input
print max_value

Why does my count becomes 0 when my random number is greater than the number I write?

I have written C code for a game where a random number is generated and the user has to guess the correct number. So, whenever the I write a number and it is greater than the random number, my code is executing as it should. However when I write a number which is less than the random number,the count variable becomes zero, instead of decreasing the count value by 1. I cannot figure out what am I doing wrong?
I have attached the image of my output where the problem can be seen.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
time_t t;
int a,count=5;
srand((unsigned)time(&t));
int randomnumber=rand()%21;
printf("This is a guessing game, Only 5 tries are left\n");
printf("enter the number: ");
scanf("%d",&a);
printf(" \n");
if (a>=20){
printf("ERROR!! Enter number only between 0-20\n");
}
printf("You only have %d tries left\n",count);
printf("enter number only between 0-20: ");
scanf("%d",&a);
printf(" \n");
if (a==randomnumber){
printf("You guessed it correctly, YOU WIN!!\n");
}
else{
for(count=4;count>=1;count--)
{
if (a>randomnumber){
printf("My number is smaller than that\n");
printf("You only have %d tries left\n",(count));
printf("enter number again: ");
scanf("%d",&a);
printf(" \n");
}
}
if (a<randomnumber){
printf("My number is greater than that\n");
printf("You only have %d tries left\n",(count));
printf("enter number again: ");
scanf("%d",&a);
printf(" \n");
}
if (a==randomnumber){
printf("You guessed it correctly, YOU WIN!!\n");
}
}
if (a!=randomnumber)
{
printf("You LOOSE!!, the Number was %d",randomnumber);
}
return 0;
}
Your tests for a < randomnumber and a == randomnumber are not inside the for loop. So you only check them after you've counted all the way down to 0.
You need to put all the tests inside the loop. You should also use else if so that you don't check the new number that they've entered on the same iteration (since you haven't decremented count yet).
And you need to break out of the loop when they guess the number.
The simplest way to organize this is to take all the code that prompts for the next number out of the if blocks, since it's the same for less than and greater than. The if blocks just print which way the error was, and break out when they win.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
time_t t;
int a,count=5;
srand((unsigned)time(&t));
int randomnumber=rand()%21;
printf("This is a guessing game, Only 5 tries are left\n");
printf("enter the number: ");
scanf("%d",&a);
printf(" \n");
if (a>=20){
printf("ERROR!! Enter number only between 0-20\n");
}
printf("You only have %d tries left\n",count);
printf("enter number only between 0-20: ");
scanf("%d",&a);
printf(" \n");
if (a==randomnumber){
printf("You guessed it correctly, YOU WIN!!\n");
}
else{
for(count=4;count>=1;count--)
{
if (a>randomnumber) {
printf("My number is smaller than that\n");
} else if (a<randomnumber) {
printf("My number is greater than that\n");
} else {
printf("You guessed it correctly, YOU WIN!!\n");
break;
}
printf("You only have %d tries left\n",(count));
printf("enter number again: ");
scanf("%d",&a);
printf(" \n");
}
}
if (a!=randomnumber)
{
printf("You LOOSE!!, the Number was %d",randomnumber);
}
return 0;
}

I am getting a nan error when doing loops

So, I am using xcode on mac and made a program that basically does simple math with the users entered values and keeps looping unless it is interrupted. At the end of the loop (once it is broken) I want to print out the total average value (so do some more math). I use a counter and sum variables to do this. However, in out output, I am getting a "nan" error when the loop end and the overall average has to display. Can anyone help, please? :/
int main() {
double gallons=0;
double miles=0;
double sum=0;
int count=0;
while (gallons>=0) {
sum+=(miles/gallons);
count++;
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
}
if (gallons<0) {
printf("The average is: %lf", sum/(count-1));
}
return 0;
}
double gallons=0;
double miles=0;
…
sum+=(miles/gallons);
Dividing zero by zero produces a NaN. Once there is a NaN, any arithmetic with it also produces a NaN.
Hm. In first iteration in sum+=(miles/gallons); you try to add to sum value 0/0. So, I think that you need to move this addition after inputs. Something like
printf("\nEnter the gallons used (-1 to end): ");
scanf("%lf",&gallons);
if (gallons<0)
break;
printf("Enter the miles driven: ");
scanf("%lf",&miles);
if (miles<0)
break;
printf("The miles/gallon for this tank was: %lf", miles/gallons);
sum+=(miles/gallons);
count++;

Taking a 2 or more digit number as char in C

I have to write a program which takes a number as characters and then find its binary, so I used this code:
screenshotofmycode
#include<stdio.h>
#include<math.h>
int main(){
int operation,basetype,k=1,k2=1,binary=0,binary2=0,remainder,remainder2,binaryzero=0000;
char num1,num2;
printf("Please enter the number of the operation you would like to perform:");
printf("\n1. Bitwise OR\n2. Bitwise NOT\n3. Bitwise COMPARE\n4. Exit");
scanf("%d",&operation);
if(operation==1){
printf("You chose Bitwise OR operation.");
printf("\nPlease enter the first number:");
scanf(" %c",&num1);//*here i tried using %s also but it doesn't work for 2
// or more digit numbers..only for numbers from 0-9*//
printf("Please specify the base(10/16):");
scanf(" %d",&basetype);
if(basetype==10){
num1=num1-'0';//*changing from char to decimal*//
if(num1==0){
printf("\nYour first number is base 2 is %04d",binaryzero);
}
else if(num1>0){
while(num1!=0){
remainder=num1%2;
num1=num1/2;
binary=remainder*k+binary;
k=k*10;
}
printf("Your first number in base 2 is:%04d",binary);
}
else{
printf("WARNING: Your number is not valid in base 10!");
printf("\nPlease enter the first number:");
scanf(" %c",&num1);
}
}
else if(basetype==16){
if(num1==0){
printf("\nYour first number in base 2 is %04d",binaryzero);
}
else if(num1>0 && num1<10 ){{
while(num1!=0){
remainder=num1%2;
num1=num1/2;
binary=remainder*k+binary;
k=k*10;}
}
printf("\nYour first number in base 2 is %04d",binary);}
else if(num1>='A' && num1<='F'){
switch(num1){//*i will continue writing cases..*//
case 'A':printf("\nYour first number in base 2 is 1010",binary);}
}
}
}
printf("\nPlease enter the second number:");
scanf("%d",&num2);
printf("Please specify the base(10/16):");
scanf("%d",&basetype);
if(basetype==10){
if(num2==0){
printf("\nYour second number is base 2 is %04d",binaryzero);
}
else if(num2>0 && num2<10){
while(num2!=0){
remainder2=num2%2;
num2=num2/2;
binary2=remainder2*k2+binary2;
k2=k2*10;
}
printf("Your second number in base 2 is:%04d",binary2);
}
else{
printf("WARNING: Your number is not valid in base 10!");
printf("\nPlease enter the second number:");
scanf("%d",&num2);
}}
return 0;
}
Unfortunately, it only works for numbers from 0 to 9, but it should work on 2 or more digit numbers.
I have to take the number as char because the user might enter the number in base 16 and I have to ask the number first then the base type. We are not allowed to use arrays.
Use atoi() function
First include string.h
then do this
char arr[3];
scanf("%s",arr);
int num=atoi(arr);
This doesn't work for your 2-digit number:
num1=num1-'0';

C Code; nested do while loops with inputs

So I got some awesome assistance the other day with a C code problem, hoping this one can generate similar responses. First task is to write a code to accept an unknown number of names. Second is to allow input of an unknown number of values (grades) for each name, and each set of values is averaged and printed with the name. There is a similar thread i read and found some inspiration, but it still isn't compiling right.
I am not married to any particular part of this code, but I was trying to keep it simple with nested Do...while loops. I have tried several different approaches, all fall short of elegantly expressing the unknown number of values assigned to an unknown number of people.
My hope is that the user will be prompted to enter a name, then as long as that value isnt nulled out, the user is immediately prompted to enter grade values that are tabulated in a running total. When the value of grade goes null, the loop quits and the sum total is averaged. The name and average are printed together until the name value is null and then the sub quits. Greatly appreciate any input from the community.
#include <stdio.h>
#include <math.h>
int main(){
char b, stu_name;
float grade, sum, avg;
int i,counter;
do{
printf("Enter a student's name? \n");
scanf("%s", &stu_name);
do{
printf("How many grades are to be entered for this student? \n");
scanf("%d", &i);
for (counter = 0; counter < i; counter++) {
printf("Enter %s's grade, hit enter and enter another \n");
scanf("%f", &grade);
sum = sum + grade;
} while (grade != '\0');
avg = sum/i;
printf("GPA for %s is %f\n", stu_name,avg);
printf("Press any key to enter another student");
scanf("%c",b);
}while (b != '\0');
return(0);}
You're missing the ending brace on the for loop, as Helio Santos pointed out.
You're also having various syntax-type problems:
For the "Enter grade" prompt, you need a %c not a %s as you only
defined stu_name as a char not a char[]
The end of the interior Do/While loop should be checking against i, not grade
That check should also be against a value that scanf could return in your setup; the %d will force trying to get a numeric value
Bam! Compilation success. Thanks much, I appreciate the help. Doesn't look like i can test it fully (notice the whacked out GPA down below) because i don't know how use this online compiler to add a grade more than once (in the loop). If anyone knows whats going on with the GPA stdout i am all ears, going to the next step of the assignment with this code.
*edit after some more comments. Currently rockin the below code. It works...but only 3-4 times for some reason.
#include <stdio.h>
#include <math.h>
int main(){
char b;
char stu_name[75];
float grade, sum, avg;
int i,counter;
do{
printf("Enter a student's name? \n");
scanf("%s", stu_name);
b = '\0'
i = 0;
sum = 0;
printf("How many grades are to be entered for this student? \n");
scanf("%d", &i);
for (counter = 0; counter < i; counter++) {
printf("Enter %s's grade, hit enter and input another \n",stu_name);
scanf("%f", &grade);
sum = sum + grade;}
avg = sum/i;
printf("GPA for %s is %f\n", stu_name,avg);
stu_name[0]= '\0';
printf("Type q or Q to quit or enter to input another student \n");
scanf(" %c", &b);
} while (b != 'q' && b!='Q');
return(0);}

Resources