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;
}
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.
I have started an intro to programming course that uses the C language and we have an assignment to make a program that takes a 5 digit number from the user such as 12345 and it prints it out as 1 2 3 4 5.
I tried to google around for help but all the answers given used code way too complicated for my understanding considering the course just started and we have only learned printf and scanf, if and switch statements and while and for loops.
I tried putting all the numbers given into separate int variables which made the program stop and then tried to put them into chars but the testing program said it was wrong since we are supposed to use int.
Is there a simple way to do this?
EDIT:
What I have tried:
#include <stdio.h>
int main(void) {
int num1,
num2,
num3,
num4,
num5;
printf("Give 5 digit number > ");
scanf("%d%d%d%d%d", &num1, &num2, &num3, &num4, &num5);
printf("Seperated number is %d %d %d %d %d", num1, num2, num3, num4, num5);
return (0);
}
Also tried that code but with char variable type but that wasn't allowed it has to be int.
The testing program gives an expected output which for 00001 is Given number 1 seperated is 0 0 0 0 1 or for -12321 is Given number -12321 seperated is -1 -2 -3 -2 -1
You can read user input into a char array using scanf.
Then using for loop you can loop through each char (1,2,3,4,5)
Use printf in the loop to print from array and a space. printf("%c ", input_from_user[i]);
I suppose the point here is understanding how C stores things. You're reading in characters (that is a set of 8-byte values that are commonly displayed as letters) and converting each one to an integer (commonly a 32-bit value that stores a number)
So you want to read the input using scanf to get a character string of your 5 digits, then use a for loop to go over each one, reading a single character from the string and converting it into an integer variable. then printf that variable plus a space, and move on to repeat the next digit.
If you read the digits in one by one then its even easier as you only need the for loop to read, convert, and print each digit as its read.
According to the question, you would be given a number of 5 digits and then you have to print the digits of that number as well.
So, in your program, you have taken five digits individually as input, to me it seems wrong. I am giving my solution below:
#include <stdio.h>
int main(void)
{
int num,idx=0,i=0;
int arr[5]; // for storing the five digits;
scanf("%d",&num);
while(num){ //loop will terminate when the num = 0
int digit = num%10;
num = num/10;
arr[idx] = digit;
idx++;
}
//Printing from the last, as the digit are stored in reverse order.
for(int i=4;i>=0;i--){
printf("%d ",arr[i]);
}
return 0;
}
I don't really understand the purpose of this exercise. If you are learning C, the last function you should learn is scanf. It boggles the mind that so many people teach it early. Try very hard not to use scanf at all until you understand the language well enough to realize that you probably never need it. That said, I suppose the point of the exercise is to do something like:
#include <stdio.h>
int
main(void)
{
unsigned num;
char buf[6];
printf("Give 5 digit number > ");
if( scanf("%u", &num) != 1 || num > 99999 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
printf("Separated number is");
snprintf(buf, sizeof buf, "%d", num);
for( int i = 0; buf[i]; i++ ) {
printf(" %c", buf[i]);
}
putchar('\n');
return 0;
}
Although likely beyond OP's stage, code can use recursion to print the value from most significant to least.
#include <stdio.h>
void print_digit(int n, int depth) {
if (depth > 1) print_digit(n/10, depth - 1); // print "left" digits first
printf(" %d", n%10);
}
void print_5(int n) {
// To do: checking for correct spelling
printf("Given number %d seperated", n); // or separated
print_digit(n, 5);
printf("\n");
}
int main(void)
{
print_5(1);
print_5(-12321);
return 0;
}
Output
Given number 1 seperated 0 0 0 0 1
Given number -12321 seperated -1 -2 -3 -2 -1
You could use your approach by limiting the number of bytes you read for each number:
#include <stdio.h>
int main(void) {
int num1, num2, num3, num4, num5;
printf("Give 5 digit number > ");
if (scanf("%1d%1d%1d%1d%1d", &num1, &num2,&num3, &num4, &num5) == 5) {
printf("Separated number is %d %d %d %d %d\n", num1, num2, num3, num4, num5);
}
return 0;
}
Note however that this is probably not what you are expected to do. You should instead read a single number and decompose it into its five digits:
#include <stdio.h>
int main(void) {
int num;
printf("Give 5 digit number > ");
if (scanf("%d", &num) == 1 && num >= 10000 && num <= 99999) {
printf("Separated number is %d %d %d %d %d\n",
num / 10000, num / 1000 % 10, num / 100 % 10, num / 10 % 10, num % 10);
}
return 0;
}
So im answering an assignment question in c and for some reason when I run it in codeblocks or even C lion I get a different and wrong answer than when I run it on Repl.it online. I copied and pasted the code so there are no errors or differences. The question itself requires u to enter a 12 digit ISBN number then calculate the product by takin (1st number) X 1 + (second number) X 3 and so on then taking the mod of the sum and subtracting from 10 and calculate the last digit.
Ex the number 978030640615
should give the product as 93 and last digit as 7
Below is my code for code blocks:
#include <stdio.h>
int main(void) {
long num1 = 0;
int num2 =0;
int sum =0;
int n = 0;
printf("Enter number :\n");
scanf("%ld",&num1);
for (int i= 0 ; i<12 ; i++){
num2 = 0;
num2 = num1%10;
num1 = num1/10;
n +=1;
if (n%2 == 0){
num2 = num2*1;
//printf("%d" , num3);
}
else {
num2 = num2*3;
//printf("%d", num2);
}
sum = num2+sum;
}
printf("\n" "%d", sum);
num2 = sum%10;
num2= 10 - num2;
printf("\n" "%d", num2);
}
and the output is
-63 and 13
My code for Repl.it is the same as the one from codeblocks I copied and pasted it but i get 93 and 7 as the answer
I need to take the numbers listed in the two files "numbers1.txt" and "numbers2.txt" (where the numbers are listed in ascending order) and move them to a file named "output.txt" where they are arranged in ascending order.
Here is what I have so far:
void appendToOutput(FILE *numFile1, FILE *numFile2, FILE *outputFile)
{
int num1 = 0;
int num2 = 0;
do {
fscanf(numFile1, "%d", &num1);
fscanf(numFile2, "%d", &num2);
while ((num1 < num2) && !feof(numFile1))
{
fprintf(outputFile, "%d\n", num1);
fscanf(numFile1, "%d", &num1);
}
while ((num2 < num1) && !feof(numFile2))
{
fprintf(outputFile, "%d\n", num2);
fscanf(numFile2, "%d", &num2);
}
if (num1 == num2)
{
fprintf(outputFile, "%d\n%d\n", num1, num2);
}
} while (!feof(numFile1) || !feof(numFile2));
return;
}
my files look like the following:
numbers1.txt
1
2
3
4
5
6
7
8
9
10
11
12
numbers2.txt:
2
4
6
8
10
12
14
16
18
20
22
24
The issue I am having is that the output file ends up looking like this:
output.txt
1
2
2
3
4
4
5
6
6
7
8
8
9
10
10
11
12
12
So my issue is that the program is not continuing to read/write numbers from numbers2.txt even though it has not yet hit the end of it's file. I've looked through it and I can't seem to find out why it's stopping, so help would be appreciated!
There are a few problems with the current code
Initialization of the 2 numbers should be performed before the main loop
Use of feof() here
Test of strict < insteaf of <= (could lock your algo)
Keep reading a file if the other one becomes empty
Regarding 2., fscanf returns a number >0 if it could read the number, so you can test this instead of checking feof (that says that EOF (a stop condition) happened before, and this might trigger one more unwanted iteration).
Suggested fixed code:
int read1 = fscanf(numFile1, "%d", &num1);
int read2 = fscanf(numFile2, "%d", &num2);
while (read1 > 0 || read2 > 0) {
while (read1 > 0 && (read2<=0 || num1 <= num2))
{
fprintf(outputFile, "%d\n", num1);
read1 = fscanf(numFile1, "%d", &num1);
}
while (read2 > 0 && (read1<=0 || num2 <= num1))
{
fprintf(outputFile, "%d\n", num2);
read2 = fscanf(numFile2, "%d", &num2);
}
}
Further explanations
readX<=0 || numY <= numX addresses 4.
readX = fscanf(...) addresses2.
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 ;