Q:

C program to create and print array of strings

belongs to collection: C String Programs

0

C program to create and print array of strings

Learn: How to create, read and print an array of strings? This program will demonstrate usages of array of strings in C programming language.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to create, read and print an array of strings in C

#include <stdio.h>

#define MAX_STRINGS	10
#define STRING_LENGTH	50

int main()
{
	//declaration
	char strings[MAX_STRINGS][STRING_LENGTH];
	int loop,n;
	
	printf("Enter total number of strings: ");
	scanf("%d",&n);
	
	printf("Enter strings...\n");
	for(loop=0; loop<n; loop++)
	{
		printf("String [%d] ? ",loop+1);
		
		getchar(); //read & ignore extra character (NULL)
		//read string with spaces
		scanf("%[^\n]s",strings[loop]);
	}
	
	printf("\nStrings are...\n");
	for(loop=0; loop<n; loop++)
	{
		printf("[%2d]: %s\n",loop+1,strings[loop]);
	}
		
	return 0;
}

Output

Enter total number of strings: 5
Enter strings...
String [1] ? Hello friends, How are you?
String [2] ? I hope, you all are fine!
String [3] ? By the way, what are you doing?
String [4] ? I hope you're doing good.
String [5] ? Bye Bye!!! 

Strings are...
[ 1]: Hello friends, How are you? 
[ 2]: I hope, you all are fine! 
[ 3]: By the way, what are you doing? 
[ 4]: I hope you're doing good. 
[ 5]: Bye Bye!!!

Here, MAX_STRINGS is a Macro that define total number of maximum strings and STRING_LENGTH to define total number of characters in a string.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to compare two strings using pointers... >>