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.
Related
#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.
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.
can any one help me understanding the output of this code?
#include <stdio.h>
int main()
{
int x = 1, y = 1;
for(; y; printf("%d %d \n", x, y))
{
y = x++ <= 5;
}
return 0;
}
the output is:
2 1
3 1
4 1
5 1
6 1
7 0
A for loop in the form of
for (a; b; c)
{
d;
}
is equivalent to
{
a;
while (b)
{
d;
c;
}
}
Now if we take your loop
for(; y; printf("%d %d \n", x, y))
{
y = x++ <= 5;
}
It is equivalent to
{
// Nothing
// Loop while y is non-zero
while (y)
{
// Check if x is less than or equal to 5, assign that result to y
// Then increase x by one
y = x++ <= 5;
printf("%d %d \n", x, y);
}
}
Now it should hopefully be easier to understand what's going on.
Also: Remember that for boolean results (like what you get as result from a comparison), true is equal to 1, and false is equal to 0.
The code is an obfuscated, ugly version of this:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int x = 1;
bool y = true;
while(y == true)
{
y = (x++ <= 5);
printf("%d %d \n", x, (int)y);
}
return 0;
}
y in the original code serves as a boolean. Back in the ancient days, there were no boolean type in C so it was common to use int instead. The expression y = x++ <= 5; evaluates to 0 or 1, which is equivalent to false or true.
Note:
While the C language allows all manner of crazy stuff, you should never write for loops as in the original code. De facto standard is to write for loops like this:
The first clause of a for loop shall only contain iterator initialization.
The second clause should only contain the loop condition.
The third clause should only contain a change of the loop iterator, such as for example an increment (like i++).
A for loop that doesn't follow the above industry standard rules is badly written, no excuses.
The statement y = x++ <= 5; sets y to 1 if x is less than or equal to 5, or to 0 if x is greater than 5. It then increments x. The loop stops when y is equal to 0, that is, on the iteration after x was incremented above 5. Then it runs the printf() statement on each iteration.
You wouldn’t normally see a loop switch the loop condition and the loop body that way. This seems to be a pathological example of how it’s technically legal. You shouldn’t imitate it.
y is 1 (true) as long as x <= 5 and x increases every iteration.
Rewrite your code:
for (int x = 1, y = 1; y; y = x <= 5, x++) {
printf("%d %d\n", x, y);
}
or using while
int x = 1;
int y = 1;
while (y) {
printf("%d %d\n", x, y);
x++;
y = x <= 5;
}
The first component of the for loop is empty; which means values of variables haven't changed. The condition in the for loop is y. Which means that the loop will run till the condition y is true; which means till the value of y is anything other than 0.
When the value of y becomes equal to 0; the condition will become false and the loop will stop iterating.
Then comes the block execution...
y = x++ <= 5;
Here first the condition x <= 5 is checked. Note that x++ is post increment and so the value of x will be incremented after the execution of the statement. So, if the value of x was 1 before increment; it will check 1 <= 5 and not 2 <= 5 and after the execution of the statement; the value will become 2.
After that comes the third component of for loop which is the increment part. Here,
printf("%d %d \n", x, y)
simply prints x and y.
So, what happens is; when the loop starts, both x and y are 1.
The statement
y = x++ <= 5;
is encountered, thus the condition x++ <= 5 is checked, where x is 1. Since the condition is true; the value of y will be 1 and x will be incremented to 2. The same thing continues.... when x will be equal to 5, x++ <= 5 will check 5 <= 5 and the condition will be true and x will be incremented to 6. Now when it goes in the loop the next time; the condition will be false and y will instead be equal to 0. Thus, now when the loop checks the condition y, the condition will be false and thus the control will flow out of the loop and thus you see the result.
I built and dumped this code in IDA since I understand assembly better :D
This code is a bit obfuscated so here will be the normal version of it:
#include <stdio.h>
int x = 1;
int y = 1;
while(y != 0) {
if(x++ <= 5)
{
y = 1;
} else {
y = 0;
}
printf("%d %d\n",x,y);
}
that for loop in the source:
for(; y; printf("%d %d \n", x, y))
checks if y is a non-zero value and if it is, it will print the string you want. In the body of the loop, the result of the comparison (0 or 1) will be copied to y and the check continues.
Precedence of operator <= is higher than the operator =.
So, the statement:
y = x++ <= 5;
is equivalent to:
y = (x++ <= 5)
Because of post-increment ++ operator, the value of x returned first and then x is incremented.
The initial value of both x and yis 1.
Since y is 1, the for loop condition evaluates to true and the statement in the for loop block executed. But in the for loop of your code, in place of loop iterator update statement you have printf() statement which is printing the value of x and y after executing the loop body statements. The flow goes like this:
1 <= 5 evaluate to 1 which is assigned to y and after this x is 2,
Output : 2 1
2 <= 5 evaluate to 1 which is assigned to y and after this x is 3,
Output : 3 1
3 <= 5 evaluate to 1 which is assigned to y and after this x is 4,
Output : 4 1
4 <= 5 evaluate to 1 which is assigned to y and after this x is 5,
Output : 5 1
5 <= 5 evaluate to 1 which is assigned to y and after this x is 6,
Output : 6 1
6 <= 5 evaluate to 0 which is assigned to y and after this x is 7,
Output : 7 0
Now the value y is 0 and in your code, the for loop condition is y so the loop condition evaluates as false and loop exits.
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?
I am not understanding for loop statement and expression following it. Please do help me understand.
#include<stdio.h>
int main()
{
int x = 1;
int y = 1;
for( ; y ; printf("%d %d\n",x,y))
y = x++ <= 5;
return 0;
}
And the output I got
2 1
3 1
4 1
5 1
6 1
7 0
y = x++ <= 5; ==> y = (x++ <= 5); ==> first compare x with 5 to check whether x is small then or equals to 5 or not. Result of (x++ <= 5) is either 1, 0 assigned to y,
As x becomes > 5, (x++ <= 5) becomes 0 so y = 0 and condition false and loop break,
Basically the for syntax is:
for(StartCondition; Test; PostLoopOperation) DoWhileTestPasses;
In this case:
StartCondition == None
Test == (y != 0)
PostLoopOperation == do some printing
DoWhileTestPasses == set y to zero if x > 5 otherwise to non-zero THEN increment x.
Which is all rather bad practice because it is confusing.
Would be better written as:
int x=0;
int y=0;
for(y=0; y = (x <= 6); x++)
{
printff("%d %d\n",x,y);
}
return(0);
In y = x++ <= 5;, y stores the value that is output by the condition x++ <= 5 (here x++ is post increment). If the condition is true then y = 1 else y = 0.
for( ; y ; printf("%d %d\n",x,y))
In the for loop you are printing the values of x and y after executing the for loop body.
Initialize your variables:
int x = 1; int y = 1;
There are 3 statements for the for loop: -1. Initialize, 2. Condition, 3. Iteration:increment/decrement
In your case, you did not provide the initialize condition, however, you have the part of condition and incrementation. I do not think your for loop is used in the correct way.
You should swap the part of incrementation with your body like this:
for(; y; y = x++ <= 5;)
printf("%d %d\n", x, y)
First, you check whether the condition is true or not, y is true or not. Then, you print x and y out. Then, the part of incrementation is executed, x++ <= 5 or not. The result is assigned to y. It does so until your condition is false, y == false.
NOTE: For the good programming, you should enclose your body with a curly braces.
similar to this
int x = 1;
for( int y = 1; y!=0 ; )
{
if (x++ <= 5)
{
y = 1;
}
else
{
y = 0;
}
printf("%d %d\n",x,y);
}
Perhaps this slightly transformed (but functionally equal) code will help:
int x = 1;
int y = 1;
while (y) {
y = (x <= 5);
x = x + 1;
printf("%d %d\n", x, y)
}