Home > Software design >  why my outer loop is not repeating itself?
why my outer loop is not repeating itself?

Time:03-10

#include<stdio.h>
void printarr( int arr , int a,int b){
  for(int z=0;z<a;z  ){
    for(int x=0;x<b;x  ){
        printf("the marks of student %d in subject %d and %d is :%d\n",z 1 , 
        x 1 , x 2 , arr);
        
    }
}
}
int main(){
int n_students = 5;
int n_sub = 2;

int marks[5][2];
for (int i=0; i<n_students; i  ){
    for (int j=0; j<n_sub; j  ){
        printf("enter the marks of student %d in subject %d\n", i 1, j 1);
        scanf("%d", marks[i][j]);
    }
}
printarr(marks , 5 , 2);
return 0;

i am getting to put only two times and the outer loop is not repeating itself please explain me in simple terms , i am just learning this launguage complete begineer.

CodePudding user response:

1.When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified.

void printarr( int arr , int a,int b){ --->void printarr( int arr [][2], int a,int b){

2.When reading array element in scanf you have missed &

scanf("%d", marks[i][j]);--->scanf("%d", &marks[i][j]);

3.When Printing array elements in printf you have to specify the index.

arr ---> arr[i][j]

#include<stdio.h>
void printarr( int arr [][2], int a,int b){
  for(int z=0;z<a;z  ){
    for(int x=0;x<b;x  ){
        printf("the marks of student %d in subject %d  is :%d\n",z 1,x 1,arr[z][x]);
        
    }
}
}
int main(){
int n_students = 5;
int n_sub = 2;

int marks[5][2];
for (int i=0; i<n_students; i  ){
    for (int j=0; j<n_sub; j  ){
        printf("enter the marks of student %d in subject %d\n", i 1, j 1);
        scanf("%d", &marks[i][j]);
    }
}
printarr(marks, 5 , 2);
return 0;
}

CodePudding user response:

You want this: (explanation in comments)

#include <stdio.h>

#include<stdio.h>

void printarr(int a, int b, int arr[a][b]) { // pass an array, not an int,
                                             //  and a and b must be before arr
  for (int z = 0; z < a; z  ) {
    for (int x = 0; x < b; x  ) {
      printf("the marks of student %d in subject %d and %d is :%d\n", z   1,
        x   1, x   2, arr[z][x]);  // use arr[x][z] here. arr obviously dons' make sense
    }
  }
}

int main() {
  int n_students = 5;
  int n_sub = 2;

  int marks[5][2];
  for (int i = 0; i < n_students; i  ) {
    for (int j = 0; j < n_sub; j  ) {
      printf("enter the marks of student %d in subject %d\n", i   1, j   1);
      scanf("%d", &marks[i][j]);   // you forgot the &
    }
  }
  printarr(5, 2, marks);   // you need to pass the size beforen the array
  return 0;                // read the documentation about VLAs
}
  • Related