ADVERTISEMENT
ADVERTISEMENT

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.

We have posted programs on strings in C language, now in this post we are going to discuss about array of strings in C.

How to declare array of strings?

char variable_name[ROWS][COLS];

Here,
ROW - Total number of maximum strings
COLS - Total number of characters in a string

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.

C String Programs »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.