Programming Examples

Cpp program to input 5 cities, display name and length of city with max length using array of characters


Write a program to input 5 cities, display the name and  length of city with maximum length

Solution

#include <iostream>
#include<cstring> // Include the <cstring> header for strlen
using namespace std;
int main()
{
    char city[5][10], ch;
    int length,max=0;
    string str=" ";
    cout << "Enter the cities" << endl;
    for (int a = 0; a < 5; a++)
    {
        cin.getline(city[a], 10);
    }
    for (int a = 0; a < 5; a++)
    {
        length=strlen(city[a]);
        //cout<<city[a];
        if(max<=length)
        {
            max=length;
            str=city[a];
        }
    }
    cout<<"The largest string is : "<<str<<" with length "<<max;
    return 0;
}
Output

Enter the cities

kanpur

ahmedabad

new delhi

agra

banglore

The largest string is : new delhi with length 9

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz