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.
Related
I'm having trouble with outputting a number pattern from recursion. I have correctly outputted some of the right numbers, but I can't get it to output the negative number and some of the missing numbers. This is the example input and output for my assignment:
Ex. If the input is:
12
3
the output is:
12 9 6 3 0 -3 0 3 6 9 12
This is my code:
int PrintNumPattern(int num1, int num2) {
printf("%d ", num1);
if (num1 <= 0) {
return 0;
}
else {
PrintNumPattern(num1 - num2, num2);
}
printf("%d ", num1);
}
int main(void) {
int num1;
int num2;
scanf("%d", &num1);
scanf("%d", &num2);
PrintNumPattern(num1, num2);
}
This is the output I keep getting from my code:
12 9 6 3 0 3 6 9 12
Your code just needs a few tweaks to provide the spirit of what you are after. Following is your code with some minor revisions.
#include <stdio.h>
#include <stdlib.h>
void PrintNumPattern(int num1, int num2) {
if (num1 < 0) {
num2 = num2 * -1; /* Reverse the sign to start incrementing back up */
}
else {
printf("%d ", num1); /* Put this here to skip a redundant repeated print */
PrintNumPattern(num1 - num2, num2);
}
printf("%d ", num1);
}
int main(void) {
int num1;
int num2;
scanf("%d", &num1);
scanf("%d", &num2);
PrintNumPattern(num1, num2);
printf("\n");
}
Here are the highlights.
When testing that the value has gone negative, there just needs to be a check for a negative number and not zero value. When that condition does occur, the second parameter needs to be changed to a negative number in order to effectively start adding instead of subtracting.
The initial "printf" statement is moved to be inside the "else" block so that it only prints out the negative number once.
In testing out these changes, the following is the output I saw on my terminal.
#Una:~/C_Programs/Console/Patterns/bin/Release$ ./Patterns
12
3
12 9 6 3 0 -3 0 3 6 9 12
#Una:~/C_Programs/Console/Patterns/bin/Release$ ./Patterns
22
4
22 18 14 10 6 2 -2 2 6 10 14 18 22
Experiment with that and see if that gives you what you want.
The posted code can't print -3 because it can't reach that value in the recursive calls
printf("%d ", num1);
if (num1 <= 0) { // As soon as num1 reaches 0, it stops the recursion
return 0;
}
else {
PrintNumPattern(num1 - num2, num2);
}
printf("%d ", num1); // This is skipped too.
To obtain the expected output, the recursion should be stop only when num1 becomes negative:
void PrintNumPattern(int num1, int num2)
{
printf("%d ", num1);
if (num1 >= 0)
{
PrintNumPattern(num1 - num2, num2);
printf("%d ", num1);
}
}
Testable here.
Note that I changed the return type to void. In the posted code the returned value is never used and not all the paths in the function have a return statement.
By rearranging #Bob's function, this is (imho) somewhat easier to think about. Full credit to #Bob...
When num1 >= 0, print it, and then go deeper... Eventually the bottom is reached, and the recursion unwinds through the 2nd printf()...
void PrintNumPattern(int num1, int num2) {
if (num1 >= 0) {
printf("%d ", num1);
PrintNumPattern(num1 - num2, num2);
// This is not an actual instruction location,
// but (conceptually) 'here' is where execution resumes
// as the recursion 'unwinds'...
// Obvious why num1 is printed both going down and coming up
}
printf("%d ", num1);
}
int main(void) {
PrintNumPattern( 12, 3 );
printf("\n");
return 0;
}
I've just started to learn coding
#include <stdio.h>
int main(void)
{
int i=0, x=0;
for (i=1; i<=100; i++) {
x++;
if (x%5==0 || x%3==0)
printf("The numbers are : %d\n", &x);
}
return 0;
}
so I'm trying to print all the integers <=100 that are divisible by either 3 or 5.
In the line:
printf("the numbers are : %d", &x);
printf is expecting an integer because of the %d format specifier, you have given it the address of an integer, thats what the & means, address of x. To fix this give printf what it desires, an int:
printf("the numbers are : %d", x);
The ampersand (&) operator returns the address of a variable, which isn't what you want - you just want the value. Also, note that you don't need two variables (x and i) - you can just use the loop's counter:
printf("The numbers are:\n");
for (i = 1; i <= 100; i++) {
if (i % 5 == 0 || i % 3 == 0) {
printf("%d ", i);
}
}
Removing the & will eliminate the error. You may also want to move the "the numbers are:" statement outisde of the loop so the text does not print each time through the loop.
I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}
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...
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 ;