×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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.

In this example, we have used the following C language topics that you should learn:

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.