chore(CPlusPlus): display longest name (#517)

pull/512/head^2
Samruddhi Ghodake 2021-10-05 23:36:14 +05:30 committed by GitHub
parent b25fc547bf
commit 6416651300
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 0 deletions

View File

@ -101,6 +101,7 @@
6. [Remove occurrences from string](Strings/remove-occurrences.cpp) 6. [Remove occurrences from string](Strings/remove-occurrences.cpp)
7. [Delete alternate characters in a string](Strings/delete-alternate-characters.cpp) 7. [Delete alternate characters in a string](Strings/delete-alternate-characters.cpp)
8. [Print first letter of every word](Strings/print-first-letter.cpp) 8. [Print first letter of every word](Strings/print-first-letter.cpp)
9. [Display longest name in a string array](Strings/longest-name.cpp)
## Trees ## Trees

View File

@ -0,0 +1,46 @@
/*
Description: Given a list of names, display the longest name.
Approach: To use length() method for every array element
Keeping the index of maximum length string in max variable
Time Complexity: O(n)
*/
#include <iostream>
using namespace std;
//function starts
string longest(string names[], int n) { //storing the index of max-length string
int max = 0;
for (int i = 1; i < n; i++) {
if (names[i].length() > names[max].length()) {
max = i;
}
}
//returning the string at max index
return names[max];
}
//main starts
int main() {
//names array
string names[] = {
"hi",
"hello",
"helloall",
"helloeveryone"
};
//calculating size of the array
int n = sizeof(names) / sizeof(names[0]);
cout << "The longest string in the array is: " << longest(names, n);
return 0;
}
/*
names=["hi","hello","helloall","helloeveryone"]
Output:
The longest string in the array is: helloeveryone
*/