Download docx - C++ laboratory exercise

Transcript
Page 1: C++ laboratory exercise

LABORATORY EXERCISESC++ PROGRAMMING

MT2044

LAB 1

NAMA: BEK E XUANUK: UK33537TARIKH: 12-10-2014

Page 2: C++ laboratory exercise

Program 3-9// This program uses a type cast to avoid integer division.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){

int books; // Number of books to readint months; // Number of months spent readingdouble perMonth; // Average number of books per month

cout << " How amny books do you plan to read? ";cin >> books;cout << " How many months will it take you to read them? ";cin >> months;perMonth = static_cast<double>(books) / months;cout << " That is " << perMonth << " books per month.\n";

system ("PAUSE");return 0;

}

Page 3: C++ laboratory exercise

Program 3-13// This program displays three rows of numbers.

#include "stdafx.h"#include <iostream>#include <iomanip> // Required for setwusing namespace std;

int main (){ int num1 = 2897, num2 = 5, num3 = 837,

num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12;

// Display the first row of numbers cout << setw(6) << num1 << setw(6)

<< num2 << setw(6) << num3 << endl;

// Display the second row of numbers cout << setw(6) << num4 << setw(6)

<< num5 << setw(6) << num6 << endl;

// Display the third row of numbers cout << setw(6) << num7 << setw(6)

<< num8 << setw(6) << num9 << endl;

system ("PAUSE"); return 0;}

Page 4: C++ laboratory exercise

Program 3-17// This program asks for sales figures for 3 days. The total// sales are calculated and displayed in a table.

#include "stdafx.h"#include <iostream>#include <iomanip> using namespace std;

int main (){

double day1, day2, day3, total;

// Get the sales for each day.cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;cout << "Enter the sales for day 3: ";cin >> day3;

// Calculate the total sales.total = day1 +day2 + day3;

// Display the sales figures.cout << "\nSales Figures\n";cout << "-------------\n";cout << setprecision(2) << fixed;cout << "Day 1: " << setw(8) << day1 << endl;cout << "Day 2: " << setw(8) << day2 << endl;cout << "Day 3: " << setw(8) << day3 << endl;cout << "Total: " << setw(8) << total << endl;

system ("PAUSE");return 0;

}

Page 5: C++ laboratory exercise

Program 3-19

// This program demonstrates using the getline function// to read character data into a string object.

#include "stdafx.h"#include <iostream>#include <string>using namespace std;

int main (){

string name;string city;

cout << "Please enter your name: ";getline(cin, name);cout << "Enter the city you live in: ";getline(cin, city);

cout << "Hello, " << name << endl;cout << "You live in " << city << endl;

system ("PAUSE");return 0;

}

Page 6: C++ laboratory exercise

Program 3-21

// This program demonstrates three ways// to use cin.get() to pause a program.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){

char ch;

cout << "This program has paused. Press Enter to continue.";cin.get(ch);cout << "It has paused a second time. Please press Enter again.";ch = cin.get();cout << "It has paused a third time. Please press Enter again.";cin.get();cout << "Thank you!";

system ("PAUSE");return 0;

}

Page 7: C++ laboratory exercise

Program 3-27// This program is used by General Crates, Inc. to calculate// the volume, cost, customer charge, and profit of a crate// of any size. It calculates this data from user input, which// consists of the dimensions of the crate.

#include "stdafx.h"#include <iostream>#include <iomanip>using namespace std;

int main (){

// Constants for cost and amount chargedconst double COST_PER_CUBIC_FOOT = 0.23;const double CHARGE_PER_CUBIC_FOOT = 0.5;

// Variablesdouble length, // The crate's length

width, // The crate's width height, // The crate's height volume, // The volume of the crate cost, // The cost to build the crate charge, // The customer charge for the crate profit; // The profit made on the crate

// Set the desired output formatting for numbers.cout << setprecision(2) << fixed << showpoint;

// Prompt the user for the crate's length, width, and heightcout << "Enter the dimensions of the crate (in feet):\n";cout << "Length: ";cin >> length;cout << "Width: ";cin >> width;cout << "Height: ";cin >> height;

// Calculate the crate's volume, the cost to produce it,// the charge to the customer, and the profit.volume = length * width * height;cost = volume * COST_PER_CUBIC_FOOT;charge = volume * CHARGE_PER_CUBIC_FOOT;profit = charge - cost;

// Display the calculated data.cout << "The volume of the crate is ";cout << volume << " cubic feet.\n";cout << "Cost to build: $" << cost << endl;cout << "Charge to customer: $" << charge << endl;cout << "Profit: $" << profit << endl;

system ("PAUSE");return 0;

}

Page 8: C++ laboratory exercise

Program 3-27 output with Example Input

Program 3-27 Output with Different Example

Page 9: C++ laboratory exercise

Program 4-2// This program averages three test scores.

#include "stdafx.h"#include <iostream>#include <iomanip>using namespace std;

int main (){

int score1, score2, score3; // To hold three test scoresdouble average; // To hold the average score

// Get the three test scores.cout << "Enter 3 test scores and I will average them: ";cin >> score1 >> score2 >> score3;

// Calculate and display the average score.average = (score1 + score2 + score3) / 3.0;cout << fixed << showpoint << setprecision(1);cout << "Your average is " << average << endl;

// If the average is greater than 95, congratulate the user.if (average > 95)

cout << "Congratulations! That's a high score:\n";

system ("PAUSE");return 0;

}

Page 10: C++ laboratory exercise

Program 4-2 output with example input

Program 4-2 with other example

Page 11: C++ laboratory exercise

Program 4-8

// This program uses the modulus operator to determine// if a number is odd or even. If the number is evenly divisible// by 2, it is an even number. A remainder indicates it is odd.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){

int number;

cout << "Enter an integer and I will tell you if it\n";cout << "is odd or even. ";cin >> number;if (number % 2 == 0)

cout << number << " is even.\n";else

cout << number << " is odd.\n";

system ("PAUSE");return 0;

}

Page 12: C++ laboratory exercise

Program 4-9

// This program asks the user for two numbers, num1 and num2.// num1 is divided by num2 and the result is displayed.// Before the division operated, however, num2 is tested// for the value 0/ If it contains 0, the division does not// take place.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ double num1, num2, quotient;

// Get the first number.cout << "Enter a number: ";cin >> num1;

// Get the second number.cout << "Enter another number: ";cin >> num2;

// If num2 is not zero, perform the division.if (num2 == 0){

cout << "Division by zero is not possible.\n";cout << "Please run the program again and enter\n";cout << "a number other than zero.\n";

}else{

quotient = num1 / num2;cout << "The quotient of " << num1 << " divided by ";cout << num2 << " is " << quotient << ".\n";

}

system ("PAUSE");return 0;

}

Page 13: C++ laboratory exercise
Page 14: C++ laboratory exercise

Nested If

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ char employed, recentGrad;

// Get the first number cout << "Are you employed? "; cin >> employed;

// Get the second number cout << "Are u recently graduated? "; cin >> recentGrad;

// Determine the user's loan qualification. if (employed == 'Y') {

if (recentGrad == 'Y') // Nested if cout << "You qualify for the special interest rate.\n";

else // Not recently graduated but employed cout << "You must have graduated from college in the past two\n

years to qualify.\n"; }

else // Not employed cout << "You must be employed to qualify.\n";

system ("PAUSE"); return 0;}

Page 15: C++ laboratory exercise

If Else// if || else if || else

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int A_SCORE, B_SCORE, C_SCORE, D_SCORE; double testScore;

// Get Grade A. cout << "The score for grade A is : "; cin >> A_SCORE;

// Get Grade B. cout << "The score for grade B is : "; cin >> B_SCORE;

// Get Grade c. cout << "The score for grade C is : "; cin >> C_SCORE;

// Get Grade D. cout << "The score for grade D is : "; cin >> D_SCORE;

// get information. cout << "Your score is: "; cin >> testScore;

//Determine letter grade. if (testScore >= A_SCORE)

cout << "Your grade is A.\n";

else if (testScore >= B_SCORE) cout << "Your grade is B.\n";

else if (testScore >= C_SCORE) cout << "Your score is C.\n";

else if (testScore >= D_SCORE) cout << "Your score is D.\n";

else if (testScore >= 0) cout << "Your score is F.\n";

else cout << "Invalid test score.\n";

system ("PAUSE"); return 0;}

Page 16: C++ laboratory exercise
Page 17: C++ laboratory exercise

Program 4-23

// The switch statement in this program tells the user something// he or she already knows: the data just entered!

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ char choice;

cout << "Enter A, B, or C: "; cin >> choice; switch (choice) { case 'A': cout << "You entered A.\n";

break; case 'B': cout << "You entered B.\n";

break; case 'C': cout << "You entered C.\n";

break; default: cout << "You did not enter A, B, or C!\n"; }

system ("PAUSE");return 0;

}

Page 18: C++ laboratory exercise

Program Output with Example Input

Program Ouptut with Different Example

Page 19: C++ laboratory exercise

Program 4-25// The program is carefully constructed to use the "fail through"// feature of the switch statement.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int modelNum; // Model number

// Get a model number from the user.cout << "Our TVs come in three models:\n";cout << "The 100, 200, and 300. Which do you want? ";cin >> modelNum;

// Display the model's features.cout << "That model has the following features:\n";switch (modelNum){ case 300: cout << "\tPicture-in-a-picture.\n"; case 200: cout << "\tStereo sound.\n"; case 100: cout << "\tRemote control.\n";

break; default: cout << "You can only choose the 100,";

cout << "200, or 300.\n";}

system ("PAUSE");return 0;

}

Page 20: C++ laboratory exercise
Page 21: C++ laboratory exercise
Page 22: C++ laboratory exercise

Program 4-30

// The program uses two variables with the same number.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ // Define a variable named number.

int number;

cout << "Enter a number greater than 0: ";cin >> number;if (number >0){

int number; // Another variable named number.cout << "Now enter another number: ";cin >> number;cout << "The second number you entered was "

<< number << endl;}cout << "Your first number was " << number << endl;

system ("PAUSE");return 0;

}

Page 23: C++ laboratory exercise

Program 5-1

// The program demonstrates the ++ and -- operators.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int num = 4; // num starts out with 4.

// Display the value in num. cout << "The variable num is " << num << endl; cout << "I will now increment num.\n\n";

// Use postfix ++ to increment num. num++; cout << "Now the variable num is " << num << endl; cout << "I will increment num again.\n\n";

// Use prefix ++ to increment num. ++ num; cout << "Now the variable num is " << num << endl; cout << "I will now decrement num.\n\n";

// Use postfix -- to decrement num. num--; cout << "Now the variable num is " << num << endl; cout << "I will decrement num again.\n\n";

// Use prefix -- to increment num. --num; cout << "Now the variable num is " << num << endl;

system ("PAUSE");return 0;

}

Page 24: C++ laboratory exercise
Page 25: C++ laboratory exercise

Program 5-3// The program demonstrates a simple while loop.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int number = 1;

while (number <=5) {

cout << "Hello\n"; number++;

} cout << "That's all!\n";

system ("PAUSE"); return 0;}

Page 26: C++ laboratory exercise

Input Validation// This program demonstrates a simple while loop.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ double teamPlayers, MIN_PLAYERS, MAX_PLAYERS, players; //Get the number of players per team. cout << "How many players do you wish per team? "; cin >> teamPlayers;

// Get the number of min and max players per team. cout << "The number for MIN_PLAYERS are: "; cin >> MIN_PLAYERS; cout << "The number for MAX_NUMBERS are: "; cin >> MAX_PLAYERS;

// Validate the input. while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS) {

//Explain the error. cout << "You should have at least " << MIN_PLAYERS

<< " but no more than " << MAX_PLAYERS << " per team.\n";

// Get the input again. cout << "How many players do you wish per team? "; cin >> teamPlayers;

}

// Get the number of players available. cout << "How many players are available? "; cin >> players;

// Validate the input. while (players <=0) {

// Get the input again. cout << "Please enter 0 or greater: "; cin >> players;

}

system ("PAUSE"); return 0;}

Page 27: C++ laboratory exercise
Page 28: C++ laboratory exercise

Program 5-6

// The program displays a list of numbers and // their squares.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ const int MIN_NUMBER = 1, // Starting number to square

MAX_NUMBER = 10; // Maximum number to square

int num = MIN_NUMBER; // Counter

cout << "Number Number Squared\n"; cout << "-------------------------\n"; while (num <= MAX_NUMBER) {

cout << num << "\t\t" << (num * num) << endl; num++; // Increment the counter.

}

system ("PAUSE"); return 0;}

Page 29: C++ laboratory exercise

Program 5-7// The program averages 3 test scores. it repeats as// many times as the user wishes.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int score1, score2, score3; // Three scores double average; // Average score char again; // To hold Y or N input

do {

// Get three scores. cout << "Enter 3 scores and I will average them: "; cin >> score1 >> score2 >> score3;

// Calculate and display the average. average = (score1 + score2 + score3) / 3.0; cout << "The average is " << average << ".\n";

// Does the user want to average another set? cout << "Do you want to average another set? (Y/N) "; cin >> again ;

} while (again == 'Y' || again == 'y');

system ("PAUSE"); return 0;}

Page 30: C++ laboratory exercise

Program 5-9// The program displays the numbers 1 through 10 and // their squares.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ const int MIN_NUMBER = 1, // Starting value

MAX_NUMBER = 10; // Ending value

int num;

cout << "Number Number Squared\n"; cout << "-------------------------\n";

for (num = MIN_NUMBER; num <=MAX_NUMBER; num++) cout << num << "\t\t" << (num * num) << endl;

system ("PAUSE"); return 0;}

Page 31: C++ laboratory exercise

Program 5-12// The program takes daily sales figures over a period of time// and calculates their total.

#include "stdafx.h"#include <iostream>#include <iomanip>using namespace std;

int main (){ int days; // Number of days double total = 0.0; // Accumulator, initialized with 0

// Get the number of days. cout << "For how many days do you have sales figures? "; cin >> days;

// Get the sa;es for each day and accumulate a total. for (int count = 1; count <= days; count++) {

double sales; cout << "Enter the sales for day " << count << ": "; cin >> sales; total += sales; // Accumulate the running total.

}

// Display the total sales. cout << fixed << showpoint << setprecision(2); cout << "The total sales are $" << total << endl;

system ("PAUSE"); return 0;}

Page 32: C++ laboratory exercise

Program 5-13// This program calculates the total number of points a// soccer team has earned over a series of games. The user// enters a series of point values, then -1 when finished.

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int game = 1, // Game counter

points, // To hold a number of points total = 0; // Accumulator

cout << "Enter the number of points your team has earned\n"; cout << "so far in the season, then enter -1 when finished.\n\n"; cout << "Enter the points for game " << game << ": "; cin >> points;

while (points !=-1) {

total += points; game++; cout << "Enter the points for game " << game << ": "; cin >> points;

} cout << "\nThe total points are " << total << endl;

system ("PAUSE"); return 0;}

Page 33: C++ laboratory exercise

Nested Loop/* This program calculates the average of score for students.*/

#include "stdafx.h"#include <iostream>using namespace std;

int main (){ int numStudents, numTests;

double total, average; cout << "Enter the total of numStudents: "; cin >> numStudents; cout << "Enter the numTests: "; cin >> numTests; // Determine each student's average score. for (int student =1; student <= numStudents; student++) {

total = 0; // Initialize the accumulator. for (int test = 1; test <= numTests; test++) {

double score; cout << "Enter score " << test << " for "; cout << "student " << student << ": "; cin >> score; total +=score;

} average = total / numTests; cout << "The average score for student " << student; cout << " is " << average << ".\n\n";

}

system ("PAUSE"); return 0;}


Recommended