How to make this a nested For Loop? - c

I made a code wherein I should print the square and cube of the first 10 counting numbers but I used for loops. What I'm looking for is how to print the same output but using nested (for) statement.
Here is my code:
#include<stdio.h>
int main()
{
int x;
printf("x\tx*x\tx*x*x\t\n");
for(x=1; x<=10; x++)
printf("%d\t%d\t%d\n", x, x*x, x*x*x);
return 0;
}

With these few items to print, a nested for loop seems unecessary, but if you really want one, it could look like this:
for(x = 1; x <= 10; x++) {
for(int i = 0, X = x; i < 3; ++i, X *= x) {
printf("%d\t", X);
}
putchar('\n');
}
Demo

Here I have added the solution of this code along with its output using the nested for loop

Related

C function to print 2D array of chars

Im trying to learn C, surely using the hard way and cant figure out this one error, could someone help? :-)
#include<stdio.h>
#include <stdlib.h>
#define max_X 15
#define max_Y 15
int x, y;
char Array[max_Y][max_X];
void displayArray(void){
for (y = 0; y < max_Y; y++) {
for (x = 0; x < max_X; x++) {
printf("%c",Array[y][x]);
}
printf("\n");
}
}
int main(void){
for (y = 0; y < max_Y; y++) {
for (x = 0; x < max_X; x++) {
Array[y][x] = '.';
}
}
displayArray;
getchar;
return(0);
}
Im trying to print out char array containing just dot characters using function. When i run it, there is just blank cmd and return value 0. I keep getting warnings about statements with no effect on these two lines:
displayArray;
getchar;
Can someone help? or give me a link to similar one where i can find answer to my problem? I was looking around but couldn't find anything i could compare to mine and understand at least a little.
You need to use parentheses even when the function you're using takes no arguments. So,
displayArray;
getchar;
should be:
displayArray();
getchar();
Also, return isn't a function. It's a keyword, so you can do:
return 0;
Use displayArray();
You should not call function like this displayArray;you can use this while providing address of function to function pointer.

Strange error with a For loop in C

int main(void)
{
const char * attributeNames = "StrDexConIntWisCha";
int characterValues[7] = {0};
int characterBonuses[7] = {0};
characterStats(characterValues);
}
void characterStats(int * characterValues)
{
int numberOfDice = 4; int diceType = 6;
int x = 1;//because characterValues[0] is level.
printf("What is your level? > ");
scanf("%d",&characterValues[0]);
printf("Current Level [%d]", characterValues[0]);
printf("Rolling stats.\n");
for(x; x <= numberOfDice; x++)
{
characterValues[x] = diceRoll(diceType);//rolling a d6
}
}
int diceRoll(int diceType)
{
int numberOfDice = 4;
int x,y,z = 0;
int diceResult, finalValue, lowestResult = 0;
int diceRoll[4] = {0};
for(x; x <= numberOfDice; x++)
{
printf("%d", diceRoll[x]);
}
}
I'm trying to create a function that will roll a 6-sided dice, 4 times, for a character generator for dungeons and dragons. The last for loop in diceRoll, doesn't appear to execute, it just skips it over and I don't understand why. At the moment, I'm just testing to see if everything works before adding in the rand().
int x,y,z = 0;
Here you only initialized z to 0, leaving x and y uninitialized, and then in the for loop:
for(x; x <= numberOfDice; x++)
Again, x is not initialized.
You should always initialize your loop counter in the for loop:
for(x=0; x<numberOfDice; x++)
and too, notice I used < not <=; a loop from 0 will always do n iterations from 0 for <n (using <= will do n+1). Looping from 0 to n-1 is idiomatic in all C-like languages since it tends to match things like indexes an an array being iterated, or pointer manipulations, which are all 0-based.
either make
int x=0,y,z=0;
or make
for(x = 0; x <= numberOfDice; x++)

Is there a O(n) way to draw a 2-D array grid instead of O(n²) in C?

Is there a O(n) way to draw a 2-D array grid instead of O(n²) in C? For instance, I'm wondering if there's a way to use one for loop instead of two. I always felt like there was a way, but thought I'd turn it over to you...
ARRAY2D grid;
void ShowGrid(void)
{
int x, y;
for (y = 0; y < grid.height; y++)
{
for (x = 0; x < grid.width; x++)
{
printf("%d", arr2_get(&grid, x, y));
}
printf("\n");
}
printf("\n");
}
You normally study what happens as you increase the number of elements.
If that's the case here, the code you posted is O(N), not O(N2).
If the grid has 100 elements, the number of times printf will be called will be proportional to 100 (O(N)), not proportional to 10,000 (O(N2)).
If on the other handle you were studying what happens as you increase the number of rows or columns, visiting all the elements will be at least O(R*C) since you have R*C elements.
Note that you can flatten the two loops, but it doesn't change the complexity in the least:
void ShowGrid()
{
const int H = grid.height;
const int W = grid.width;
int n;
for (n = 0; n < H*W; ++n)
{
int y = n / W;
int x = n % W;
printf("%d", arr2_get(&grid, x, y));
printf("\n") if x == W-1;
}
}
The following code uses a single for loop:
void ShowGrid(void)
{
int i;
for (i = 0; i < grid.width * grid.height; i++)
{
int x = i % grid.width;
int y = i / grid.width;
printf("%d", arr2_get(&grid, x, y));
if (x == grid.width - 1)
printf("\n");
}
printf("\n");
}
Another approach without multiplication or division:
void ShowGrid(void)
{
int x = 0;
int y = 0;
while (y < grid.height) {
printf("%d", arr2_get(&grid, x, y));
x += 1;
if (x == grid.width) {
printf("\n");
x = 0;
y += 1;
}
}
printf("\n");
}
But the time complexity is obviously the same as with two for loops.
There are ways to structure your 2d matrix as a 1 dimensional array or your loop variables, which will allow you to use 1 loop. However, this will not reduce the run time complexity at all.
In your situation, you are always going to have to access each cell of the 2d grid.
If you define N = Width*Height. Your code is already O(n). If you define N = Width = Height, then your code is O(N^2). Neither of these can be improved.

Nested for loops seem to execute separately for some reason

I am attempting to process a two-dimensional array in C. I tried two nested for loops, but it seems that the two loops execute separately. I expect that the inside loop loops eight times for each loop of the outside loop, resulting in eight times the number of outside loops being the total number of loops.
As a simplified test, I tried this:
#include <stdio.h>
int main() {
int x = 0;
int y = 0;
for (; x < 7; x++, printf("(%d,%d)", x, y)) {
for (; y < 8; y++, printf("(%d,%d)", x, y)) { }
}
}
This resulted in these results:
(0,1)(0,2)(0,3)(0,4)(0,5)(0,6)(0,7)(0,8)(1,8)(2,8)(3,8)(4,8)(5,8)(6,8)
Could somebody please explain to me why this might be happening? Thanks.
The reason is simple: you do not reinitialize the y variable in inner loop: when it reaches 8, it stays this way and the inner loop does not execute any more. Change your code to:
#include <stdio.h>
int main() {
for (x=0; x < 7; x++, printf("(%d,%d)", x, y)) {
for (y = 0; y < 8; y++, printf("(%d,%d)", x, y)) { }
}
}

For loop output in C

I am trying to understand the for loop better. I have the following variables:
x = 1
y = 10
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
This is what I have, but it is not quite doing the trick:
int x = 1;
int y = 10;
for (int i = 0; i < y; i++)
{
x *= 2;
}
printf("%d\n", x);
Do I need another variable to do this?
It looks fine to me. If you want it to print at each iteration, you need to move the printf into the loop.
Also, your code will only work in C99 or with GCC's default extensions since you have int i inside the for loop.
If you want it to display a running count then you should place printf inside the for-loop, so it gets executed with each iteration.
Do I need another variable to do this?
No. You could actually remove a variable - y. It is unneeded and you can specify 10 directly in the loop's conditional:
int i = 0;
int x = 1;
for (i = 0; i < 10; i++)
{
x *= 2;
printf("%d\n", x);
}
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
Your example contradicts your requirement. Incrementing an integer and doubling it would look produce 1, 4, 6, 8, 10, 12, 14...n. They are simply multiples of two. Your example produces powers of two, i.e.,
int x;
for( x = 0; x < 10; ++x )
{
printf("%d\n", pow(2, x) );
}
for (int i = 0; i < y; i++)
{
x *= 2;
printf("%d\n", x);
}
Think you want the printf statement inside the for loop... between the { and the }.
int x = 1;
int y = 10;
int i = 0;
int main() {
for(i = 0; i < y; i++) {
x *= 2;
printf("%d\n", x);
}
return 0;
}
Output:
2
4
8
16
32
64
128
256
512
1024
your answer contradict with your source code,if you want to print 1,2,4,8,16,... you will get first element 2, because you are multiplying every iteration 2 times than its value, you do not need to use extra variable,moreover you can remove y,put directly 10 and use printf statement inside {}.hope it will help
if you know that you have to increment it for only 10 times. Then why to use extra variable ? use this....
for(x = 1; x<=1024; x*=2)
{
printf("%d ",x);
}

Resources