I am using code blocks and it says my code has no errors, Yet when I run the program it stopped working as I tried to give an input. Please keep in mind that my programming class has just started and I do not know much at all.
Here is the code to my program:
#include <stdio.h>
int main()
{
int num;
int num1, num2, num3, num4;
printf("Please insert a number here:\n");
scanf("%d\n", num);
printf("When value of variable num is 2,\n");
num1 = num +1;
printf("\nThe value of num after using num + 1 is: %d", num1);
num2 = num +=1;
printf("\nThe value of num after using num +=1 is: %d", num2);
num3 = ++num;
printf("\nThe value of num after using ++num is: %d", num3);
num4 = num++;
printf("\nThe value of num after using num++ is: %d", num4);
return 0;
}
and when I run the program it stopped working.
So, how can I fix this error?
Thanks in advance.
You have an error in the scanf call.
It should be
scanf("%d", &num);
Note the & before num. Scanf expects a pointer to the variable that have to be filled in with the input value.
Regarding your code and the question in your comment you should note that:
num1 = num +1;
num1 is num plus one
printf("\nThe value of num after using num + 1 is: %d", num1);
num2 = num +=1;
num is incremented by 1 then assigned to num2 with the new value
printf("\nThe value of num after using num +=1 is: %d", num2);
num3 = ++num;
num is again incremented by 1 and then assigned to num3
printf("\nThe value of num after using ++num is: %d", num3);
num4 = num++;
num at its actual value is assigned to num4 then num is incremented by 1 (the ++ operator is after the variable so the increment occurs after the assignment)
printf("\nThe value of num after using num++ is: %d", num4);
What you write inside your printf is not exact. You are not printing the value of num but num1, num2,...
As
num4 = num++;
num4 is different than num (it's num minus one)
Yeah, I think you still have to use
scanf("%d", &num);
even for int since it's still reading numeric data.
I think your answer changed halfway as well after ans2 because you used num2 = num +=1;. The += is like using num = num + 1;. Which would modify the value of num. So, ans3 and ans4 became different from what you expected. E.g. if you entered num as 2, ans 3 and ans4 would equal 4 instead of 3. If you want to get notified about this, you can put some print statements such as printf("\n Just printing value of num at this moment: %d",num); at various places in your code to observe the changes.
The way you are taking the input is wrong. You need to add an '&' sign before all the variables except for strings. So change the statement to scanf("%d",&num);
And also from reading your code,you want to initiate num1 if value of num=2.
printf("When value of variable num is 2,\n")
but your code does initiate it for any value of num. For avoiding that use an if loop as
printf("When value of variable num is 2,\n")
if(num==2)
{num1=num+1;}
else
{num1=0;
//or some other condition you wish
}
//and rest continues...
Related
So I'm coding in C and compiling with gcc, I was attempting to create a simple code to display the Fibonacci sequence, you can input the amount of digits of the sequence you'd like to be displayed. Instead of the expected 0 1 1 2 3 5 8 etc. I get 0 1 1 2 3 4 5 6 7 etc. And I can't figure out why, if I remove the second "while" from the code, it works as intended, but I don't understand why. Do variables lose their values if they're inside multiple "while"s? Please help me figure this out. Again I'm a beginner so try to keep it simple.
My code:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
num1 = num1 + num2;
printf("%d ", num1);
cont++;
while(cont < num - 2){
num2 = num1 + num2;
printf("%d ", num2);
cont++;
}
}
return 0;
}
The answer to your main question is no. Variables work like this: We declare a variable somewhere in our code. This variable has a name, a value (we either initialize it or it has a random value) and an address in memory. Your program has access to this variable within the block which this variable has been declared. In this particular example, because you declared the variable cont in the main function, that means wherever you change the value of this variable in the main function that change takes place.
The problem in your code is that the variable num1 doesn't change accordingly and, in the whole program, has the value 1. That is the reason why the values printed change by 1. A piece of code that would solve this problem is the following:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0,temp;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
temp = num2;
num2 = num1 + num2;
num1 = temp;
printf("%d ", num2);
cont++;
}
return 0;
}
This code just stores the value of num2 in a variable temp, so we don't lose the value of num2 because we want to modify it and the new value of variable num1 must be the old value of variable num2.
Good day, I was practicing about C and encounter a problem. The problem was this part or somewhere here.
for (ctr = num2; ctr <= num1; ctr++)
For example the output is
Enter the value of n1: 3
Enter the value of n2: 10
4 6 8 10
I would like it to start from the greatest 10 8 6 4 instead of the least 4 6 8 10.
#include <stdio.h>
int main(void) {
int num1, num2, ctr;
printf("Enter value of n1: ");
scanf("%d", &num2);
printf("Enter value of n2: ");
scanf("%d", &num1);
for (ctr = num2; ctr <= num1; ctr++) {
if (ctr % 2 == 0)
printf("%d ", ctr);
}
return 0;
}
In your for, simply replace
ctr = num2; ctr <= num1; ctr++
with
ctr = num1; ctr >= num2; ctr--
Your current for loop first initializes ctr to num2. As we go through the loop, ctr is incremented such that it's value becomes num2 + 1, then num2 + 2, ..., then num1 - 1, then num1. After ctr is num1, the statement in the loop is executed one last time, then ctr is incremented and it's value becomes num1 + 1, which exceeds num1, causing the loop to end.
ctr takes on the values in {num2, num2 + 1, ... , num1 - 1, num1, num1 + 1}. The statement in the loop is executed for each of the values ctr takes except for num1 + 1.
To reverse this, you initialize ctr to num1 and as we go through the loop, ctr should be decremented such that it's value becomes num1 - 1, then num1 - 2, ..., then num2. After ctr is num2, the statement in the loop is executed one last time, then ctr is decremented and it's value becomes num2 - 1, which is less than num2, causing the loop to end.
ctr takes on the values in {num1, num1 - 1, ..., num2 + 1, num2, num2 - 1}. The statement in the loop is executed for each of the values ctr takes except for num2 - 1.
Notice how in both loops, the statement is executed when ctr takes on a value in {num2, num2 + 1, ..., num1 - 1, num1}. The only difference is that in the first loop, ctr starts with num2, moving up to num1, whereas in the second loop, ctr starts at num1, moving down to num2.
After making the above change, your program should function as expected. In the code below, I have (1) made the suggested change above and (2) included checks for the return value of scanf. It is not necessary to make change (2), but it is typically good practice to check the return value of scanf. For reference (from C99 Standard)
The scanf function returns the value of the macro EOF if an input
failure occurs before any conversion. Otherwise, the scanf function
returns the number of input items assigned, which can be fewer than
provided for, or even zero, in the event of an early matching failure.
In our case, we expect a scanf call of the form scanf("%d", &num2) to return 1. A return value not equal to 1 means there was an error in scanf. Currently, our function simply stops the program if there is an error. However, using the feof and ferror functions, one would be able to know the type of error that occurred and the programmer can choose to make the program behave differently depending on the type of error. For brevity I have omitted the use of feof and ferror (both from <stdio.h>), though I thought I would mention them since we are on the topic of scanf errors.
It is also worth noting that you need to be careful that the user does not enter a number for num2 that is equal to INT_MIN (a macro defined in <limits.h>), the minimum value for an object of type int. While assigning INT_MIN to an int such as num2 is not by itself wrong, if num2 is INT_MIN, eventually ctr will equal num2, the statement in the loop will be executed one "last" time, but then num2 will be decremented which would mean trying to assign to num2 a number lower than the minimum value for an object of type int. That is, the program will have undefined behavior. The likely result of setting num2 to INT_MIN is that the loop will run forever.
Program
#include <stdio.h>
#include <stdlib.h>
int main(void){
int num1, num2, ctr;
printf("Enter value of n1: ");
if (scanf("%d", &num2) != 1) {
printf("scanf: error\n");
exit(EXIT_FAILURE);
}
printf("Enter value of n2: ");
if (scanf("%d", &num1) != 1) {
printf("scanf: error\n");
exit(EXIT_FAILURE);
}
for (ctr = num1; ctr >= num2; ctr--)
if (ctr % 2 == 0)
printf("%d ", ctr);
printf("\n");
return 0;
}
Example Session
Enter value of n1: 3
Enter value of n2: 10
10 8 6 4
I realize that my logic statements are not correct at the time, but I'm frustrated with the numbers not matching my inputs. The numbers usually come out as large integers (ex. 4128168, they're never the same for the integer entered). I'm new to programming in general and can't find much of an answer for this error. Any help is appreciated!
int num1;
int num2;
int num3;
int largest;
int second;
printf("Enter three numbers and I'll identify the largest and second largest.\n");
scanf_s("%d%d", &num1, &num2);
(largest = num1);
(second = 0);
if (num2 > largest)
(largest = num2);
else (num2 > second);
(second = num2);
scanf_s("%d", &num3);
(second = num2);
(largest = num3);
if (num3 > largest)
(largest = num3);
else (second = num3);
printf("The largest number is %d\n", &largest);
printf("The second largest number is %d\n", &second);
return 0;
}
printf("The largest number is %d\n", &largest);
printf("The second largest number is %d\n", &second);
You are printing the address, print the values:
printf("The largest number is %d\n", largest);
printf("The second largest number is %d\n", second);
First of all I recommend you first to read all the data and then to find the greatest and the middle number.
For a better code I would recommend you, also, to put all the data in an array and then to sort it. It would allow you to use your program with the desired number of input and output numbers.
Despite that, the solution that you want is the next:
-You should write:
second = num1; //too, initializing
if (num2 > largest)
largest = num2;
else
largest = num1;
Then the 3rd number.
Instead of:
if (num3 > largest)
(largest = num3);
else (second = num3);
You should write:
if (num3 > largest){ //now, comparing the new number with the actual largest
second = largest; //on this right order without overlapping 'largest'
largest = num3;
} else if(num3 > second)
second = num3;
Also, you should not write assign statements between parentheses ( ) because it can bring you to confuse conditional statements and assign statements like in your first "else".
Then, it is important to specify your variable names without "&" in your 'printf' calls.
Please, if I helped you, rate me.
Q. Write a program that reads a positive integer and then finds the smallest power of 2 that is greater than or equal to the number that was read. For example, if the program reads the value of 25, it should note that 32 = 2^5 is the smallest power of two greater than or equal to 25.
My approach:
**
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1, n;
int num2 = 2^n;
printf("Please type in num1: ");
scanf("%d", &num1);
n = 0;
while (num1 > num2)
{
n=n+1;
}
printf("The power value is %d", n);
return (0);
}
**
I am still a beginner so......
When your loop starts, num1 has some specific value, and num2 has another value.
Everytime through the loop, you do not change either value.
So the expression will stay true forever, and the loop will keep running forever, never exiting!
If you want the loop to end eventually, you must change the expression of the loop in some way!
You should modify the value of num1 or num2 inside your loop.
try this is algorithm is fast
int a, b = 1;
printf("Enter no \n");
scanf("%d",&a);
while (a >= b)
{
b = b << 1 ;
}
printf("%d",b);
I seem to have a problem with declarations screwing up my math. Any advice or suggestions are highly welcomed.
Here's the code:
int num1, num2, num3, num4, op, ;
op = ((1==num3) || (2==num4));
num3 = (num1 + num2);
num4 = (num1 * num2);
I've been trying lots of arrangements and re-assignments. A lot has compiled, but when 5 + 5 = 2659043, there's a problem...
Not sure what you're trying to do, but this is what your code is doing:
int num1, num2, num3, num4, op, ;
This line informs the C compiler that it needs to allocate space for 5 integers (num1, num2, num3, num4, op), these integers can now be used as variables until the scope expires. Not sure why you have the last ',' you might want to remove that.
op = ((1==num3) || (2==num4));
If num3 is 1, or num4 = 2, then set op to 1 (true). Otherwise, set op to 0 (false).
num3 = (num1 + num2);
Self-explanatory: Add num1 and num2 and put the sum into num3.
num4 = (num1 * num2);
Self explanatory: Multiply num1 and num2 and put the product into num4.
Immediately I see an issue with your program. You are using these variables, but have not initialized them to anything. For example, how is there supposed to be a sum of (num1 + num2) if num1 and num2 do not have a value. Try this:
#include <stdio.h>
int main()
{
int num1, num2, sum;
num1 = 1;
num2 = 2;
sum = num1 + num2;
printf("sum = %d\n", sum);
}
Okay... there's a lot wrong here, but I'll go through what you posted in the comments point by point.
#include <stdio.h>
int main() {
/*Declare the active agents */
int num1=0, num2=0, num3=0, num4=0, op = 1 || 2 ;
You initialize your variables to zero here, except op, which you set to 1 (1 || 2, which is the boolean or, will return 1 (true), so as a result you set op to 1).
num3 = (num1 + num2);
num4 = (num1 * num2);
Here you set num3 and num4 both to zero, since num1 + num2 is 0 + 0 and num1 * num2 is 0 * 0. You want to move this down after your scanf's.
/* Information Extraction Method */
printf("YO MOFO!!!Press a number or hit the dirt!!\n");
scanf("%d", &num1);
printf("Since you didn't hit the dirt, how about another number?\n");
scanf("%d", &num2);
/* Menu (AKA Input */
printf("If you want to add, press 1 ,\nIf you want to multiply, press 2 ... \n\n ");
scanf ("%d", &op);
These printf's and scanf's are good. Good job.
/* PROCESS */
if (op = 1) {num3;};
if (op = 2) {num4;};
Three things here. First, op = 1 is assigning 1 to op. Same with op = 2. You want op == 1 and op == 2 as you have below. The result of this will be that op will always be 2 after these if statements.
The second thing is that, while a valid statement, num3; by itself won't do anything.
Finally, while it doesn't hurt anything, you don't need semicolons after your closing curly braces.
/* OutPut */
if (op == 1) {
printf("Alone, a toothpick is weak, but as part of a sum, your answer is:\n%d"), &num3;
};
if (op == 2) {
printf("Multiplied as a sum of it's parts, your answer is:\n%d"), &num4;
};
Here you're printing out the address of num3 and num4 instead of their values. This is part of the reason you're seeing large numbers that don't make sense, it's the address of num3 and num4 in memory. Only scanf needs the ampersand (&), printf does not. Also, as it stands, the actual value of these will always be 0 since your calculations are done before you get the numbers from the user.
EDIT: Actually, it turns out the reason you aren't getting the right numbers here is that you aren't passing the number to printf at all. You have num3 and num4 outside of the parentheses. There still shouldn't be an ampersand before the variable name, but it should look like this printf("Multiplied... is:\n%d", num4); Notice how num4 is inside the parentheses.
printf("\n\n\n\nMath frum da hud..... Yo. \n\n\nLOL\n >;]");
/* End Of Program */
return 0;
}
Edit: For clarity's sake, I've re-written it in a manner such that it should work the way you intended.
#include <stdio.h>
int main() {
/*Declare the active agents */
int num1=0, num2=0, num3=0, num4=0, op = 0;
/* Information Extraction Method */
printf("YO MOFO!!!Press a number or hit the dirt!!\n");
scanf("%d", &num1);
printf("Since you didn't hit the dirt, how about another number?\n");
scanf("%d", &num2);
num3 = (num1 + num2);
num4 = (num1 * num2);
/* Menu (AKA Input */
printf("If you want to add, press 1 ,\nIf you want to multiply, press 2 ... \n\n ");
scanf ("%d", &op);
/* OutPut */
if (op == 1) {
printf("Alone, a toothpick is weak, but as part of a sum, your answer is:\n%d", num3);
};
if (op == 2) {
printf("Multiplied as a sum of it's parts, your answer is:\n%d", num4);
};
printf("\n\n\n\nMath frum da hud..... Yo. \n\n\nLOL\n >;]");
/* End Of Program */
return 0;
}
HTH.
You did not initialize the variables, so their values are undefined (and probably not 0). You should initialize (like that, for example):
int num1 = 0, num2 = 0, num3 = 0, num4 = 0, op = 0 ;