Q:

C program to read n strings and print each string\'s length

belongs to collection: C String Programs

0

C program to read n strings and print each string's length

 

All Answers

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

Read N strings and print them with the length program in C language

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

int main()
{
	//Declare Variables
	char string[10][30]; //2D array for storing strings
	int i, n;

	//Get the maximum number of strings
	printf("Enter number of strings to input\n");
	scanf("%d", &n);

	//Read the string from user
	printf("Enter Strings one by one: \n");
	for(i=0; i< n ; i++) {
		scanf("%s",string[i]);
	}

	//Print the length of each string
	printf("The length of each string: \n");
	for(i=0; i< n ; i++) {
		//Print the string at current index
		printf("%s  ", string[i]);

		//Print the length using `strlen` function
		printf("%d\n", strlen(string[i]));
	}

	//Return to the system
	return 0;
}

Output

Enter number of strings to input
3
Enter Strings one by one: 
www.google.com
www.includehelp.com
www.duggu.org

The length of each string: 
www.google.com  14
www.includehelp.com  19
www.duggu.org  13

Let's break it down. Inside the main function, we have string array of characters. It is a 2D array that can store 10 strings with maximum 30 characters in each. Next we declare variables for loop and maximum user input strings.

After taking the value of n from user, we get input for each string one by one and using scanf() we store the characters in the array. In the second loop, for displaying the strings, we first print the string using printf() function. Notice that we have applied %s to specify to print characters of the string. Then, we print the length of corresponding string using strlen() function. Note that strlen() function returns an integer that is the length of the string. This is why we have specified %d specifier in printf function.

Finally, we return back to the system using return statement.

Hope you like the article, please share your thoughts.

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 copy one string to another and count ... >>
<< C program to eliminate/remove first character of e...