Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can I use another for loop here? 1

Status
Not open for further replies.

Rmcta

Technical User
Nov 1, 2002
478
US
I am learning C and just for practice I am trying to create a table.
1) Must scanf always be right after a printf to work?
2) Instead of &MyArray[x][y],&MyArray[x][y+1], &MyArray[x][y+2] I wish to use a loop so that my values are saved into the correct columns which are from 0 to N. Can that be done?


#include <stdio.h>
#define N 3

main()
{
int MyArray[N][N];
int x=0,y=0;
for (x=0; x<N; x++)
{printf("Enter %d numbers for row %d: ", N, x);
scanf("%d %d %d", &MyArray[x][y],&MyArray[x][y+1], &MyArray[x][y+2] );}

 
scanf does not need to be after printf to work, but there needs to be user input, you are using printf to prompt the user for input, but scanf doesn't require it.

Yes, you can use another for loop these are called nested loops.

Code:
    int MyArray[N][N];
    int x,y;

    for (x=0; x<N; x++)
    {printf("Enter %d numbers for row %d: ", N, x);
      for (y = 0; y < N; y++)
        scanf("%d", &MyArray[x][y]);
    }

Hope this helps.
 
Thank you for your help. I actually wrote the same code but did not work because I didn't use the braces.

Is it a rule that if I have a nested loop I must use braces for the system to know what it is?
 
You must use braces if there is more than one statement in the for loop. For example, in the following code you wouldn't need braces because each for loop only contains 1 statement. The single statment of the first for loop is the 2nd for loop and the single statement of the 2nd for loop is the scanf statement.

Code:
for (x=0; x<N; x++)
  for (y = 0; y < N; y++)
    scanf("%d", &MyArray[x][y]);

In the code from the previous post, however, there are 2 statments in the first for loop: the printf statement and the 2nd for loop, so the first for loop must have braces.

Hope that's clear.

Good luck.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top