0% found this document useful (0 votes)
14 views33 pages

امتحانات قبووول

The document is a lab manual for C++ programming at Sana'a University, covering various topics including output statements, variables, constants, and operators. It consists of multiple laboratory exercises designed to teach students fundamental programming concepts and practices in C++. Each lab includes objectives, learning outcomes, introductory concepts, and exercises for students to complete.

Uploaded by

omarabdkafi018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views33 pages

امتحانات قبووول

The document is a lab manual for C++ programming at Sana'a University, covering various topics including output statements, variables, constants, and operators. It consists of multiple laboratory exercises designed to teach students fundamental programming concepts and practices in C++. Each lab includes objectives, learning outcomes, introductory concepts, and exercises for students to complete.

Uploaded by

omarabdkafi018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

Faculty of Computer

& Information Technology

Sana'a University
C++
Dr.

Lab Manual
Programming language
C++
Contents

Laboratory #1 – Introduction & Output Statement.........................................................................2

Laboratory #2– C++ Variables, Constant & Input statement:.........................................................6

Laboratory #3 – Operators in C++................................................................................................10

Laboratory #4 – Control Structures I............................................................................................14

Laboratory #5 – Control Structures I (switch ( ) ).........................................................................17

Laboratory #6 – Loops (1)............................................................................................................20

Laboratory #7 – Loops (2)............................................................................................................22

Laboratory #8 C++: Nested control structure (Nested loops).......................................................25

Laboratory #9 C++ One-Dimensional Arrays:..............................................................................29

C++ projects.................................................................................................................................31
Laboratory #1 – Introduction & Output Statement

1. Laboratory Objective
The objective of this laboratory is to introduce students to the basic concepts in C++
Programming Language as well as the basic forms for the Output Statements in the Language.

2. Laboratory Learning Outcomes:


After conducting this laboratory student will be able to: Write, edit, compile, debug, and run
simple C++ Programs that includes simple Output Statements in the C++ Language.

3. Laboratory Introductory
Concepts
a. C++ program environment:

b. Structure of C++ program:


Both the
open
curly #include <iostream> This specifies the real beginning of our
brace using namespace std; program. Here we are declaring a
and function named main. All
close
// First program in C++ C++ programs must contain this function
curly to be executable.
int main( ) begin of the
brace
body of a
are { function.
required The body of

}
for every main function
function
definitio cout << "This is a simple C++ program!\n" ;
n.
end of the Structure of output statement in C++ program:
body of a
cout << expression <<
} function. expression ….;

# include <iostream>
This line is a preprocessing directive. All preprocessing directives within C ++ source code begin with a # symbol.
This one directs the preprocessor to add some predefined source code to our existing source code before the
compiler begins to process it. This process is done automatically and is invisible to us. Here we want to use some
parts of the iostream library, a collection precompiled C++ code that C++ programs (like ours) can use. The
iostream library contains routines that handle input and output (I/O) that include functions such as printing to the
display, getting user input from the keyboard, and dealing with files.

c. Variations of simple in C++ program:


#include <iostream> #include <iostream> #include <iostream>
int main() { using std::cout; using namespace std;
std::cout << "This is a using std::endl; int main() {
simple C++ program!" << int main() { cout << "This is a simple
std::endl; cout << "This is a simple C++ program!" << endl;
return 0; C++ program!" << endl; return 0;
} return 0; }
}
Variations of simple c++ program

Note:The using namespace std directive allows us to omit the std:: prefixes and use
their shorter names. This directive is optional, but if it is omitted, the longer names are
required.

4. Laboratory Exercises
Exercise 1: Write a C++ program to print “Hello World! “Statement

Exercise 2: Write a C++ Program to print “Hello, World” with sequential output of several
strings
#include <iostream.h>
//This program illustrates the output of strings and characters:
int main( )
{
cout << "Hello, " << 'W' << 'o' << "r" << "ld" << '.' << '\n';
return 0;
}

Exercise 3: Write C++ program to print some information about you as this form:

*****************************************
Name: Mohammed Ali
===========================
Age: 20
===========================
Email : [email protected]
===========================

Exercise 4: Correct this Program which demonstrate comments in C++ program

#include <iostream.h< // This directive is needed to use cout


//This program prints message: "Hello, World:".
int main)(
{
cout << /* now printing */ "Hello, World.\n"; /* change ?/*
return 0; // Some compilers will complain if you omit this line
*/ }end of program/*
}

Exercise 5: correct the mistakes in the following program:

#include<iostraem.h>
Void main[ ]
{
Cout>>” my name is Ali”
Retorn 0;
}

Exercise 6: This program designed to print B letter write C++ program to print your first
letter
#include <iostream.h>
int main()
{
cout << " ******* " << endl;
cout << " ******* " << endl;
cout << " ** ** " << endl;
cout << " ** * " << endl;
cout << " ***** " << endl;
cout << " ****** " << endl;
cout << " ** * " << endl;
cout << " ** ** " << endl;
cout << " ******* " << endl;
cout << " ******* " << endl;
return 0;
}

Exercise 7: Write this program then demonstrate and discuss what happened?

#include <iostream>
using namespace std;
int main()
{
cout << "7 + 3 = " << 7 + 3 << endl;
cout << "7 - 3 = " << 7 - 3 << endl;
cout << "7 * 3 = " << 7 * 3 << endl;
cout << "7 / 3 = " << 7 / 3 << endl;
cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;
cout << "7 % 3 = " << 7 % 3 << endl;
cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;
cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;
return 0;
}

Exercise 8: What, if anything, prints when each of the following C++ statements is
performed? If nothing prints, then answer “nothing.”
Assume x = 2 and y = 3.

a) cout << x;
b) cout << x + x;
c) cout << "x=";
d) cout << "x = " << x;
e) cout << x + y << " = " << y + x;
f) z = x + y;
g) // cout << "x + y = " << x + y;
h) cout << "\n";

Exercise 9: write C++ program to print small message

Exercise 10: Write a program that prints the numbers 1 to 4 on the same line with each pair
of adjacent numbers separated by one space.
Write the program using the following methods:
a) Using one output statement with one stream insertion operator.
b) Using one output statement with four stream insertion operators.
c) Using four output statements.

5. Laboratory Instructions
(a) Some Good Programming Practices
Every program should begin with a comment that explains the purpose of program, author and
creation date and last updated date.
 Use blank lines, space characters and tabs to enhance program readability.
 Many programmers make the last character printed a newline (\n). This ensures that the
function will leave the screen cursor positioned at the beginning of a new line.
 Indent the entire body of each function one level within the braces that delimit the body of the
function. This makes the program easier to read.
 Place a space after each comma (,) to make programs more readable.
(b) Some Common Programming Mistakes
Forgetting to include the <iostream> header file in a program that inputs data from the
keyboard or outputs data to the screen cause the compiler to issue an error message.
 Omitting the semicolon at the end of C++ statement is a syntax error.
Laboratory #2– C++ Variables, Constant & Input statement:

1. Laboratory Objective:
The objective of this laboratory is to introduce students to the basics of declaring
Variables, and Constants as well as the use of different Operators in the C++ Language.

2. Laboratory Learning Outcomes:


After conducing this laboratory student will be able to: Declare Variables and Constants and use
them in Simple C++ Programs

3. Laboratory Introductory Concepts:


a. Input stream object.
(>>) stream extraction operator

i. Used with std::cin.


ii. Waits for user to input value, then press Enter (Return) key.
iii. Stores value in variable to right of operator.

Ex: std::cin >> integer1;

b. Initialization of variables and constants.


Identifiers are used to name variables, constants and many other
components of
a program. They consist exclusively of letters, digits and the
underscore _ character. They cannot begin with a digit and cannot
duplicate reserved words used in C++ such as int or if. The data type
indicates what kind of data can be stored, thus setting the size of that
location.

Variables is a Components of memory in which data values stored can


change during the execution of the program.

Data_Type identifier = initial_value;

Variable = expression;

ex: int myAge = 19;


Constants is a Components of memory in which data values stored
are initialized once and never changed during the execution of the
program.

const Data_Type identifier = value;

ex: const float Pi = 3.14159265;

Data Type in C++

/The char data type allows only one character to be stored in its
memory location. The string data type (actually a class and not a true
data type built into the language)
allows a sequence of characters to be stored in one memory location.
And To use this data type, you need to access program components
from the library, #include <string>.

c. Operators in the C++ Language


i. (=) assignment operator
a. Assigns value to variable

b. Binary operator (two operands)

Ex: sum = variable1 + variable2;

4. Laboratory Exercises

Exercise 1: Write a C++ Program to initialize two variables as they are declared the first
number =20 and the second =34 then print them like: 20, 34

Exercise 2: write a C++ program to ask user to enter his age then print this letter:

***Your age is 20 years. ***

Exercise 3: Write a C++ Program that calculates the circumference of a circle if you know
that Circumference=2 * π * r, π= 3.14?
Exercise 4: Write a C++ program to ask user to enter his name, age, tall Then print them
as:

Your name is Ahmed

20 Years old ago.

Your tall is 1.70 Meters.

Exercise 5: Write a C++ program that converts degrees Celsius to Fahrenheit

if you know that T(°F) = T(°C) × 9/5 + 32

Exercise 6: Write a program that inputs a five-digit number, separates the number into its
individual digits and prints the digits separated from one another by three spaces each.
(Hint: Use the integer division and modulus operators.) For example, if the user types in
42339 the program should print 4 2 3 3 9

Exercise 7: write a C++ program that work as small calculator which ask user to enter two
numbers then your program should print 4 fundamental operations:

Ex: If the user enters 4,2 then your program will print this results:

4+2=6

4-2=-2

4* 2= 8

4/2=2

Exercise 8: Write a C++ program to give ASCII code of the letter which the user enters it?

Exercise 9: Write a C++ program to convert small letter to capital and vice versa?

Exercise 10: Write a C++ program that asked the employee about his salary then program
adds incentives 10,000 and 5,000 transportation and 20% of salary bonus then print the
total salary

Exercise 11: correct the mistakes in the following program:

#include<<ostream>

Using name space std;

Int main ()

Cin>>x;

Cout<<” y =”>>x

}
Exercise 12: what is the output of the following program:

#include<iostream>

using name space std;

int main ()

int a,b;

cin >>a>>b;

cout<<” a=” <<a<<” \n” <<” b=” <<b;

5. Laboratory Instructions:
(a) Some Good Programming Practices
 Many programmers prefer to declare each variable on a separate line. This format
allows for easy insertion of a descriptive comment next to each declaration.
 Choosing meaningful variables makes a program self-documenting.
 Avoid using abbreviation in identifiers. This promotes program readability.
 Place spaces on either side of a binary operator. This makes the operator stand out
and makes the program more readable.

(b) Some Common Programming Mistakes


 Attempting to use the modulus operator (%) with non-integer operands is a compilation
error.
Laboratory #3 – Operators in C++.

1. Laboratory Objective:
The objective of this laboratory is to introduce students to the operators in C++ Programming
Language.

2. Laboratory Learning Outcomes:


After conducting this laboratory student will be able to Use different types of Operators, such as
Arithmetic, Relational, logical, increment & decrement and assignment operators in Simple C++
Programs.

3. Laboratory Introductory Concepts:


1. Operators in C++:
 Arithmetic Operators: +, -, *, /, %
 Assignment operators: Max = 5; Max = A ; F = A+B*2
 Compound Assignment: A += 10; A = A + 10;
A- =C;A=A-C;
I*=4I=I*4;
r / = 2;r = r /2;
S%=3;S=S%3;
B &= true;B = B && true;
B |= true;B = B || true;
 Increment and Decrement operators:
Postfix
C++;use the value of C, then increment (C = C+1) it.
C--;use the value of C, then decrement (C = C-1) it.
Prefix
++C  increment the value of C (C = C+1), then use it .
- -C;Decrement the value of C (C = C-1), then use it.
 logical Operators: <, >, ==, <=, >=, != .

 Boolean Operators: &&, ||, !

 Conditional operator:

(Expression1? Expression2: Expression3)


4. Laboratory Exercises

Exercise 1: Write single C++ statements that

a) Input integer variable x with cin


b) Input integer variable y with cin
c) Initialize integer variable i to 1.
d) Initialize integer variable power to 1.
e) Multiply variable power by x and assign the result to power.
f) Increment variable i by 1.
h) Output integer variable power with cout

Exercise 2: (Gas Mileage) Drivers are concerned with the mileage obtained by their
automobiles. One driver has kept track of several tankful of gasoline by recording miles
driven and gallons used for each tankful. Develop a program that will input the miles
driven and gallons used for each tankful.
The program should calculate and display the miles per gallon obtained for tankful. Here is
a sample input/output dialog:

Enter the gallons used : 12.8


Enter the miles driven: 287
The miles / gallon for this tank was 22.421875

Exercise 3: write a C++ program that calculates the square root of the number entered by
the user

Exercise 4: Test the increment and decrement operators:

#include <iostream.h>
//Tests the increment and decrement operators:
int main()
{
int m = 66, n;
n = ++m;
cout << "m = " << m << ", n = " << n << endl;
n = m++;
cout << "m = " << m << ", n = " << n << endl;
cout << "m = " << m++ << endl;
cout << "m = " << m << endl;
cout << "m = " << --m << endl;
return 0;
}
Exercise 5: Test the combined operators:

#include <iostream.h>
//Tests combined operators:
int main()
{
int n = 44;
n +=9;
cout << n << endl;
n -= 5;
cout << n << endl;
n *= 2;
cout << n << endl;
return 0;
}

Exercise 6: Tests output of type char:

#include <iostream.h>
//Tests output of type char:
int main()
{
char c = 64;
cout << c++ << " ";
cout << c++ << " ";
cout << c++ << " ";
cout << c++ << endl;
c = 96;
cout << c++ << " ";
cout << c++ << " ";
cout << c++ << " ";
cout << c++ << endl;
return 0;
}

Exercise 7: Tests logical operator what is the output of the following program:

#include <iostream.h>
int main()
{
int a, b, c;
cout << "Enter three integers" :;
cin >> a >> b >> c;
cout (a >= b && a >= c) ;
cout (b >= a && b >= c) ;
cout (c >= a && c >= b) ;
return 0;
}

Exercise 8: State the order of evaluation of the operators in each of the following C++
statements and show the value of x after each statement is performed.

a) x = 7 + 3 * 6 / 2 - 1;
b) x = 2 % 2 + 2 * 2 - 2 / 2;
c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) );

d) x = 10 / 2 * 4 + 4 * 3 % 2;
Exercise 9: what is the output of the following program:

#include<iostream.h>
int main()
{
int x=1,y=2;
y++;
++x;
cout<<x++<<endl<<++y;
x=2* 7 + ++x + y--;
cout<<x<<endl<<y;

Exercise 10: Given the equation y = ax3 + 7, which of the following, if any, are correct C++
statements for this equation?

a) y = a * x * x * x + 7;
b) y = a * x * x * ( x + 7 );
c) y = ( a * x ) * x * ( x + 7 );
d) y = ( a * x ) * x * x + 7;
e) y = a * ( x * x * x ) + 7;
f) y = a * x * ( x * x + 7 );
Laboratory #4 – Control Structures I

1) Laboratory Objective:
The objective of this laboratory is to train students on how and when to use different C++
control structures

2) Laboratory Learning Outcomes:


After conducting this laboratory students will be able to:
Identify and practice using C++ Control Structures.

3) Laboratory Introductory Concepts:


Control Structure are ways for programmers to control what pieces of a program are to be
executed at certain times. 
 There are two basic types of Control Structures: conditional statements and Loops.

- Structure of if statement:

If (Condition) Statement;

If (Condition) Statement_1 else Statement_2

4) Laboratory Exercises

Exercise 1: write a C++ program to print the number if the number is divided by 5

Exercise 2:(Guess game) write a C++ program to initial value in variable then ask the user
to guess number if the number which the user guess equal your number print “you win”
else print “you lost”

Exercise 3: write a C++ program That calculates the rate of student the program will read
scores and determine the rate:
If the grade >=90 print “Excellent” …. etc.

Exercise 4: Write a C++ program doing a traffic signal if the red prints stop whether yellow
prints prepared if the Green prints move

Exercise 5: Write a C++ program to solve the second degree equation

aX2 + bX + c= 0 for any real a, b and c

If you know x=-b / 2*a

=b*b - 4*a*c

If >0 you find two solution

X1=-b / 2*a

X2=-b / 2*a

If =0 you find one solution

X=-b/2*a

If <0 you cannot find any solution

Exercise 6: write a C++ program that checks if the user enters the dimensions of square or
rectangle

Exercise 7: write a C++ program which calculates the age group (child, young, old)
Exercise 8: write a C++ Program like a calculator for the basic operations,

the user enters two numbers and operation, then the program calculates

the result by (if …else if) statement.

Exercise 9: write a C++ Program that calculates the volume of blood

if it is a natural between 4-6

If less is suffering from a decrease in blood

If it has more than an increase in blood volume

Exercise 10: write a C++ program that prompt the user to enter number and determines
and prints whether it is (odd and negative - odd and positive – even and negative - even
and positive)

Exercise 11: correct the mistakes in the following program and after the correct write

the output of the program:

include<iostream.h>#

int main()

Int a=5;

int b=7;

If[b%2=1]

a=a+6;

b=b+4 ;

a++;

--b:

elsif(a%2=1)

a=a-6

b=b-4 ;

}
a=a+3:

b=b+2;

cout<<"a="<<a<<"\tb="<<b<<\n;

5) Laboratory Instructions
(a) Good Programming Practices
 Apply reasonable indentation in you program to make it more readable.
 Indent both body statements of an if…else statement.
 Always putting the braces in an if…else statement (or any control statement) helps
prevent their accidental omission.
(b) Some Common Programming Mistakes
 Using a keyword as an identifier is a syntax error.
 Spelling a keyword with any uppercase letter is a syntax error. All of C++’s
keyword contain only lowercase letters.
 Forgetting one or both of the braces that delimit a block can lead to syntax errors or
logic errors in a program.
 Placing a semicolon after the condition in an if statement leads to logic error in
single selection if statements and a syntax error in double-selection if…else
statements

Laboratory #5 – Control Structures I (switch ( ) )

1. Laboratory Objective
The objective of this laboratory is to train students on how and when to use switch in C+
+ control structures.

2. Laboratory Learning Outcomes: After conducting this laboratory student will


be able to:
Identify and practice using multiple conditional structure by using switch statement.

3. Laboratory Introductory Concepts

Structure of switch statement:

Switch (expression)

Case constant_1:

Block of Statements_1

Break;

Case constant_2:
Block of Statements_2

Break;

……

Default:

Default Block of Statements

4. Laboratory Exercises

Exercise 1: write a C++ program to print “Saturday” if the user enters 1

“Sunday” if the user enters 2 … etc. - using (switch)-.

Exercise 2: write a C++ Program like a calculator for the basic operations, the user enters two
numbers and operation, the program calculates the result by switch statement

Exercise 3: write a C++ program That calculates the rate of student

(Excellent, Very Good, Good, Accepted or Failed) by using switch statement.

Exercise 4: (Odd or Even) Write a C++ program that reads an integer and determines and
prints whether it is odd or even. [Hint: Use the remainder operator. An even number is a
multiple of two. Any multiple of two leaves a remainder of zero when divided by 2.]

Exercise 5: (Largest and Smallest Integers) Write a C++ program that reads 3 integers and
then determines and prints the largest and the smallest integers in the group. Use only the
programming techniques you have learned

Exercise 6: The cost of an international call from USA to Yemen is calculated as follows:
Connection fee is $2.00 for the first three minutes; and $0.45 for each additional minute.
Write a program that prompts the user to enter the number of minutes the call lasted and
outputs the amount due. Format your output with two decimal places.

Exercise 7: (Body Mass Index Calculator) we introduced the body mass index (BMI)
calculator in the formulas for calculating BMI are

BMI =weight In kilograms / (height In meters)2


Create a BMI calculator application that reads the user’s weight in pounds and height in
inches (or, if you prefer, the user’s weight in kilograms and height in meters), then
calculates and displays the user’s body mass index. Also, the application should display
the following information from the Department of Health and Human Services/National
Institutes of Health so the user can evaluate his/her BMI:

BMI VALUES
Underweight: less than 18.5
Normal: between 18.5 and 24.9
Overweight: between 25 and 29.9
Obese: 30 or greater

Exercise 8: write a C++ program which check the entered value (char or number or sign)
and print the kind of the value

Exercise 9: In a right triangle, the square of the length of one side is equal to the sum of
the squares of the lengths of the other two sides. Write a program that prompts the user to
enter the lengths of three sides of a triangle and then outputs a message indicating
whether the triangle is a right triangle.

Exercise 10:(Sales Commission Calculator) One large chemical company pays its
salespeople on a commission basis. The salespeople receive $200 per week plus 9% of
their gross sales for that week. For example, a salesperson who sells $5000 worth of
chemicals in a week receives $200 plus 9% of $5000, or a total of $650. Develop a program
that will input each salesperson’s gross sales for last week and will calculate and display
that salesperson's earnings. Process one salesperson's figures at a time.

Here is a sample input/output dialog:

Enter sales in dollars (-1 to end): 5000.00


Salary is: $650.00

Exercise 11: (Salary Calculator) Develop a program that will determine the gross pay for
each of several employees. The company pays “straight time” for the first 40 hours
worked by each employee and pays “time-and-a-half” for all hours worked in excess of 40
hours. You’re given a list of the employees of the company, the number of hours each
employee worked last week and the hourly rate of each employee. Your program should
input this information for each employee, and should determine
and display the employee's gross pay.

Here is a sample input/output dialog:

Enter # of hours worked (-1 to end): 39


Enter hourly rate of the worker ($00.00): 10.00
Salary is $390.00

Exercise 12: (Palindrome Tester) A palindrome is a number or a text phrase that reads the
same backward as forward. For example, each of the following five-digit integers is a
palindrome: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit
integer and determines whether or not it’s a palindrome. [Hint: Use the division and
remainder operators to separate the number into its individual digits.]
Laboratory #6 – Loops (1)

1. Laboratory objective:

the objective of this laboratory is to introduce students to Loops Concept using the 3 types of it
for, while and do ..while with their specific uses .

2. Laboratory Learning Outcomes:

after conducting this laboratory student will be able to repeat a block of code according to
program’s needs.

3. Laboratory Introductory Concepts:


a loop is a control structure type helps writing a very simple statement to produce a significantly
greater result simply by repetition.

there are 3 types of Loop Control Structure (for ( ) – while( ) – do while( ) ).

- FOR - for loops are the most useful type. The syntax for a for loop is:
for (variable initialization; condition; variable update) {

Code to execute while the condition is true

}
4. Laboratory Exercises:

Exercise 1: Write a program in C++ to print numbers from 1 to 10.

Exercise 2: Write a program in C++ to print sum of numbers from 20 to 50.

Exercise 3: identify and correct the errors in each of the following statements: -

a) For(x=100,x>=1,++x)
cout<<x<<endl;

b) The following code should output the odd integers from 19 to 1 :


for (x=19;x>1,x+=1)
cout<<x<<endl;

Exercise 4: Write a program that uses a for statement to sum a sequence of integers.
Assume that the first integer specifies the number of values remaining to be entered. Your
program should read only one value per input statement. atypical input sequence might be
5 100 200 300 400 500, where the 5 indicates that the subsequent 5 values are to be
summed.

Exercise 5: write a program that uses a for statement to calculate the average of several
integers. Assume the last value read is 9999. For example, the sequence 10 8 11 7 9999
indicates that the program should calculate the average of all the values preceding 9999.

Exercise 6: Write a program the uses a for statement to find the smallest of several
integers. Assume that the first value specifies the number of remaining values.

Exercise 7 : Write a program that uses a for statement to calculate and print the product of
the odd integers from 1 to 15 .

Exercise 8: Write a program that reads a nonnegative integer and uses for statement to
computes and print its factorial.

Exercise 9: Write a program in C++ to find the Greatest Common Divisor (GCD) of two
numbers. [ex: 1st number : 15 , 2nd number : 25 , greatest common divisor : 5]

Exercise 10: Write a program that uses a for statement to print a calendar by determining
the first day in the month.
Laboratory #7 – Loops (2)

1. Laboratory objective:

the objective of this laboratory is to introduce students to Loops Concept using the while and
do ..while with their specific uses .

2. Laboratory Learning Outcomes:

after conducting this laboratory students will be able to repeat a block of code according to
programs needs by using the while and do ..while .

3.Laboratory Introductory Concepts:

Structure of while ( )
WHILE - WHILE loops are very simple. The basic structure is:

while (condition)

//Code to execute while the condition is true

Structure of do while( )

DO...WHILE - DO...WHILE loops are useful for things that want to loop at least once. The
structure is:

do {

...

} while (condition);
5. Laboratory Exercises

Exercise 1: Identify and correct the errors in each of the following statements: -
a) The following code should output the even integers from 2 to100:
counter= 2;
do
{
cout<<counter << endl;
counter += 2;
} While (counter < 100 );

b) int c = 1;
While ( c <= 5 )
product *= c;
}

c) int x= 1,total;
while (x<= 10 )
{
total += x;
++x;
}

Exercise 2: What does the following programs print?


a) #include <iostream>
using namespace std;
int main()
{
int y;
int x= 1;
int total = 0;
while (x<= 10 )
{
y=x* x;
cout << y<<endl;
total += y;
x++;
}
Cout << "Total is " << total << endl;
}

b) #include <iostream>
using namespace std;
int main()
{
int count = 1; // initialize count
while ( count <= 10 )
{
cout << (count % 2 ? "****" : "++++++++")<<endl;
++count;
}
}
c) #include<iostream>
using namespace std;
int main()
{
Int total=0,
count=0,
number;
do
{
cin >> number;
total = total + number;
count++;
}
while (number!=-1);
cout<<"The number of data read is"<<count<<endl;
cout<<"The sum of the numbers entered is "<<total<<endl;
return 0;
}

Exercise 3: Write a C++ program that uses a while statement and the tab escape
sequence \t to print the following table of values:
N 10*N 100*N 1000*N
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000

Exercise 4: We say that a number or a sentence is a palindrome only and only if we could
read it the same from both sides, for example: 5532355 is considered a palindrome
number.
Write a program that uses a while statement to read a nonnegative integer containing of
seven numbers and determining whether it is palindrome or not.

Exercise 5: Write a program that uses a while statement to print English letters from A to Z
in an uppercase.

Exercise 6: Write a program that uses a while statement to print English letters from a to z
in a lowercase.

Exercise 7: Write a program that uses a while statement to calculate and print the product
of the odd integersfrom1 to 15.

Exercise 8: Write a program that uses a while to read a nonnegative integer and uses a for
statement to computes and prints its factorial.

Exercise 9: Write a program that uses a while statement to print a calendar by determining
the first day in the month.
Laboratory #8 C++: Nested control structure (Nested loops)

1. Laboratory Objective:
The objective of this laboratory is to introduce students to the nested loops in the C++ Language.

2. Laboratory Learning Outcomes:


After conducing this laboratory student will be able to put one control structure within another
and write nested loops with any kind of loops such as while – do-while and for in C+
+ Programs

3. Laboratory Introductory Concepts:


a. Nested loop concept.
The placing of one loop inside the body of another loop is called
nesting. When you "nest" two loops, the outer loop takes control of
the number of complete repetitions of the inner loop. While all types
of loops may be nested like while – do-while and for but , the most
commonly nested loops are for loops.

b. Example :
Suppose you want to create the following grid of numbers:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
There are five lines in this grid. Therefore, we use a for statement to
output these lines as follows:
for (int i = 1; i <= 5; i++)
//output a line of numbers
In the first line, we want to print the numbers 1 through 5, in the
second line we want
to print the numbers 2 through 6, and so on. Notice that the first line
starts with 1 and
when this line is printed, i is 1. Similarly, the second line starts with 2
and when this
line is printed, the value of i is 2, and so on. If i is 1, i + 4 is 5; if i is 2, i
+ 4 is 6; and
so on. Therefore, to print a line of numbers we can use the value of i as
the starting
number and the value of i + 4 as the limiting value. That is, consider
the following
for loop:
for (j = i; j <= i + 4; j++)
cout << j << " ";
A little more thought produces the following nested loops to output the
desired grid:
for (i = 1; i <= 5; i++)
{
for (j = i; j <= i + 4; j++)
cout << j << " ";
cout << endl;
}

To write the same program using While loop the code will be :

int i = 1;
while ( i <= 5 )
{
int j = i;
while ( j <= i + 4)
{
cout << j << " ";
j++;
}
cout << endl;
i++;
}

4. Laboratory Exercises

Exercise 1: Write a C++ Program that print a multiplication table.

Exercise 2: What is the outputs of the following programs?


A: B:
int main ()
int main () {
{ const int M=10;
for(int i=1;i<=5;i++) const int N=10;
{ int i,j;
for(int j=(i+1);j<=5;j++) for(i=1;i<=M;i++)
cout<<setw(5)<<j; {
cout<<endl; for(j=1;j<=N;j++)
} cout<<setw(3)<<M*(i-1)+j;
return 0; cout<<endl;
int main()
} }
{
int row = 10; // initialize row return 0;
int column; // declare column int main()}
C: {
while (row >= 1)
D: for( int I = 1; I <= 9; i++ )
{
column = 1; {
while (column <= 10 ) for( int j = 1; j<= (9-i) ; j++ )
{ cout << "";
cout << (row % 2 ? "<" : ">"); for( int j = 1; j <= I ; j++ )
++ column; cout << setw(1) << j;
} for( int j = (i-1); j >= 1; j--)
-- row; cout << setw(1) << j;
cout << endl; cout << endl;
} }
return 0; return 0;
} }
Exercise 3: Write a program that print prime numbers in the range from ( 1 - 50 ).

Exercise 4: Write a program that uses for statements to print the following patterns
separately, one below the other. Use for loops to generate the patterns. All asterisks (*)
should be printed by a single statement of the form cout << "*"; (Hint): The last two
patterns require that each line begin with an appropriate number of blanks.

Exercise 5: Write a program that prints the following diamond shape. You may use output
statements that print a single asterisk (*), a single blank or a single newline. Maximize your
use of repetition (with nested for statements) and minimize the number of output
statements.
Exercise 6: What does the following program segment do?

for ( i = 1; i <= 5; i++ )


{
for ( j = 1; j <= 3; j++ )
{
for ( k = 1; k <= 4; k++ )
cout << '*';
cout << endl;
}
cout << endl;
}

Exercise 7: Change the following program using Nested while

Int main ( )
{
for ( int i = 1; i < 5; i++ )
{
for ( int j = 1; j < 4; j++ )
cout << i + j << " ";
cout << endl;
}
return 0;
}

5. Laboratory Instructions:
(a) Some Good Programming Practices
 Too many levels of nesting can make a program difficult to understand . As a rule, try to avoid
using more than three levels of indentation.

 You can use nested loop from different kinds of loops ,for example, for loop inside while loop
or the opposite.
Laboratory #9 C++ One-Dimensional Arrays:

1. Laboratory Objective
The objective of this laboratory is to train students on how to use Arrays data structure in the
context of the C++ Programming Language.

2. Laboratory Learning Outcomes: After conducting this laboratory student will


be able to:
a. Declare one-Dimensional Arrays.
b. Use one-Dimensional Arrays in Simple Applications.
c. Apply C++ basic concepts in dealing with Arrays.

3. Laboratory Introductory Concepts


An array consists of a series of elements (variables) of the same type that are placed
consecutively in the computer’s memory such that the elements can be individually referenced by
adding an index to the array name.
Example: 
A[0] A[1] A[2] A[3] A[4]
-12 36 -120 72 255
Declaration of one dimensional array:
Data_Type Array_Name [elements];
Initialization of one dimensional array:
Data_Type Array_Name [elements]= {value_1, value_2, …, value_n-1};

4.Laboratory Exercises
Exercise 1: Identify and correct the errors in each of the following statements:-

a) arraySize = 10; // arraySize was declared const


b) Assume that int b[ 10 ]= {};
for ( int i= 0;i <= 10;++i )
b[ i ] = 1;
c) Assume that: int a[ 3 ];
cout << a[ 1 ]<< "" << a[ 2 ]<< "" << a[ 3 ]<<endl;
d) double f[ 3 ]={ 1.1, 10.01, 100.001, 1000.0001 };
e) Assume that: double d[ 2 ][ 10 ];
d[ 1, 9 ]= 2.345;

Exercise 2: Write C++ statements to accomplish each of the following:


a) Display the value of element 6 of character array f.
b) Input a value into element4 of one-dimensional floating-point array b.
c) Initialize each of the5 elements of one-dimensional integer array g to 8.
d) Total and print the elements of floating-point array c of 100 elements.
e) Copy array a into the first portion of array b. Assume double a[ 11 ], b[ 34 ];

Exercise 3: Write a program to find the smallest number in a one-dimensional array


containing 10 elements.

Exercise 4: Write a program to find the biggest number in a one-dimensional array


containing 10 elements.

Exercise 5: Write a program to read elements of a one dimensional array and then
calculating sum of odd numbers and even numbers separately.

Exercise 6: Write a program that print the index number and its contents of a one
dimensional array.

Exercise 7: Write a program that search for a specific element in a one dimensional array.

Exercise 8: Write a program that reads 10 numbers from keyboard and then print them in
the form number then asterisk, for example:1 2 3 4 5 will be 1*2*3*4*5.

Exercise 9: write a program that calculate the summation of two arrays and print result
from new array.

Exercise 10: write a program that calculate the repetition of numbers in an array, then print
each element with its repetition.

Exercise 11: write a program that reads 10 nonnegative elements and print them after
sorting them in an ascending order.

Exercise 12: write a program that reads 10 nonnegative elements and print them after
sorting them in an descending order.
Int main ( )
{
for ( int i = 1; i < 5; i++ )
{
for ( int j = 1; j < 4; j++ )
cout << i + j << " ";
cout << endl;
}
return 0;
}
C++ projects

These projects are examples for C++ projects, you can choose from these
projects or do any project you like.

 C++ project on quiz


 C++ Project for Shopping
 C++ Project for Calculator
 C++ Project for Date convertor
 C++ Project for Convert from any numeric system to another
system
 C++ Project for Encryption
 C++ Project for Number reader
 C++ Project for Age calculator
 C++ Project for X-O game
 C++ Project for give Information about countries…
 C++ Project for any Game…
 C++ Project for Coins convertor
 C++ Project on Phone contact
 C++ Project for Timer
 C++ Project on Solution for any problem in mathematic…
 C++ Project on any Educational program …

Notes:
 Every student must do different project
 You must understand your project well
 Grade depend on:
 quality of your project
 Over the understanding of your project
 Differentiate your project with other student’s projects

You might also like