Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Yes or No while loop for a 2d array doesn't print array in C

I’m new to c and don’t really understand how 2d arrays work. When the code is executed it prompts for me to enter a course and then when the loop is broken the print statement doesn’t show what I inputted.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main()

   {

   char courses[60][100];
   char ans ='y';
   int  i=0;
   int p,j;

   while (ans == 'y'){
   printf("Enter course:\n");
   for (p=0;p<j;p++)
   scanf("%s", &courses[p]);
   getchar(); 

   i++;

  printf("Would you like to enter another course? (y or n) \n"); 
  ans = getchar();

 }
 printf("courses are %s",courses[p]);
 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int main()
{
    char courses[60][100];
    char ans ='y';
    size_t  i = 0;

    do
    {
        printf("Enter course:\n");
        scanf("%s", &courses[i]);
        getchar(); 
        i++;
        printf("Would you like to enter another course? (y or n) \n"); 
        ans = getchar();
    }while(ans == 'y');
    for(size_t p = 0; p < i; p++)
        printf("courses are %s\n",courses[p]);
}

https://godbolt.org/z/EKqEq8aos

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading