i am getting a unknown error in my c program - c

Code:
#include <stdio.h>
void main()
{
int s1,s2,s3,s4,s5,sum;
float per;
printf("Enter subject 1 marks out of 100 \n");
scanf("%d",s1);
printf("Enter subject 2 marks out of 100\n");
scanf("%d",s2);
printf("Enter subject 3 marks out of 100 \n");
scanf("%d",s3);
printf("Enter subject 4 marks out of 100\n");
scanf("%d",s4);
printf("Enter subject 5 marks out of 100\n");
scanf("%d",s5);
sum=s1+s2+s3+s4+s5;
per=sum/100;
if (per>60 && per<70){
printf("your percentage is %d and you get 10% schoolarship",per)
;}
else if (per>70.1 && per<90){
printf("your percentage is %d and you get 20% schoolarship",per)
;}
else {
printf("your percentage is %d and you get 30% schoolarship",per)
;}
}
Output:
I am trying to make a percentage calculator and it shows a weird output.
What am I doing wrong?

When you call scanf, it is important to pass in the address of the variable you want to store. Otherwise, scanf will not behave as you expect.
Right now, you are not passing in the address to scanf; but rather the variable itself.
So you should do something like:
scanf("%d",&s1);
instead.
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
I recommend reading a little bit about how scanf works at the following link.
"Following is the declaration for scanf() function.
int scanf(const char *format, ...)"
Additionally, check out this link for a few examples of scanf:
https://www.programiz.com/c-programming/c-input-output
scanf("%d", &testInteger);
The syntax is format first, then pass in the address of where you want to store the data.

scanf() requires a pointer to the value, it should be scanf("%d",&s1);

Related

Segmentation fault when handling characters

Fair warning, I am quite new to C, and am still very much a beginner with the language. This problem has stuck with me for a while and I thought someone here might be able to help.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old \n", age);
double gpa;
printf("Enter your GPA: ");
scanf("%lf", &gpa);
printf("You're GPA is %lf \n", gpa);
char name[20];
printf("Please enter your name: ");
scanf("%s", &name);
printf("Your name is %s \n", name);
char grade;
printf("Enter your grade: ");
scanf("%s", &grade);
printf("Your grade it %s \n ", grade);
return 0;
}
The problem lies in the 'grade' section, everything else works perfectly.
The output of the program with user input is
Enter your age: 3
You are 3 years old
Enter your GPA: 4.5
You're GPA is 4.500000
Please enter your name: Test
Your name is Test
Enter your grade: B
Segmentation fault (core dumped)
Hopefully someone here can help. All the best!
Input for getting the input of grade would be
scanf(" %c",&grade);
The issue arises because the grade is a char variable, not a char array.
char -> %c
char array(aka String in C) -> %s
The reason you get segmentation fault is that you are scanning the input B as a string instead of a character (it is equivalent to {'B','\0'}, so it is not just B) and you are trying to assign this string into a char .
If you want to get a character as input (seems like you want it this way) you must do :
scanf ("%c",&grade);
The %c format specifier is for scanning chars, and &grade is basically the address of grade.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
However, if you want to get a string as input (i.e. character array in C) , you must define grade like this :
char grade [n];
(n is a number telling the size of array)
and the scanf line must be :
scanf ("%s",grade);
The %s format specifier is for getting strings (i.e. character arrays in C). The reason why we used grade without an address-of (&) operator is related with pointers. Because grade is already a pointer; we need its value (i.e. the address of the first character of array), not address. Check this link for better understanding. Also check this post after ensuring you've understood the logic of pointers.
Note : This is a self study question. Avoid getting downvoted as possible.

C programming scanf assistance

I am attempting to build a form/gpa calculator for class, but when entering the amount of classes using scanf, the output is 6,487,576 regardless of what I enter.
int main()
{
int opt;
int c;
printf("*******************************\n");
printf("** Fanshawe Grade Calculator **\n");
printf("*******************************\n");
printf("Please Choose an Option:\n");
printf("[1] Enter Your Marks\n");
printf("[2] Quit\n");
scanf("%d", &opt);
switch(opt) {
case 1 :
printf("********************************************************\n");
printf("** Enter Your Marks For Your Courses (Up to 10 Only): **\n");
printf("********************************************************\n");
scanf("%i", &c);
printf("You Have Entered %i Classes!\n", &c);
/*int i;
for(i=1;i=c;i++) {
printf("Enter Your Mark for Class #%i\n", &i);
}*/
break;
case 2 :
printf("GoodBye!");
exit(0);
break;
}
return 0;
}
Help please!
When you use %i with scanf(), it can allow you to input hexadecimal and octal numbers as well (this isn't an issue as explained here).
However, you shouldn't use & while using printf() as it'll display the memory location of the variable instead of the value stored in it.
Try this:
case 1 :
printf("********************************************************\n");
printf("** Enter Your Marks For Your Courses (Up to 10 Only): **\n");
printf("********************************************************\n");
scanf("%d", &c);
printf("You Have Entered %d Classes!\n", c);
break;
printf("You Have Entered %i Classes!\n", &c) outputs the address of the variable c (&c takes the address), i.e. it outputs the number of the memory cell. Since you want to pass the value of the variable you should not use the operator of taking address of a variable &.
printf("You Have Entered %i Classes!\n", c);
There are two problems here. First, you need to include the following headers:
#include <stdio.h> // declares functions like printf and scanf
#include <stdlib.h> // declares functions like exit
If you don't include these headers, then the compiler does not know how to execute them or their exact formats. When you attempt to compile, the warnings will not be helpful. There are a few good websites for this; just search something like "c exit()" in Google and it will tell you which headers you need in the future. When I compiled this code, I used gcc main.c -Wall which forces all warnings to be displayed.
Secondly, you use the address of c in both cases. When you go to print the value of c, you are actually printing the address of c, not the value. scanf() takes the address(es) of the variables to store values in, but printf() takes the variables themselves. The code should look more like this:
scanf("%i", &c);
printf("You Have Entered %i Classes!\n", c);
It is also always a good idea to initialize your variables. This way, you know when something is assigned improperly, or not assigned at all. I forgot to assign my variables for a while, and when compiled on another machine, it didn't work. This is because different machines will initialize variables differently. Just change the code to the following:
int opt = 0;
int c = 0;

Accepting Multiple Strings in 2 dimensional array?

While executing this, loop is directly jumping to the end and giving me below output.
1.Generate Bill
2.Generate Bills of last 10 Purchase
Select Option:1
Enter Number of Groceries:3
Enter GroceryName:XYZ <Hit Enter>
Enter GroceryName:
Enter GroceryName:
Could you please suggest me better way of doing it in c ?
I have already tried certain links on stack overflow on this, however it doesn't seem to be working for me.
void main()
{
int iPrice[1000];
char cGroceName[100][100];
int iOption;
int iGrocNum;
printf("\n1.Generate Bill");
printf("\n2.Generate Bills of last 10 Purchase");
printf("\nSelect Option:");
scanf_s("%d", &iOption);
switch (iOption)
{
case 1:
printf("\nEnter Number of Groceries:");
scanf_s("%d",&iGrocNum);
for (int i = 0; i <iGrocNum; i++)
{
printf("\nEnter GroceryName:");
scanf_s(" %s",cGroceName[i]);
}
scanf_s(" %s",cGroceName[i]);
should be
scanf_s("%99s", cGroceName[i], sizeof cGroceName[i]);
as scanf_s requires a third argument for certain format specifiers such as %s denoting the maximum size of its corresponding argument.
See scanf_s documentation.

Addition not working in c

I was trying c code to add but my program doesn't execute, codeblocks unfortunately closes. What is the error?
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,(a+b));
}
I want to put the result of addition directly in printf statement with float inputs but I am not getting it working.
I also tried putting the result in variable a but it didn't work either.
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
}
where am I going wrong?
The problem is in the following statement
printf("%30sAddition Of Numbers\n");
here, the format string supplied to the printf() conatins %30s (or, %s, in general) which is a format specifier (conversion specifier), and you did not supply any argument to it. It invokes undefined behavior.
To quote C11 standard, chapter ยง7.21.6.1
[...] If there are insufficient arguments for the format, the behavior is
undefined. [...]
You can also check the man page to find out more about the format specifiers.
EDIT:
As discussed in the below comments, if you want some spaces to appear before the output, change
printf("\t\tAddition Of Numbers\n");
That said,
void main() should be int main (void), at least, to conform to the standards.
You should always check the return value of scanf() to ensure the successful scanning.
The "%30sAddition Of Numbers\n" issue in your post has been addressed by two good answers (at the time of this post). But you asked a question in comments that may not have been answered completely:
works with %30s when i use all integer numbers and not float! how do i make it work with floats.
A generic answer to that question:
The format specifier you use in scanf(): "%f",&a could result in undesirable results if scanning in unexpected newlines, spaces or other white space. This can be addressed by modifying the format specifier string to suppress these characters. Here is a suggestion:
char* fmt = "%[^\n]%*c";//This generic format specifier, can be used for both integer
//and floating point inputs when used in conjuction
//with strtod() or strtol() (see below)
scanf(fmt, input);
Explanation of "%[^\n]%*c".
When a user is asked to enter a generic number, it might be a float or an integer. You can accommodate that by creating methods for both, and being specific about what kind of value you would like to process:
float get_float(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter floating point number and hit return:\n");
scanf(fmt, input);
return strtod(input, dummy);
}
long get_int(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
Called like this:
int main(void)
{
long integer_var = get_int();
float float_var = get_float();
float sum = (float)integer_var + float_var;
return 0;
}
Try adding getch(); function at the bottom before closing curly brackets,
like this
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
getch();//it will hold your output screen so you can see the output
}
In this line
printf("%30sAddition Of Numbers\n");
you did not supply a string argument for the %s format. This causes undefined behaviour.
If you want the output spaced, you could try a small modification
printf("%30s\n", "Addition Of Numbers");
in this case you are supplying a string literal to satisfy the %s format.
Additionally you must always check the return value from scanf to see that it did convert the number of arguments it was supposed to. It's a basic newbie error not to, and the root cause of hundreds of SO questions.

I don't understand why I can't get three inputs in c

A friend of mine is trying to learn c (on her own, with a book) and sometimes she asks for help.
She just showed me something I can't answer; I'm ashamed but I studied C in college and then moved to php. I'm really stuck so I would like to know why we can't get three inputs. Here's partial code:
#include <stdio.h>
int main()
{
int num1;
int num2;
char x;
printf("Enter a number:\n");
scanf("%d\n",&num1);
printf("Enter another number:\n");
scanf("%d\n",&num2);
printf("Choose an operation sign:\n");
scanf("%c\n",&x);
...
Like this it asks for the first input two times, like this:
Enter a number:
1
2
Enter another number:
3
Choose an operation sign:
-
If I remove the \n it skips the last scanf.
Can you help me understand why?
Read here: scanf() leaves the new line char in buffer?
Solution:
int main()
{
int num1;
int num2;
char x;
printf("Enter a number:\n");
scanf("%d",&num1);
printf("Enter another number:\n");
scanf("%d",&num2);
printf("Choose an operation sign:\n");
scanf("\n%c",&x); /* See the \n <---------------- */
}
An alternative:
char buf[2]; /* We need 2 characters for the null */
scanf("%1s", buf); /* We ask max 1 character (plus null given by scanf) */
char x = buf[0]; /* We take the first character */
As a small note, thanks to how scanf works, with both the solutions you can insert directly in the first "input" all the data and the various scanf will take their part. So you could insert 123 234 + and it would be split in the three variables correctly.
Yes, scanf does not remove the newline, and you can't flush stdin, so how about this:
int num1;
char nleater;
printf("Enter a number:\n");
scanf("%d%c", &num1, &nleater);
or indeed this:
printf("Enter number sign number: ");
scanf("%d %c %d",&num1,&x,&num2);
printf("%d %c %d", num1, x, num2);
You can also try to use fflush, but it depends on the library implementation (stdio).
The C reference for it can be found here.
I'll test this a bit later on and update my post and say whether it worked.

Resources