Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I was having trouble with 2D array of string in C. Without the use of poi

ID: 3689919 • Letter: H

Question

Hello, I was having trouble with 2D array of string in C. Without the use of pointers or even the <string.h> library, how would a user be able to input, for example, first and last names of people? I've tried the nested for loops but it's inconsistent as to how many times I'm able to input names. This is the array I tried to use:

char name[number of people][max length of char];

for(i = 0; i < number of people; i++)

{

for(j = 0; j < max length of char; j++)

{

scanf("%s", &name[i][j]);

}

}

Explanation / Answer


//C program that uses 2d character array to store first and last
//name and print to console.
#include<stdio.h>
#include<conio.h>
int main()
{

   //Set constant for numPeople and maximum lenght of the name
   const int numPeople=5;
   const int maxLength=20;

   //Declare two character arrays to store first name and last name in
   //two different 2d-array of characters since 2d array of string stores
   //size of the array of max lenght
   char fName[numPeople][maxLength];
   char lName[numPeople][maxLength];

   //read first and last name for numPeople
   for(int i = 0; i < numPeople; i++)
   {
       printf("Enter first name, last name: ");
       //read first name and last name
       scanf("%s %s", &fName[i], &lName[i]);
   }

   for(int i = 0; i < numPeople; i++)
   {
       printf("%s %s ", fName[i],lName[i]);
   }

  
   //pause the program output on console
   getch();
   return 0;

}

------------------------------------------------------------------------------------------------------------------

Sample Ouptut:

Enter first name, last name: M John
Enter first name, last name: M kunal
Enter first name, last name: M Jeni
Enter first name, last name: H Singh
Enter first name, last name: N Milan
M John
M kunal
M Jeni
H Singh
N Milan

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote