0
Program to print largest and smallest string in C++
I am looking for a c++ program that reads three strings and prints the longest and smallest string.
8 Answers
+ 9
Share your attempt first
+ 3
Amal Babu
You are printing A[i] where I =4, not in your array range. What you need to print is A[max] where you need to find maximum size string position in array.. Like
int min=0,max=0;
maxi=strlen(A[0]);
for(i=0;i<3;i++)
if(strlen(A[i])>maxi)
max=i; //store position index
cout<<"The largest string is:"<<A[max]<<endl;
Edit : update maxi value also...
Next for minimum is same. Try and reply if you don't get..
+ 2
string a,b,c;
cin>>a>>b>>c;
cout<<"Longest:";
a.size()>b.size()?a.size()>c.size()?cout<<a:cout<<c:b.size()>c.size()?cout<<b:cout<<c;
cout<<"\nShortest:";
a.size()<b.size()?a.size()<c.size()?cout<<a:cout<<c:b.size()<c.size()?cout<<b:cout<<c;
+ 1
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char * str[3] = {"Hello","Planet","Mars"};
if(strlen(str[0]) > strlen(str[1]) && strlen(str[0]) > strlen(str[2]))
cout << str[0];
else if(strlen(str[1]) > strlen(str[2]))
cout << str[1];
else
cout << str[2];
if(strlen(str[0]) < strlen(str[1]) && strlen(str[0]) < strlen(str[2]))
cout << str[0];
else if(strlen(str[1]) < strlen(str[2]))
cout << str[1];
else
cout << str[2];
return 0;
}
+ 1
Amal Babu
OK. Update maxi value also....
Now check by this:
mini=maxi=strlen(A[0]);
for(i=0;i<3;i++)
{
if((int)strlen(A[i])>maxi){
maxi=strlen(A[i]);
max=i;
}
}
cout<<"The largest string is:"<<A[max]<<endl;
0
https://code.sololearn.com/cU3F31NB0R0t/?ref=app
where is the issue in the code? please help me!
0
Jayakrishnađźđł Thanks for your help.
It is my modified code.but if the largest number is the first input & smallest is the second,the output is wrong....!
https://code.sololearn.com/cjEoPvPD3U5n/?ref=app
0
Jayakrishnađźđł ok..Now it is working for all i/p. Thanks.