Skip to content
doubtly

Write a C++ program that right justifies text. It should read and echo a sequence of left justified lines and print them in right justified format.

Write a C++ program that right justifies text. It should read and echo a sequence of left justified lines and print them in right justified format.

[March 2003, March 2006, Oct. 2006, Oct. 2003, March 2005, March 2007] Computer science program maharashtra board

Doubtly Asked Updated maharashtra-board Save WhatsApp Report

2 answers

Best answer

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
char line[5][100];
int i, j, len, maxlen=0;
for(i=0; i<=4; i++)
{
cin.getline(line[i], 99, '\n');
len=strlen(line[i]);
if(len>maxlen)
maxlen=len;
}
for(i=0; i<=4; i++)
{
len=strlen(line[i]);
for(j=1; j<=maxlen-len; j++)
{
cout<<" ";
}
cout<<line[i]<<endl;
}
}

Only works in Turbo c++ for maharashtra board syllabus

Doubtly · 1 May 2021 Report
Was this answer helpful?

Answer: Read the lines, find the length of the longest line, then print each line after enough leading spaces to make all lines end in the same column.

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
    char line[5][100];
    int i, j, len, maxlen = 0;
    clrscr();
    cout << "Enter 5 lines of text:" << endl;
    for (i = 0; i < 5; i++)
    {
        cin.getline(line[i], 100, '\n');
        len = strlen(line[i]);
        if (len > maxlen)
            maxlen = len;
    }
    cout << "Left justified (as entered):" << endl;
    for (i = 0; i < 5; i++)
        cout << line[i] << endl;
    cout << "Right justified:" << endl;
    for (i = 0; i < 5; i++)
    {
        len = strlen(line[i]);
        for (j = 1; j <= maxlen - len; j++)
            cout << " ";
        cout << line[i] << endl;
    }
    getch();
}

How it works: the first loop reads each line with cin.getline and keeps track of the longest length maxlen. The lines are then echoed as entered. Finally, each line is printed after maxlen - len spaces, so the last character of every line falls in the same column, which is right justification. (This is Turbo C++ style as in the board syllabus; in standard C++ use <iostream>, <cstring>, int main() and using namespace std;, and drop conio.h.)

Doubtly AI · 23 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.