From 6416651300fa4e282ca63a75ed7d6b00ae7c1a14 Mon Sep 17 00:00:00 2001 From: Samruddhi Ghodake <72791227+samughodake@users.noreply.github.com> Date: Tue, 5 Oct 2021 23:36:14 +0530 Subject: [PATCH] chore(CPlusPlus): display longest name (#517) --- algorithms/CPlusPlus/README.md | 1 + algorithms/CPlusPlus/Strings/longest-name.cpp | 46 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 algorithms/CPlusPlus/Strings/longest-name.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 37be9287..6eafa549 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -101,6 +101,7 @@ 6. [Remove occurrences from string](Strings/remove-occurrences.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) +9. [Display longest name in a string array](Strings/longest-name.cpp) ## Trees diff --git a/algorithms/CPlusPlus/Strings/longest-name.cpp b/algorithms/CPlusPlus/Strings/longest-name.cpp new file mode 100644 index 00000000..9554fdf8 --- /dev/null +++ b/algorithms/CPlusPlus/Strings/longest-name.cpp @@ -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 + +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 +*/