Reputation: 33
I am writing a program for class that asks users to enter a the size of a 2D array and then has the user enter the values for the array. This is the code I have so far:
#include <stdio.h>
int main(void)
{
// Setup
int N, M;
int row = 0, col = 0;
printf("\n");
printf("This program counts occurences of digits 0 through 9 in an NxM array.\n");
printf("Enter the size of the array (Row Column): ");
scanf(" %d %d", &N, &M);
int array[N][M];
// Array Input
for (row = 0; row < N; row++)
{
printf("Enter row %d: ", row);
for (col = 0; col < M; col++);
{
scanf(" %d", &array[row][col]);
}
}
printf("\n");
return 0;
}
The issue that I am having when the program is compiled and the information is entered, the second and all following scanf() statements are skipped over or the whole second for loop is skipped over after the first line is entered. Here is an example of entered input:
This program counts occurences of digits 0 through 9 in an NxM array.
Enter the size of the array (Row Column): 2 6
Enter row 0: 0 1 2 3 4 5
Enter row 1:
And then the program ends entirely. I really have no idea why its being skipped over. I have tried altering how many spaces are in the scanf() statement but no matter what I change the same issue occurs. I am unsure if I am missing some stupid mistake I have made or if there is a bigger problem. I am pretty new at coding.
Upvotes: 2
Views: 205
Reputation: 1
for (col = 0; col < M; col++);
This is what you wrote inside the nest for loop. But the ";" simply means the end of code line and it will just run the for loop M times without doing anything.
Change it to
for (col = 0; col < M; col++)
Upvotes: 0
Reputation: 72271
You just have a stray semicolon. Try changing
for (col = 0; col < M; col++);
{
to:
for (col = 0; col < M; col++)
{
A for
introduces a statement which controls the very next statement, which could be a simple statement ending with a semicolon, another control statement, or a compound statement using {
braces }
. In your code, the semicolon on the same line as the for
keyword counts as an empty statement that has no effect. So that code will just increment the loop variable the appropriate number of times, and only after that move on to the next part.
Make sure you enable compiler warnings. (Both gcc and clang provide clear warnings that this code might not do what you meant.)
Upvotes: 5