(C) Trouble with adding integers [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having troubles with a simple addition calculator.
After I put in the first number, the program crashes.
#include <stdio.h>
int main()
{
printf("Addition calculator\n");
int num1,num2;
printf("Enter the first number: ");
scanf(" %d",num1);
printf("\nEnter the second number: ");
scanf(" %d",num2);
int sol;
sol=num1+num2;
printf("The solution is %d", sol);
return(0);
}

scanf(" %d", &num1);
scanf expects an address of a variable, so it can change its value. You're passing in the value of num1 as an address, which has a very very very high probability to be somewhere your program is not allowed to write.
Same for num2.
I love analogies, so...
Think about this code:
int recordASeven(int x) {
x = 7;
}
int main() {
int y = 0;
recordASeven(y);
printf("y is %d\n", y);
}
This prints 0. Why? It's like this: You have a piece of paper in your locker, with "0" written on it. You copy the "0" carefully onto another piece of paper, give it to a friend and say "write down 7 here instead". He does so, then throws paper away. You look into your locker, and there's your own paper with "0" on it. Because you're passing your friend a copy of your paper and not your own paper, he can't change your own original. Same with functions in C - they can't ever change the variables they get passed in. So scanf can't ever modify the variables directly.
int recordASevenBetter(int *x) {
*x = 7;
}
int main() {
int y = 0;
recordASeven(&y);
printf("y is %d\n", y);
}
Now here you take a blank piece of paper, give him the combination that will open your locker, and give that to your friend, saying "go to my locker, write down 7 on the paper in there". When you go and inspect the paper in your locker later, sure enough, there's "7" on it. In C speak, "&y" will give you the location of where the value of y is ("pointer"), so that anything can change it; "*x" will access the value in the location specified by the value of x.
int recordASevenAndFailMiserably(int *x) {
*x = 7;
}
int main() {
int y = 0;
recordASeven(y);
printf("y is %d\n", y);
}
Finally, here's your problem: you give your friend a copy of your "0", and tell him it's your locker combination. When he goes to open your locker, he gets frustrated, trashes your room and pees on the floor.
In this case, the compiler can detect the disparity, since there is a clear mismatch between the declared and the provided types, and the compiler will refuse to do it. But scanf uses variadic argument list, which means the declaration does not list the parameter types. It will be the responsibility of scanf to decypher the format and interpret the bag of bytes it gets as something sensible. And the compiler can only stand by and watch shaking its head (when you enable warnings) as you lie to scanf about what you're giving it.

Please change it to &num1 and &num2 as mentioned by Amandan. You have to pass the address of the variable.

Related

C programming - Finding the necessary number in the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).

Program with array to find a sum in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I was thinking of a code to find the sum of numbers.
So i wrote bellow code :
#include <stdio.h>
#include <math.h>
int main()
{
int n,i,s=0,a[100];
printf("enter number of numbers");
scanf("%d",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
s=0;
for (i=1;i<=n;i++)
{s=s+a[i];}
printf("sum is%d\n",s);
}
But in the output it shows segmentation error . I.e.
So whats the mistake?
So this line:
scanf("%d",n);
should be replaced by
scanf("%d",&n);
Explanation:
scanf() reads data from stdin according to format and store data in the location pointed by next additional argument. this case, format is %d means we want to read an integer number and this integer number will be stored in the location of n. The & operator is to get the location of a variable in C.
Use this :
scanf("%d",&n);
The reason :
You MUST put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it.
Examples :
scanf("%d %d", &a, &b);
printf("%d %d", a, b);
As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value.
But in case of printf function as we are only going to print the values of the variables in output console, there are no changes going to be made in variable a and b’s values. So it is not required to send their addresses.

scanf reading totally different number [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Here is all the code I have in Visual Studio:
#include <stdio.h>
int main (void) {
int input;
puts("There are 10 seats available on the next flight");
puts("Where would you like to reserve a seat?");
puts("Please type 1 for First Class");
puts("Please type 2 for Economy");
scanf("%d", &input);
if (input == 1) {
printf("You Typed %d\n", &input);
}
if (input == 2) {
printf("You Typed %d\n", &input);
}
}
But when I run the program I get output that says:
There are 10 seats available on the next flight
Where would you like to reserve a seat?
Please type 1 for First Class
Please type 2 for Economy
1
You Typed 6159588
Press any key to continue . . .
I get a totally random number every time. Because of this I can't seem to get anything I write after the input to work. Why is this happening?
What you get printed out is the address of the variable input, not its value! This is because printf accepts its arguments by value - simply because they can be passed like that. What you need thus is
printf("%d", input); // without the ampersand!
scanf - in contrast - is fundamentally different. It is going to place a value into a variable you provide to it - and therefore needs a pointer.
Simple example:
int n = 7;
void myPrintf(int v)
{
++v;
}
void myScanf(int* v)
{
++*v;
}
int main(int argc, char* argv[])
{
myPrintf(n); // n passed by value, cannot be modified
// (but printf does not intend to, either!)
myScanf(&n); // n will be incremented!
// (scanf does modify, thus needs a pointer)
return 0;
}
Back to the roots, though: There is still a fundamental problem: You are passing a pointer, but evaluate it as an int. If sizes of both differ - which is the case on modern 64-bit hardware - you are in trouble. The value then is read from the stack with different size and part of your address actually gets discarded (pointer addresses require "%p" format specifier, assuring that the apprpriate number of bytes is read from stack - in case of modern systems 8 vs. 4 for int).

How do you get C to produce output from number inputted in code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
What code do you have to include to get C to produce an output from number inputted into the system.
#include <stdio.h>
int main()
{
int z;
printf("Please enter a number");
return 0;
}
I want the programme to work out a mathematical equation to the number that the user enters, for example if I enter 5 I want it to work out the exponent 2 of 1 up to that integer input.
You can use scanf function to get input from user like this:
#include <stdio.h>
int main()
{
int z;
printf("Please enter a number");
scanf("%d", &z);
// do your calculations on z
printf("Result: %d", z);
return 0;
}
You can use the scanf function.
For a number (or in your case an integer specifically) the line is
scanf("%d", &z);
where the %d specifies that its reading in an integer and the &z is a pointer to your integer variable z.
Information here: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
I'm guessing you're new to C programming, so once you get the basics down I would suggest familiarizing yourself with pointers as they are a critical aspect of the language. Some useful resource here using google-fu : https://www.tutorialspoint.com/cprogramming/c_pointers.htm

Can't get a number guessing game to work in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Tried to write a program in C to say the amount of times you guessed the right number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, searchNumber, Number, rightGuess;
rightGuess = 0;
printf("Give your number: ");
scanf("%d",&searchNumber);
printf("\n\n Give 10 numbers: ");
for(i=1;i<=9;i++){
scanf("%d \n",&Number);
if(Number == searchNumber){
rightGuess++;
}
}
printf("You guessed the number %d times",&rightGuess);
return 0;
}
However every time I run it, it says I guessed the number 6356736 times. Even though I only entered a number 0 times. Any help?
Maybe you made a mistake in printf().
If there is a variable named var, &var means the memory address where variable var is. Maybe the number 6356736 you saw in your program is the memory address, not the value in variable var.
You will have to change this line in order to print the value of variable rightGuess
printf("You guessed the number %d times", &rightGuess);
To this line.
printf("You guessed the number %d times", rightGuess);
Your call to printf ought to be
printf("You guessed the number %d times", rightGuess);
i.e. don't pass a pointer to rightGuess in correspondence to the %d format specifier. Currently the program behaviour is undefined! (It could well be outputting the address of rightGuess which accounts for the large number - but don't ever rely on that; you need to use %p to output pointer addresses.)

Resources