C Program to Find the Largest/Longest String
Write a c program to accept n strings and print the string with maximum length i.e write a c program to find the largest/longest string.
Algorithm / Solution:
Here is the solution for C program to find the largest or longest string.- Start
- Use 2d string to store n arrays.
- Use for loop to loop through strings.
- Use strlen() function to check length of each string.
- Assign length of string with index 0 to Max.
- Compare Max with length of n'th string.
- Each time store index of corresponding string when Max changes.
- Display string with Max length.
- Stop.
C Program / Source Code :
Here is the source code of C program to find the largest or longest string.- /*Aim: Write a program to find the largest or longest string.*/
- #include<stdio.h>
- #include<string.h>
- #define size 100
- #define wsize 20
- void Longest_Word(char str[][20],int n); // Longest_Word Function Prototype
- void main()
- {
- char str[size][wsize];
- int i,count=0,n;
- printf("\n How many words to accept:- ");
- scanf("%d",&n);
- printf("\n Enter %d words:- \n \n",n);
- for(i=0;i<n;i++)
- scanf("%s",str[i]);
- Longest_Word(str,n);
- }
- // Longest_Word Function
- void Longest_Word(char str[][20],int n)
- {
- int i,Max,len1,c;
- Max=strlen(str[0]);
- for(i=1;i<n;i++)
- {
- len1=strlen(str[i]);
- if(len1>Max)
- {
- c=i;
- Max=len1;
- }
- }
- printf("\n The longest string among all is \"%s\" \n \n",str[c]);
- }
/* Output of above code:-
How many words to accept:- 5
Enter 5 words:-
Halo
I
Am
Master
Chief
The longest string among all is "Master"