Recursive function C multiplying by 4 problem - c

I'm supposed to write a program in C for school where I multiply by 4 but I can't get it to work. When I type 2 I get 20, when I type 3 it's 84, when I type 4 it's 340 and so on, why is that?
#include <stdio.h>
int multi(int i)
{
if (i == 1) {
return 4;
}
if (i == 0) {
return 0;
}
if (i > 1) {
return (multi(i-1)*4)+4;
}
}
int main()
{
int i;
printf("type a numer for multiplication by 4\n");
scanf("%d",&i);
printf("%d * 4 is %d\n",i, multi(i));
}

Multiplying X by Y is adding X Y number of times.
X * Y = X + X + X ...Y times
So change
return (multi(i-1)*4)+4;
to
return multi(i-1) + 4;
and it will work as intended for multiplication by 4.
However, if you want to raise X to the power of Y, you have to multiply X Y number of times.
X to the power of Y = X * X * X...Y times
In this case, there are a couple of more changes you have to make to your code which I leave to you as an exercise.

Related

Reversing last n digits of an Integer in C

I need to write a program that takes 2 digits(X and n) and then prints X with last n digits of X reversed.
For example
Input: 12345 3
Output: 12543
Input: 523 2
Output: 532
I already wrote a control mechanism for checking n is greater or equal than the number of digits of X
For example if inputs are 6343 and 7, program prints that inputs should be changed and takes input again.
My main problem is I couldn't find an algorithm for reversing last n digits. I can reverse any int with this code
int X, r = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
while (X != 0)
{
r = r * 10;
r = r + n%10;
X = X/10;
}
printf("Reverse of the number = %d", r);
But I couldn't figure how two reverse just last digits. Can you give me any idea for that?
I couldn't figure how to reverse just last digits
Separate the number using pow(10,n) - see later code.
unsigned reverse_last_digits(unsigned x, unsigned n) {
unsigned pow10 = powu(10, n);
unsigned lower = x%pow10;
unsigned upper = x - lower;
return upper + reverseu(lower, n);
}
Create a loop that extracts the least-significant-digit (%10) and builds up another integer by applying that digit. (y = y*10 + new_digit)
unsigned reverseu(unsigned x, unsigned n) {
unsigned y = 0;
while (n-- > 0) {
y = y*10 + x%10;
x /= 10;
}
return y;
}
For integer type problems, consider integer helper functions and avoid floating point functions like pow() as they may provide only an approximate results. Easy enough to code an integer pow().
unsigned powu(unsigned x, unsigned expo) {
unsigned y = 1;
while (expo > 0) {
if (expo & 1) {
y = x * y;
}
expo >>= 1;
x *= x;
}
return y;
}
Test
int main() {
printf("%u\n", reverse_last_digits(12345, 3));
printf("%u\n", reverse_last_digits(523, 2));
printf("%u\n", reverse_last_digits(42001, 3));
printf("%u\n", reverse_last_digits(1, 2));
}
Output
12543
532
42100
10
Code uses unsigned rather than int to avoid undefined behavior (UB) on int overflow.
It is an easy one.
1. let say the number you want to reverse is curr_number;
2. Now, the places you want to reverse is x;
(remember to verify that x must be less than the number of digit of curr_number);
3. now, just take a temp integer and store curr_number / pow(10,x) ('/' = divide and pow(10,x) is 10 to the power x)
4. now, take a second number temp2, which will store curr_number-(temp * pow(10,x) )
5. reverse this temp2 (using your function)
6. now, answer = (temp * pow(10,x) ) + (temp2) //(note temp2 is reversed)
example with steps:
curr_number = 1234567
places you want to reverse is 3
temp = 1234567 / (10^3) i.e (1234567/1000) = 1234 (because it is int type)
temp2 = 1234567 - (1234*10^3) i.e 1234567 - 1234000 = 567
reverse(567) = 765
answer = (1234 * 10^3) + 765 = 1234765
Create two variables
lastn which stores the last n digits (345)
r which stores the reversed last n digits (543)
Subtract lastn from the original number (12345 - 345 = 12000)
Add r to the above number (12000 + 543 = 12543)
int c = 0; // count number of digits
int original = x;
int lastn = 0;
while (x != 0 && c < n) {
r = r * 10;
r = r + x % 10;
lastn += (x % 10) * pow(10, c);
x = x / 10;
c++;
}
printf("reversed: %d\n", original - lastn + r);
In case you don't have problems using char, you can do this
#include <stdio.h>
#include <string.h>
#define SIZE 10
int main() {
char n[SIZE]; // the Number;
int x; // number of last digits of n to reverse
int len; // number of digits of n
scanf("%s%d", n, &x);
len = strlen(n);
for(int i = 0; i < len; i++) {
i < len - x ? printf("%c", n[i]) : printf("%c", n[2*len -1 - i - x]);
}
return 0;
}
If you want you can make the program more readable by splitting the for in two
for(int i = 0; i < len - x; i++) {
printf("%c", n[i]);
}
for(int i = len-1; i >= len - x; i--) {
printf("%c", n[i]);
}
Note: the program won't work if n > x (i.e. if you want to swap more digits than you got)

how to find which integer no is maximim out of given numbers

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y, z, result, max;
printf("\nInput the first integer: ");
scanf("%d", &x);
printf("\nInput the second integer: ");
scanf("%d", &y);
printf("\nInput the third integer: ");
scanf("%d", &z);
result=(x+y+abs(x-y))/2;
max=(result+z+abs(result-z))/2;
printf("\nMaximum value of three integers: %d", max);
printf("\n");
return 0;
}
unable to understand the formula:
result=(x+y+abs(x-y))/2;
max=(result+z+abs(result-z))/2;
Looking at this expression:
(x+y+abs(x-y))/2
If x => y, then abs(x-y) is the same as x-y. That gives us: (x+y+(x-y))/2 == (x+x+y-y)/2 == 2x/2 == x.
If x < y, then abs(x-y) is the same as y-x. That gives us: (x+y+(y-x))/2 == (x-x+y+y)/2 == 2y/2 == y.
So the above expression evaluates to the larger of x and y without using any conditionals. The following expression (result+z+abs(result-z))/2 does the same thing with z and the max of x and y.
Note however that this method has the potential to cause overflow. The cleanest way to do this is to explicitly compare:
if (x >= y && x >= z) {
max = x;
} else if (y >= x && y >= z) {
max = y;
} else {
max = z;
}
then how to solveit – Ujjwal Bhardwaj 5 mins ago
int max(int a, int b, int c)
{
return a > b ? (a > c ? a : c) : (b > c ? b : c);
}
One way to visualize it is:
Imagine you have 2 trees. One is 16 meter tall and the other is 20 meter tall.
You look at their average, which is the “midpoint” and is 18 meter tall. Now, what’s their difference? 4 meter.
You take 18 and add half of that difference, is 20 (the max). Likewise, you can take the average and minus half of the difference and it is the min.
So,
average plus half the difference
= (x + y) / 2 + abs(x - y) / 2
= (x + y + abs(x - y)) / 2
The following line of code returns the value of whichever is greater, x or y.
result = (x + y + abs(x - y)) / 2;
By adding the absolute value of the difference between x and yto the sum of x and y you essentially get 2 times the larger number. For example, if x=5 and y=20 then abs(x - y) = 15. So 5 + 20 + 15 = 40 which is 2 times the larger number. Divide that by 2 and you have determined larger value. Then by repeating the formula with the result above and z you have calculated the largest of the three.

how to multiply values from table in c

I am new to programming and have been asked to create a table with 3 variables x, y and z.
To create x and y, I was asked to use a for loops and have does so. For z, I have to multiply the values of x and y but I'm not entirely sure how to work out z and how to place it in a table.
Please help. I have given an example of how my results should be.
What I've done so far:
int x, y, z;
for (x = 1; x <= 4; x++)
printf(" %d ", x);
for (y = 2; y <= 5; y++)
printf(" %d ", y);
return 0;
The data structure should be not complex
int matrix[3][5];
for(i=0; i<5;i++){
matrix[0][i]=i+1;
matrix[1][i]=i+2;
matrix[2][i]=matrix[0][i]*matrix[1][i];
}
You can change to char matrix to include your headers
You could see that course
https://www.edx.org/course/c-programming-pointers-and-memory-management
If the task is only to print a table, like the one posted, all you need is one loop:
#include <stdio.h>
int main(void)
{
// print the header of the table
puts("======================\n x y z = x * y\n----------------------");
for ( int x = 1; // initialize 'x' with the first value in the table
x <= 5; // the last value shown is 5. 'x < 6' would do the same
++x ) // increment the value after each row is printed
{
int y = x + 1; // 'y' goes from 2 to 6
int z = x * y; // 'z' is the product of 'x' and 'y'
// print each row of the table, assigning a width to each column,
// numbers are right justified
printf("%3d %3d %3d\n", x, y, z);
}
puts("======================");
return 0;
}
The output beeing
======================
x y z = x * y
----------------------
1 2 2
2 3 6
3 4 12
4 5 20
5 6 30
======================
int x[] = {1,2,3,4,5,.....} <-----for storing values of x
int y[] = {2,3,4,5,6,....} <------for storing values of y
Take another array for storing z values.
So now we have z[i]=x[i]*y[i] where i=0,1,2,........n also y[i]=x[i]+1
Use a loop to calculate and print the result.

3-digit integer number program won't execute

Yes, this is a basic C coding homework problem. No, I am not just looking for someone to do it for me. Considering that this is my first programming class, I'm not surprised that I can't get it to work, and I'm certain there is plenty wrong with it. I just want some help pointing out the problems in my code and the things that are missing so that I can fix them on my own.
Homework Question:
Write a program to read ONLY one integer number (your input must be
one 3 digit number from 100 to 999), and to think of a number as
being ABC (where A, B, and C are the 3 digits of a number). Now,
form the number to become ABC, BCA, and CAB, then find out the
remainder of these three numbers when they are divided by 11.
Assume remainders would respectively be X, Y, and Z and add them
up as X+Y, Y+Z, and Z+X. Now if any of these summations is odd
number, increase it by 11 if the summation plus 11 is less than 20,
otherwise decrease the summation by 11 (this summation operation
must be positive number but less than 20). Finally, divide each
of the sums in half. Now, print out all the resulting digits.
My Code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declare all variables
int OrigNumber;
int x, y, z;
int number;
number = x, y, z;
int sum;
//
printf("Input a three digit number");
//
int c;
c = OrigNumber %10;
//
int b;
b=((OrigNumber - c) % 100)/10;
//
int a;
a = (OrigNumber - (b + c))/100;
//
int abc, bca, cab;
abc = (a*100) + (10*b) + c;
bca = (10*b) + c + (a*100);
cab = c + (a*100) + (10*b);
//
if((number % 2) == 1)
{
if(number + 11 < 20)
number += 11;
else if((100 - 11 > 0) && (100 - 11 < 20))
number -= 11;
}
//
x = abc/11;
y = bca/11;
z = cab/11;
//
sum = (x + y),
(y + z),
(z + x);
}
To start with, you need to read the input. Start with a prompt that includes a carriage return:
printf("Input a three digit number: \n");
Since it's a three digit number, you could add the following line to read the input:
scanf("%3d", &OrigNumber);
The next bit of code works quite well until you get to your if (number % 2) which is meaningless since you didn't really define number - well, you did, but the line
number = x, y, z;
does NOT do what you think it does. If you add
printf("So far I have abc=%d, bca=%d, cab=%d\n", abc, bca, cab);
after you first read in the number and computed those three, you will see you are well on your way.
Note that
number = x, y, z;
Uses a thing called the "comma operator". All the things (a,b,c) are "evaluated" but their values are not returned. At any rate, where you have that line, you didn't yet assign a value to x,y and z.
Is that enough to get your started?
update now that you have had a few hours to mull this over, here are a few more pointers.
Your computation of abc, cab, bca makes no sense. I will show you just one of them:
cab = c*100 + a*10 + b;
Next you need to compute each of x, y and z. Again, here is one of the three:
y = bca%11;
Now you have to make the sums - I call them xy, yz, and zx. Just one of them:
zx = z + x;
Next, to deal with the instruction: "Now if any of these summations is odd number, increase it by 11 if the summation plus 11 is less than 20, otherwise decrease the summation by 11:
if(xy % 2 == 1) {
if(xy + 11 < 20) xy += 11; else xy -= 11;
}
use similar code for all three sums. Then "divide by 2":
xy /= 2;
repeat as needed.
Finally, print out the result:
printf("xy: %d, yz: %d, zx: %d\n", xy, yz, zx);
The amazing thing is that if you did this right, you get the original numbers back...
You could make the code more compact by using an array of values and looping through it - rather than repeating the code snippets I wrote above with different variables. But I suspect that is well outside the scope of what you are expected to know at this point.
Can you take it from here?
#include <stdio.h>
int main()
{
//Declare all variables
int OrigNumber;
int a, b, c;
int abc, bca, cab;
int x, y, z;
int xplusy , yplusz, xplusz;
printf(" A program to read ONLY one integer number.\n Input must be one 3 digit number from 100 to 999 : ");
scanf("%d", &OrigNumber); // Get input from console
if(OrigNumber > 999 || OrigNumber < 100) {
printf("Invalid number. Quiting program. This is error handling. Important while learning programming.");
return 0;
}
c = OrigNumber %10; // digit at unit's place
b=((OrigNumber) % 100)/10; //digit at the ten's place
a = (OrigNumber)/100; //digit at the 100's place. Note: 734/100 = 7. NOT 7.34.
printf("\n Three numbers say A,B, C : %d, %d , %d ", a, b, c);
abc = a*100 + 10*b + c;
bca = 100*b + 10*c + a;
cab = c*100 + a*10 + b;
printf("\n Three numbers say ABC, BCA, CAB : %d, %d , %d ", abc, bca, cab);
x = abc % 11; // Reminder when divided by 11.
y = bca % 11;
z = cab % 11;
printf("\n Three numbers say X, Y, Z : %d, %d , %d ", x, y, z);
xplusy = x + y; // Adding reminders two at a time.
yplusz = y + z;
xplusz = x + z;
printf("\n Three numbers X+Y, Y+Z, X+Z : %d, %d , %d ", xplusy, yplusz, xplusz);
if((xplusy % 2) == 1) {
if(xplusy + 11 < 20)
xplusy += 11;
else
xplusy -= 11;
}
if((yplusz % 2) == 1) {
if(yplusz + 11 < 20)
yplusz += 11;
else
yplusz -= 11;
}
if((xplusz % 2) == 1) {
if(xplusz + 11 < 20)
xplusz += 11;
else
xplusz -= 11;
}
xplusy /= 2; // Finally, divide each of the sum in half.
yplusz /= 2;
xplusz /= 2;
printf("\n Now print out all the resulting digits : %d, %d , %d \n", xplusy, yplusz, xplusz);
return 0;
}
int abc, bca, cab;
abc = (a*100) + (10*b) + c;
bca = (10*b) + c + (a*100);
cab = c + (a*100) + (10*b);
I suggest printing out the numbers at this point in the code.
printf( "%d %d %d", abc, bca, cab );
I think you'll see one of the problems you need to solve.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int n, a, b, c, abc, bca, cab, x, y, z, p, q, r;
scanf("%d", &n);
c=n%10;
b=(n/10)%10;
a=n/100;
abc=a*100+b*10+c;
bca=b*100+c*10+a;
cab=c*100+a*10+b;
x=abc%11;
y=bca%11;
z=cab%11;
p=x+y;
q=y+z;
r=z+x;
return 0;
}
Now if any of these summations is odd number, increase it by 11 if the
summation plus 11 is less than 20, otherwise decrease the summation by
11 (this summation operation must be positive number but less than
20). Finally, divide each of the sums in half. Now, print out all the
resulting digits.
i didnt get the final part, can you explain it more clearly?

Find the sum of all the even-valued terms in the sequence which do not exceed four million

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
I made the program but my answer doesnt match.
#include<stdio.h>
int main()
{
long unsigned int i,sum=0,x=1,y=2,num;
for(i=0;i<4000000;i++)
{
num=x+y;
if(i%2==0)
sum+=num;
x=y;
y=num;
}
printf("%lu\n",sum);
getchar();
return 0;
}
Three problems I can see:
You should start with x = 1, y = 1, since otherwise you skip the first even-valued Fibonacci;
Your loop condition should be (x + y) <= 4000000
You should test num for even-ness, not i.
(After these changes, it should be obvious that you can omit i entirely, and therefore replace the for loop with a while loop)
In your code you find the sum of fibonacci numbers with even index, not even numbers themselves + you search the first 4000000 numbers in sequence, not the numbers with values <= 4000000. Your code should be something like
while ( y < 4000000){
...
if (y %2 == 0)
sum += y;
}
I've made a minimal set of corrections and now get the right answer. You may learn more by reading this (after all, it was yours, to start with) than by me rambling on about it...
#include <stdio.h>
#define LIMIT (4 * 1000 * 1000)
int main() {
long unsigned int sum = 0, x = 1, y = 2, num;
while (x <= LIMIT) {
if ((x & 1) == 0 && x <= LIMIT)
sum += x;
num = x + y;
x = y;
y = num;
}
printf("%lu\n", sum);
return 0;
}
I think the following line
if(i%2==0)
might instead be
if( num % 2 == 0)
On further thinking, I think you don't actually need the variable i. Instead, your loop can be controlled by num as:
enum { LIMIT = 4 * 1000 * 1000 };
num = x + y;
while( num <= LIMIT ) {
print num inside the loop, for debugging
for(i=0;i<4000000;i++)
{
num=x+y;
printf("num is %lu\n", num); /* DEBUGGING */
if(i%2==0)
sum+=num;
x=y;
y=num;
}

Resources