Loading....
Coupon Accepted Successfully!

 

More Programs

19.13 Write a program to enter five numbers in an integer array. Display the largest number. If the array contains null element, throw the exception.

#include<iostream.h>

int main()

{

int max[5],k=0,m;

cout<<“\n Enter five numbers:”;

for (k=0;k<5;k++)

cin>>max[k];

try

{

for (k=0;k<5;k++)

{

if (max[k]==0)

throw max[k];

if (max[k]>m)

m=max[k];

}

cout<<“Largest number is :”<<m;

}

catch (int k)

{

cout<<“\n caught a null value”;

}

}

OUTPUT

Enter five numbers : 4 5 8 7 0

caught a null value

Explanation: In the above program, an integer array max [5] is declared. The cin statement within the first for loop reads integers through the keyboard. The second for loop and the second if statement within it checks the successive numbers of arrays and stores the largest number in the variable m. Before this, the first if statement checks whether the number is zero. If the number is zero, an exception is thrown.

19.14 Write a program to enter a string and display it and throw an exception when null character is detected.

#include<iostream.h>

int main()

{ char text[20];

int x=0;

cout<<“\n Enter text:”;

cin.getline(text,20);

try

{

while (1)

{


if
(text[x]==‘\0’)

throw text[x];

cout<<text[x];

x++;

}

}

catch (char c)

{

cout<<“\n End of string”;

}

return 0;

}

OUTPUT

Enter text : Haste is Waste

Haste is Waste

End of string

Explanation: In the above program, a character array text [20] is declared. The cin statement accepts the string through the keyboard. The while loop and the statements within it are used to display the string. The if statement checks every character of the string to see whether it is a null character or other character. If it is a null character, an exception is thrown; otherwise, the character is displayed on the screen. Thus, at last when a null character is found, an exception is thrown. The message “End of string” is displayed by the catch block.





Test Your Skills Now!
Take a Quiz now
Reviewer Name