Introduction to Programming in C++ Lab Exercises Section 3 1. What

advertisement
Introduction to Programming in C++
Lab Exercises
Section 3
1. What is wrong with this program?
if radius >= 0
{ area = radius * radius * PI;
cout << area;
}
2. Write a C++ program that asks the user to enter an integer and then determines whether
the integer is a single digit number. Display the result
3. This program requires you to combine your knowledge of the remainder operator with
your understanding of the if/else construct. You are to write a C++ program that asks the
user for an integer, determines whether it is an even or odd number, and displays that
result. This program requires a simple if/else statement.
A sample dialog for this program looks as follows:
Enter an integer: 23
23 is odd.
4. Write a C++ program that inputs a single character and then tests with a switch construct
if that character is a vowel or not. (Note – vowels in English are the characters ‘a’, ‘e’, ‘i’, ‘o’
and ‘u’, together with their uppercase counterparts. Display a suitable message.
5. Enter the following program and run it.
#include <iostream>
#include <cstdlib>
#include <ctime> // Needed for the time function
using namespace std;
int main()
{
// Generate a random number to be guessed
srand(time(0));
int number = rand() % 101;
cout << "Guess a magic number between 0 and 100";
int guess = -1;
while (guess != number)
{
// Prompt the user to guess the number
cout << "\nEnter your guess: ";
cin >> guess;
if (guess == number)
cout << "Yes, the number is " << number << endl;
else if (guess > number)
cout << "Your guess is too high" << endl;
else
cout << "Your guess is too low" << endl;
} // End of loop
return 0;
}
The program generates a random number between 0 and 100 and the user is prompted to guess it.
The program uses a while loop to keep prompting the user for another guess until the user guesses it
correctly.
6. Write a for loop that displays the message “Welcome to C++!\n” ten times on the screen.
7. Bonus question: Write a C++ program containing a nested loop that displays the following
*
* **
* ***
*******
Download
Study collections