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.
Read N strings and print them with the length program in C language
Output
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