NOTES C++ (Week 1-12)
NOTES C++ (Week 1-12)
Between high-level language and machine language there are assembly language also called symbolic machine
code. Assembly language are particularly computer architecture specific. Utility program (Assembler) is used
to convert assembly code into executable machine code. High Level Programming Language are portable but
require Interpretation or compiling to convert it into a machine language which is computer understood.
1. Machine languages
2. Assembly languages
3. High-level languages
Any computer can directly understand only its own machine language. Machine language is the "natural
language" of a computer and as such is defined by its hardware design. Machine languages generally consist of
strings of numbers (ultimately reduced to 1s and 0s) that instruct computers to perform their most
elementary operations one at a time. Machine languages are machine dependent (i.e., a particular machine
language can be used on only one type of computer).
Machine-language programming was simply too slow, tedious and error-prone for most programmers. Instead
of using the strings of numbers that computers could directly understand, programmers began using English-
like abbreviations to represent elementary operations. These abbreviations formed the basis of assembly
languages. Translator programs called assemblers were developed to convert early assembly-language
programs to machine language at computer speeds.
Computer usage increased rapidly with the advent of assembly languages, but programmers still had to use
many instructions to accomplish even the simplest tasks. To speed the programming process, high-level
languages were developed in which single statements could be written to accomplish substantial tasks.
Translator programs called compilers convert high-level language programs into machine language. High-level
languages allow programmers to write instructions that look almost like everyday English and contain
commonly used mathematical notations.
From the programmer's standpoint, obviously, high-level languages are preferable to machine and assembly
language. C, C++, Microsoft's .NET languages (e.g., Visual Basic .NET, Visual C++ .NET and C#) and Java are
among the most widely used high-level programming languages.
The process of compiling a high-level language program into machine language can take a considerable
amount of computer time. Interpreter programs were developed to execute high-level language programs
INTRODUCTION TO C++:
C++ programming language is an enhanced version of C language that provides object-oriented programming
(OOP) capabilities. It is a superset of C, which means that you can use a C++ compiler to compile C programs.
Object oriented programming techniques differ significantly from the sequential programming used in C
programming language.
The C language was evolved from B by Dennis Ritchie at Bell Laboratories. C uses many important concepts of
BCPL and B. C initially became widely known as the development language of the UNIX operating system.
Today, most operating systems are written in C and/or C++. C is now available for most computers and is
hardware independent. With careful design, it is possible to write C programs that are portable to most
computers.
The widespread use of C with various kinds of computers (sometimes called hardware platforms)
unfortunately led to many variations. This was a serious problem for program developers, who needed to
write portable programs that would run on several platforms. A standard version of C was needed. The
American National Standards Institute (ANSI) cooperated with the International Organization for
Standardization (ISO) to standardize C worldwide; the joint standard document was published in 1990 and is
referred to as ANSI/ISO 9899: 1990.
C++, an extension of C, was developed by Bjarne Stroustrup in the early 1980s at Bell Laboratories. C++
provides a number of features that "spruce up" the C language, but more importantly, it provides capabilities
for object-oriented programming.
A revolution is brewing in the software community. Building software quickly, correctly and economically
remains an elusive goal, and this at a time when the demand for new and more powerful software is soaring.
Objects are essentially reusable software components that model items in the real world. Software developers
are discovering that using a modular, object-oriented design and implementation approach can make them
much more productive than they can be with previous popular programming techniques. Object-oriented
programs are easier to understand, correct and modify.
Object files are intermediate files that represent an incomplete copy of the program: each source file only
expresses a piece of the program, so when it is compiled into an object file, the object file has some markers
indicating which missing pieces it depends on. The linker takes those object files and the compiled libraries of
predefined code that they rely on, fills in all the gaps, and spits out the final program, which can then be run
by the operating system (OS).
The compiler and linker are just regular programs. The step in the compilation process in which the compiler
reads the file is called parsing.
In C++, all these steps are performed ahead of time, before you start running a program. In some languages,
they are done during the execution process, which takes time. This is one of the reasons C++ code runs far
faster than code in many more recent languages.
OBJECT: Understanding Concept of Whitespace, Output Using cout, String Constants, Preprocessor
Directives, Header Files, Comments, Defining Integer Variables, Declarations and Definitions,
Variable Names Assignment Statements, Integer Constants, Output Variations, The endl
Manipulator, Input with cin.
PROGRAM 1:
Write down the following program and compile it. You can write skip comments that are written after each
line.
COMMENTS
Comments are removed by the C pre-processor before the resulting program code is compiled so the C
Compiler does not see them but they can be read by humans looking at the contents of your program file.
Single line comments start with // and multi line comments starts with /* and end with */
INTEGER VARIABLES
A variable has a name and can be given a value. Variables are located in particular places in the computer’s
memory. When a variable is given a value, that value is actually placed in the memory space assigned to the
variable. Integer variables represent integer numbers like 1, 30,000, and –27. The following statement is used
to declare the integer variable:
int var1;
PROGRAM 2:
int main()
{
cout << “My Name is XYZ” <<endl; //endl (end line)
cout << “My age is: ” << 18; //numbers without “ ”
cout << endl << “I am student of IICT”;
cout << “18 + 18 = ” << 18+18 << endl; //Adding two numbers
cout << “C++ is fun”;
return 0;
}
PROGRAM 3:
Write down the following program and compile it.
int main()
{
int a; //Integer type variable declaration
a = 10; //Assigning value to variable (initialization)
int b = 10; //Declaration + initialization
int c;
c = a + b; //Assigning sum of 2 variable into a variable
cout << “a = ” << a << endl;
cout << “b = ” << b << endl;
cout << “c = a + b =” << c << endl;
cout << “a + b = ” << a + b << endl;
cout << “a + b + c= ” << a + b + c;
return 0;
}
ARITHMETIC OPERATORS
The symbols +, -, *, / are the arithmetic operator used to perform addition, subtraction, multiplication and
division between two numbers or variables.
PROGRAM 4:
int main() {
int a, b; //Two Integer type variable declaration
float c; //float type variable declaration
Exercise 1:
Write down a program which takes the values of variable ‘a’ and ‘b’ as input and evaluate the following
equation:
x = a2 + 2ab + b2
Display the result of ‘x’
Exersice 2:
Write down a program which takes the temperature in Celsius °C from user and displays the output in
Fahrenheit °F
°F = (°C × 9/5) + 32
DATA TYPES
You may like to store information of various data types like character, wide character, integer, floating point,
double floating point, boolean etc. Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Take a simple arithmetic problem: what's left over when you divide 11 by 3? The answer is easy to compute:
divide 11 by 3 and take the remainder: 2. The modulus operator ('%'), that computes the remainder that
results from performing integer division.
+= Add AND assignment operator, It adds right operand to the left operand and C += A is equivalent to
assign the result to left operand. C=C+A
-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is equivalent to C
operand and assign the result to left operand. =C-A
*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is equivalent to
operand and assign the result to left operand. C=C*A
/= Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to
operand and assign the result to left operand. C=C/A
%= Modulus AND assignment operator, It takes modulus using two operands C %= A is equivalent to
and assign the result to left operand. C=C%A
PROGRAM 1:
#include <iostream>
using namespace std;
int main() {
char ch1 = 'A'; //define char variable as character
char ch2 = '\t'; //define char variable as tab
cout << ch1 << ch2; //display characters
ch1 = 'B'; //set char variable to char constant
cout << ch1; //display character
cout << '\n'; //display newline character
return 0;
}
EXERCISE 1:
Write a program which generate the following output on the screen you have to use scape sequences and you
cannot use endl:
“Welcome All” is a string constant
‘A’ is a character constant
\t is for tab
\n for new line
PROGRAM 2:
#include <iostream>
using namespace std;
int main(){
float rad; //variable of type float
const float PI = 3.14159F; //type const float
cout << "Enter radius of circle: "; //prompt
cin >> rad; //get radius
float area = PI * rad * rad; //find area
cout << "Area is " << area << endl; //display answer
return 0;
}
PROGRAM 3:
#include <iostream>
using namespace std;
int main() {
short a = 1234; //Short Integer type variable
unsigned short ua = 41234; //unsigned Short
int b = 3212; //Integer type variable
unsigned int ub = 54321; //unsigned int
long c = 123345435; //Long Integer type variable
unsigned long uc = 4111117295;
float d = 123.432; //Floating point type variable
double e = 4.12e223; //Double precision float type
long double f = 1.3e3212; //Long double type variable
char ch1 = ‘N’; //Character type variable
unsigned char ch2 = 203; //unsigned character
//Printing all variable values on screen
cout << “short variable= ” << a << endl;
cout << “unsigned short variable= ” << ua << endl;
cout << “int variable= ” << b << endl;
cout << “unsigned int variable= ” << ub <<endl;
cout << “long variable= ” << c << endl;
cout << “unsigned long variable= ” << uc <<endl;
cout << “float variable= ” << d << endl;
cout << “double variable= ” << e << endl;
cout << “long double variable= ” << f << endl;
cout << “char variable= ” << ch1 << endl;
cout << “unsigned char variable= ” << ch2 << endl;
return 0;
}
PROGRAM 4:
#include <iostream>
using namespace std;
int main()
{
cout << 6 % 8 << endl // 6
<< 8 % 8 << endl // 0
<< 9 % 8 << endl // 1
<< 10 % 8 << endl; // 2
return 0;
}
#include <iostream>
using namespace std;
int main() {
int ans = 27;
ans += 10; //same as: ans = ans + 10;
cout << ans << ", ";
ans -= 7; //same as: ans = ans - 7;
cout << ans << ", ";
ans *= 2; //same as: ans = ans * 2;
cout << ans << ", ";
ans /= 3; //same as: ans = ans / 3;
cout << ans << ", ";
ans %= 3; //same as: ans = ans % 3;
cout << ans;
return 0;
}
EXERCISE 2:
Write a program which takes 2 int values from user and then perform all five asthmatic operations on them.
The output should be like:
PROGRAM 6:
#include <iostream>
using namespace std;
int main() {
int c = 10;
cout << "c =" << c << endl; //displays 10
cout << "++c =" << ++c << endl; //displays 11 (prefix)
cout << "c =" << c << endl; //displays 11
cout << "c++ =" << c++ << endl; //displays 11 (postfix)
cout << "c =" << c << endl; //displays 12
cout << "--c =" << --c << endl; //displays 11 (prefix)
cout << "c =" << c << endl; //displays 11
cout << "c-- =" << c-- << endl; //displays 11 (postfix)
cout << "c =" << c << endl; //displays 10
return 0;
}
EXERCISE 1:
Write a program which takes the values of variable a, b and c from user at run time of program and calculates
the answer of x1 and x2 in Quadratic Equation. You can take extra variables for the calculation but the final
result must be stored in variable x1 and x2. The Equation is
EXERCISE 2:
Write a program which takes the radius of a circle and calculates the area and circumference of the circle. Use
pre define PI constant from cmath library
Input the radius(1/2 of diameter) of a circle : 5
The area of the circle is : 78.5397
The circumference of the circle is : 31.4159
CASTING
Type casting is a way to convert a variable from one data type to another data type. For example, if you want
to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values
from one type to another explicitly using the cast operator as follows:
(type_name) expression
There are several kinds of casts in Standard C++: static casts, dynamic casts, reinterpret casts, and const casts.
Here we’ll be concerned only with static casts. Here’s a statement that uses a C++ cast to change a variable of
type int into a variable of type char:
aCharVar = static_cast<char>(anIntVar);
AUTOMATIC CONVERSION
Type conversions can be implicit which is performed by the compiler automatically, When two operands of
different types are encountered in the same expression, the lower-type variable is converted to the type of
the higher-type variable. Types are considered “higher” or “lower,” based roughly on the order shown below:
Highest Lowest
long double double float long int short char
int main(){
int signedVar = 2000000000; //signed
unsigned int unsignVar = 2000000000; //unsigned
signedVar = (signedVar * 2) / 3; //calculation exceeds range
unsignVar = (unsignVar * 2) / 3; //calculation within range
cout << "signedVar = " << signedVar << endl; //wrong
cout << "unsignVar = " << unsignVar << endl; //OK
return 0;
}
PROGRAM 5: Demonstrating the casting in expressions.
#include <iostream>
using namespace std;
int main()
{
int signedVar = 2000000000; //signed
unsigned int unsignVar = 2000000000; //unsigned
signedVar = (((unsigned)signedVar * 2) / 3);
//calculation now will not exceeds range as the data is converted
//in unsigned during the calculation
unsignVar = (unsignVar * 2) / 3; //calculation within range
cout << "signedVar = " << signedVar << endl; //OK
cout << "unsignVar = " << unsignVar << endl; //OK
return 0;
}
PROGRAM 6: Demonstrating the static casting in expressions.
#include <iostream>
using namespace std;
int main()
{
int intVar = 1500000000; //1,500,000,000
intVar = (intVar * 10) / 10; //result too large
cout << “intVar = “ << intVar << endl; //wrong answer
intVar = 1500000000; //cast to double
intVar = (static_cast<double>(intVar) * 10) / 10;
cout << “intVar = “ << intVar << endl; //right answer
return 0;
}
This loop runs as long as the condition in the center is true. Note that there is no semi colon after the “for”
statement. If there is only one statement in the “for” loop then the braces may be removed. If we put a
semicolon after the for loop instruction then that loop will not work for any statement.
This loop runs as long as the condition in the parenthesis is true. Note that there is no semicolon after the
“while” statement. If there is only one statement in the “while” loop then the braces may be removed.
This loop runs as long as the condition in the parenthesis is true. Note that there is a semicolon after the
“while” statement. The difference between the “while” and the “do-while” statements is that in the “while”
loop the test condition is evaluated before the loop is executed, while in the “do” loop the test condition is
evaluated after the loop is executed. This implies that statements in a “do” loop are executed at least once.
However, the statements in the “while” loop are not executed if the condition is not satisfied.
#include <iostream>
using namespace std;
int main() {
for (int k = 1 ; k <= 10 ; k++ )
cout << "Name" <<endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
for (int k = 1 ; k <= 1000 ; k+=10 )
cout << k << " ";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
for (int k = 10 ; k >= 0 ; k-- )
cout << k << " ";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
for (int k = 1 ; k <= 10000 ; k = (k+k)*10 )
cout << k << " ";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int k, num;
cout << "Enter Table Number" ;
cin >> num;
for (k = 1 ; k <= 10 ; k++ )
cout << num << " * " << k << " = " << num*k << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int m, k = 0;
for ( ; k <= 10 ; )
{
cout << "Enter Marks" ;
cin >> m;
cout << "Marks = " << m;
k++;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int N = 5;
int i,j;
for (i=1; i<=N; i++)
{
for (j=1; j<=i; j++)
cout << "* ";
cout << endl;
}
return 0;
}
Exersice 1:
Write a program that prints the values by using for loop
10 100 1000 10000 100000 1000000 10000000 100000000
1000000000
Exersice 2:
Write a program that computes the nth Fibonacci number where n is a value input by the user.
Enter N: 10
Fibonacci series till 10th place:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Exersice 3:
Write a program to find the sum of the first N natural numbers, where the value of N is provided by
the user.
Enter N: 7
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
Exersice 4:
Write a program which takes a 3 numbers from users
1. Table number
2. Starting values of table
3. Ending value of table
Then it displays the table of the given number from starting value till ending value. For Example:
Enter Table Number: 7
Enter Starting Value: 6
Enter Ending Value: 12
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
7 x 11 = 77
7 x 12 = 84
#include <iostream>
#include <cmath>
#include<conio.h>
using namespace std;
int main() {
char ch = ‘y’;
double number, answer;
while (ch == ‘y’)
{
cout << "Enter a number: ";
cin >> number;
answer = sqrt(number);
cout << "Square root is "<< answer << endl;
cout << "Do you want the square root of another number?" << endl;
cout << "Press y for yes... " << endl << endl;
ch = getche();
}
return 0;
}
#include <iostream>
#include <cmath>
#include<conio.h>
using namespace std;
int main() {
char ch;
double number, answer;
do
{
cout << "Enter a number: ";
cin >> number;
answer = sqrt(number);
cout << "Square root is "<< answer << endl;
cout << "Do you want the square root of another number?" << endl;
cout << "Press y for yes... " << endl << endl;
ch = getche();
}
while (ch == ‘y’);
return 0;
}
INTRODUCTION
There are three major decision making structures. The ‘if’ statement, the ‘if-else’ statement, and the ‘switch’
statement. Another less commonly used structure is the conditional operator.
THE IF STATEMENT
The if statement enables you to test for a condition (such as whether two variables are equal) and branch to
different parts of your code, depending on the result or the conditions with relational and logical operators
are also included.
The simplest form of an ‘if’ statement is:
if (expression)
statement;
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Enter a number: ";
cin >> a; //get number
if (a == 10)
cout << "The number is equal to 10";
if (a > 10)
cout << "The number is greater than 10";
if (a < 10)
cout << "The number is less than 10";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter age: "; cin >> age; //get number
return 0;
}
#include <iostream>
#include <conio.h> // for getche()
using namespace std;
int main()
{
int chcount=0; //counts non-space characters
int wdcount=1; //counts spaces between words
char ch = 'a'; //ensure it isn't '\r'
RAND() FUNCTION
The rand() function is used to generate random numbers. If we generate a sequence of random number with
rand() function, it will create the same sequence again and again every time program runs.
int rand(void):
Returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX: is a constant whose default
value may vary between implementations but it is granted to be at least 32767.
#include <iostream>
#include <conio.h>
#include <cstdlib> // for rand() function
#include <iomanip> // for setw()
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
int main() {
int a;
char ch;
do{
int x = (rand() % 5) + 1;
cout<<endl<<"Enter number between 1 to 5...";
cin>>a;
if (a==x)
cout<<"You guessed the right number";
else
cout<<"Sorry try again the number was "<< x;
cout<<endl<<"Do you want to run again?"
<<endl<<"Press y for yes...";
ch = getch();
}
while(ch=='y');
return 0;
}
#include <iostream>
using namespace std;
int main() {
int marks;
float per;
cout << " Enter marks out of (800)"; cin >> marks;
per = (float)marks/800 * 100;
if (per >= 80)
cout << "Percentage = " << per <<" \t A Grade :-D ";
else if (per >= 70)
cout << "Percentage = " << per <<"\t B+ Grade :-D ";
else if (per >= 60)
cout << "Percentage = " << per <<"\t B Grade :-) ";
else if (per >= 50)
cout << "Percentage = " << per <<"\t C Grade :-| ";
else if (per >= 40)
cout << "Percentage = " << per <<"\t D Grade :-| ";
else
cout << "Percentage = " << per <<"\t Fail :-( ";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a;
char ch;
do
{
cout<<"Enter any number from 1 to 10: "; cin>>a;
cout<<"The number is ";
switch(a)
{
case 1: cout<<"One"; break;
case 2: cout<<"Two"; break;
case 3: cout<<"Three"; break;
case 4: cout<<"Four"; break;
case 5: cout<<"Five"; break;
case 6: cout<<"Six"; break;
case 7: cout<<"Seven"; break;
case 8: cout<<"Eight"; break;
case 9: cout<<"Nine"; break;
case 10: cout<<"Ten"; break;
default: cout<<"Sorry cannot convert this number";
}
cout<<endl<<"Do U want to continue.... (Y / N)?"; cin>>ch;
}
while (ch =='y');
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a, b;
char ch;
cout<<"Enter number operator number:";
cin>>a>>ch>>b;
switch(ch)
{
case '*':
cout<<"The answer is "<<a*b; break;
case '/':
if (b == 0)
{
cout<<"Cant devide with Zero"; break;
}
cout<<"The answer is "<<a/b; break;
case '-':
cout<<"The answer is "<<a-b; break;
case '+':
cout<<"The answer is "<<a+b; break;
default:
cout<<"Sorry wrong operator";
}
return 0;
}
Exercise 1:
Write a program that asks the user to type an integer and writes "YOU WIN" if the value is
between 56 and 78 (both included). In the other case it writes "YOU LOSE"
Exercise 2:
Write a program to input day number (1-7) and print day of week name using switch case.
Input day number(1-7): 2
The day is Tuesday
Exercise 3:
Write a program to input month number and print total number of days in month using switch...case
Input month number(1-12): 2
Total number of days = 28
Exercise 4:
Write two programs to check whether an alphabet is vowel or consonant. First program by using
switch statement and second by using else-if structure.
Input character: a
'a' is a vowel
Input character: b
'b' is a consonant
Exercise 4:
Write a program which prints ASCII table from 1 to 126
(Use setw() for arrangement and make sure there should be only 8 ASCII numbers and characters on
each line. Take hint from program 5 of this handout)
CONDITIONAL OPERATOR
The conditional operator (?:) is C’s only ternary operator; that is, it is the only operator to take three terms.
The conditional operator takes three expressions and returns a value:
This line is read as "If expression1 is true, return the value of expression2; otherwise, return the value of
expression3." Typically, this value would be assigned to a variable.
#include <iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter a, b ";
cin>>a>>b;
c = a > b ? a : b ;
cout<<"Larger number is: "<<c;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
for(int j=0; j<80; j++) //for every column,
{ //ch is ‘x’ if column is
char ch = (j%8) ? ‘ ‘ : ‘x’; //multiple of 8, and
cout << ch; //’ ‘ (space) otherwise
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter a, b and c: ";
cin>>a>>b>>c;
LOGICAL OPERATORS
While relational (comparison) operators can be used to test whether a particular condition is true or false,
they can only test one condition at a time. Often we need to know whether multiple conditions are true at
once and logical operators provide us with this capability to test multiple conditions. Depending upon the
requirement, proper logical operator is used. There are three logical operators:
a b a && b a b a || b
true true true true true true
true false false true false true
false true false false true true
false false false false false false
The ! operator is a unary operator, taking only one argument and negating its value:
a !a
true false
false true
#include <iostream>
using namespace std;
int main()
{
int age, height;
cout << "Enter age of candidate: "; cin >> age;
cout << "Enter height of candidate in cm: "; cin >> height;
if (age>=18 && height>=160)
cout << "The candidate is selected ";
else
cout << "Sorry! The candidate is not selected ";
return 0;
}
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
int month;
cout<<"Enter month in number: "; cin>>month;
if(month == 12 || month == 1 || month == 2)
cout<<"It is Winter";
else if(month == 3 || month == 4 || month == 5)
cout<<"It is Spring";
else if(month == 6 || month == 7 || month == 8)
cout<<"It is Summer";
else if(month == 9 || month == 10 || month == 11)
cout<<"It is Autumn";
else
cout<<"You entered wrong Month";
return 0;
}
PROGRAM 6: Demonstrates || (OR) operator and nested for loops
#include <iostream>
#include<conio.h>
using namespace std;
int main() {
int r, c, k ,j;
char ch;
do{
cout<<"Enter Number of rows:";
cin>>r;
cout<<"Printing Triangle:"<<endl;
for (k=1; k<=r ; k++){
BREAK STATEMENT
The break; statement terminates a loop (for, while and do..while loop) and a switch statement immediately
when it appears.
include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;
while (true) { // test expression is always true
cout << "Enter a number: "; cin >> number;
if (number != 0.0)
sum += number;
else
break; // terminates the loop if number equals 0.0
}
cout << "Sum = " << sum;
return 0;
}
#include <iostream>
using namespace std;
int main() {
long dividend, divisor;
char ch;
do {
cout << "Enter dividend: "; cin >> dividend;
cout << "Enter divisor: "; cin >> divisor;
if( divisor == 0 ) { //if attempt to divide by 0,
cout << "Illegal divisor\n"; //display message
continue; //go to top of loop
}
cout << "Quotient is " << dividend / divisor;
cout << ", remainder is " << dividend % divisor;
cout << "\nDo another? (y/n): "; cin >> ch;
} while( ch != 'n' );
return 0;
}
Exercise 1:
Write a program to input a character from user and check whether given character is
alphabet, digit or a special character. Use if-else for logic and if user press Enter only the
program should exit.
Input character: a
'a' is alphabet
Input character: A
'A' is alphabet
Input character: #
'#' is special character
Input character: 1
'1' is a number
Input character:
Exit
EXERCISE 2:
Write a program which prints the following pattern by using nested loops
< - >>>>>>>>>>
<< - >>>>>>>>>
<<< - >>>>>>>>
<<<< - >>>>>>>
<<<<< - >>>>>>
<<<<<< - >>>>>
<<<<<<< - >>>>
<<<<<<<< - >>>
<<<<<<<<< - >>
<<<<<<<<<< - >
EXERCISE 3:
Write a program which prints the following pattern by using nested loops
*
***
*****
*******
*********
***********
Exercise 4:
Write a program which takes a number as input from user between range (1 to 99) and converts the
number into words by using multiple switch cases.
Enter a number: 55
Fifty Five
Enter a number: 3
Three
Enter a number: 20
Twenty
Enter a Number: 0
Exit
OBJECT: To Understand Array Fundamentals, Defining Arrays, Array Elements, Accessing Array
Elements, Initializing Arrays, Operations on Arrays Multidimensional Arrays, Two
Dimensional Array
ARRAY INTRODUCTION
An array is used to store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All
arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.
DECLARING ARRAYS
To declare an array in C++, the programmer specifies the type of the elements and the number of elements
required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero
and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type
double, use this statement
double balance[10];
INITIALIZING ARRAYS
You can initialize C++ array elements either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we declare for
the array between square brackets [ ]. Following is an example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be
5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base
index. Following is the pictorial representation of the same array we discussed above
#include<iostream>
using namespace std;
int main() {
int arr[5];
int k;
return 0;
}
Exercise 1: Write a program that takes input of 5 elements for array int a[5] and the calculate the
sum and average of the elements of array.
#include<iostream>
using namespace std;
int main() {
int arr[10];
int loc=0, large, k;
for (k=0 ; k<10 ; k++){
cout<<"Enter element No." << k+1 << ": ";
cin>>arr[k];
}
large=arr[0];
for (k=0 ; k<10 ; k++)
if (large < arr[k]){
loc = k;
large=arr[k];
}
cout<<"The largest element is:" << arr[loc];
return 0;
}
PROGRAM 3: Demonstrates array initialization and shows days from start of year to date specified
#include<iostream>
using namespace std;
int main() {
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
cout << "\nEnter month (1 to 12): "; //get date
cin >> month;
cout << "Enter day (1 to 31): ";
cin >> day;
total_days = day; //separate days
for(int j=0; j<month-1; j++) //add days each month
total_days += days_per_month[j];
cout << "Total days from start of year is: " << total_days
<< endl;
return 0;
}
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace std;
int main() {
const int size=5;
int roll_no[size];
int marks[size];
float per[size];
char grade[size];
if(per[i]>=80) grade[i]='A';
else if(per[i]>=70 && per[i]<80) grade[i] = 'B';
else if(per[i]>=60 && per[i]<70) grade[i] = 'C';
else if(per[i]>=50 && per[i]<60) grade[i] = 'D';
else if(per[i]>=40 && per[i]<50) grade[i] = 'P';
else grade[i] = 'F';
}
return 0;
}
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of
the array, and i and j are the subscripts that uniquely identify each element in a.
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram.
int main() {
int arr[5][3];
cout<<"An Integer Double Dimensional Array..."<<endl;
cout<<"Enter elements"<<endl;
for (int r=0 ; r<5 ; r++)
for (int c=0; c<3; c++) {
cout<<"Enter arr[" << r << "]["<<c<<"]:";
cin>>arr[r][c];
}
cout<<"The elements in array are:"<<endl;
for (int r=0 ; r<5 ; r++){
for (int c=0; c<3; c++)
cout<<arr[r][c]<<" ";
cout<<endl;
}
return 0;
Exercise 3: Write a program in C++ for addition of two Matrices of same size (3 x 3).
Input the element of the square matrix (3 x 3 )
Input elements in the first matrix:
[0][0] : 9
[0][1] : 8
[0][2] : 7
[1][0] : 6
[1][1] : 5
[1][2] : 4
[2][0] : 3
[2][1] : 2
[2][2] : 1
STRINGS
Strings are used to represent text. They are set of characters that can also contain alphabets, spaces,
numbers and other symbols. C++ provides following two types of string representations:
The C-style character string.
The string class type introduced with Standard C++.
C-STRINGS
The C-String originated within the C language and continues to be supported within C++. This string is
actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one
more than the number of characters in the word "Hello."
Declaration Syntax:
char str [Size];
Initialization:
char str [] = {'H','e','l','l','o','\0'};
OR
char str[] = "Hello";
#include <iostream>
using namespace std;
int main()
{
char str1[] = {'H','e','l','l','o','\0'};
char str2[] = "Welcome";
cout<<str1<<" "<<str2<<endl;
char str3[20]; //string variable str
cout << "Enter a string: ";
cin.get(str3, 20); //put string in str
cout << "You entered: " << str3 << endl;
return 0;
}
#include <iostream>
using namespace std;
const int MAX = 2000;
char str[MAX];
int main()
{
cout << "Enter a string:"<<endl;
cin.get(str, MAX, '$'); //terminate with $
cout << "You entered:"<<endl << str << endl;
return 0;
}
You can also use the += operator to append a string to the end of an existing string:
s3 += s2;
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, nickname, address;
string greeting(“Hello, “);
cout << “Enter your full name: “;
getline(cin, full_name); //reads embedded blanks
cout << “Your full name is: “ << full_name << endl;
cout << “Enter your nickname: “;
cin >> nickname; //input to string object
greeting += nickname; //append name to greeting
cout << greeting << endl; //output: “Hello, Jim”
cout << “Enter your address on separate lines\n”;
cout << “Terminate with ‘$’\n”;
getline(cin, address, ‘$’); //reads multiple lines
cout << “Your address is: “ << address << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1 = "We all should respect everyone";
cout<<s1<<endl;
cout<<"Total Characters: "<<s1.length()<<endl;
int n;
n = s1.find("respect");
cout << "Found respect at index: " << n << endl;
n = s1.find_first_of("abcd");
cout << "First of spde at index: " << n << endl;
n = s1.find_first_not_of("aeiouAEIOU");
cout << "First consonant at: " << n << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "His Name is Rizwan";
string s2 = s1.substr(12);
cout<<s1<<endl;
cout<<s1.substr(4,4)<<":"<<s2;
return 0;
}
Function doesn’t need the size of the first dimension as two dimensional array is an array of arrays. It
doesn’t need to know how many elements there are, but it does need to know how big each element
is. Following is the declaration of one dimensional array:
void somefunc( int elem[] );
PROGRAM 1: Demonstrates a double dimensional array by creating a board for tic-tac-toe by using
a function which is taking array as an argument.
#include<iostream>
#include<conio.h>
using namespace std;
void display(char[3][3]);
int main(){
char arr[3][3]={{' ',' ',' '},
{' ',' ',' '},
{' ',' ',' '}};
for (int i=0 ; i<3 ; i++)
for (int j=0 ; j<3 ; j++)
{
display(arr);
cout<<"Please Enter X or O";
cin>>arr[i][j];
system("cls");
}
}
void display(char a[3][3])
{
cout<<"\n\n\n -----------\n";
for (int i=0 ; i<3 ; i++){
for (int j=0 ; j<3 ; j++)
cout<<" | "<<a[i][j];
cout<<" |\n -----------\n\n";
}
}
EXERCISE 1:
Write a simple program that asks the user for a Car registration number and then verifies that by:
Using a length function to make sure 6 characters were entered, use cout for displaying error
if user enters less or more letters.
Check the first three character to make sure they are alphabetic. You can use
the isalpha(char) function for this.
Check the last three character to make sure they are numeric. You can use
the isdigit(char) function for this.
Include “ctype.h” for both isalpha() and isdigit() functions
EXERCISE 2:
Write a program that reads a commercial website URL from user; you should expect that the URL
starts with ‘www.’ and ends with ‘.com’
Retrieve the name of the site and output it. For instance, if the user inputs www.yahoo.com, your
program should output yahoo.
FUNCTIONS
A function is a group of statements that together perform a task. Every C++ program has at least one function,
which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions
is up to you, but logically the division usually is such that each function performs a specific task. Function
provides following benefits:
• Provides reusability as we can use a function multiple times
• Make code organized and increase readability of a program as when the code increases is always
difficult to read.
• Decrease the length of code
• If there is a bug in the code it can be detected easily when we divided the code in function according
to tasks, thus provides maintainability
2. Defining a function:
A function definition provides the actual body of the function. The general form of a C++ function
definition is as follows:
Return Type: A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name: This is the actual name of the function.
Signature: The function name and the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function
does.
return_type = function_name(arguments);
#include <iostream>
using namespace std;
// function definition
void starline() //function declarator
{
for(int j=0; j<45; j++) //function body
cout << ‘*’;
cout << endl;
}
#include <iostream>
using namespace std;
void repchar(char, int); //function declaration
int main()
{
repchar(‘-’, 43); //call to function
cout << “Data type Range” << endl;
repchar(‘=’, 23); //call to function
cout << “char -128 to 127” << endl
<< “short -32,768 to 32,767” << endl
<< “int System dependent” << endl
<< “double -2,147,483,648 to 2,147,483,647” << endl;
repchar(‘-’, 43); //call to function
return 0;
}
void repchar(char ch, int n) //function declarator
{
for(int j=0; j<n; j++) //function body
cout << ch;
cout << endl;
}
PROGRAM 5: Demonstrate a function preceding main which return value and eliminates
unnecessary variables.
#include <iostream>
using namespace std;
float lbstokg(float pounds) {
return 0.453592 * pounds;
}
int main() {
float lbs;
cout << “\nEnter your weight in pounds: “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbstokg(lbs)<< endl;
return 0;
}
#include <iostream>
using namespace std;
void printNumberIfEven(int num)
{
if (num % 2 == 1) {
return;
}
cout << "even number; number is " << num << endl;
}
int main() {
int x;
cout<<"Enter a number:";
cin>>x;
printNumberIfEven(x);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
long raiseToPower(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result = result * base;
}
return result;
}
int main() {
int b,ex;
cout<<"Enter Base:";
cin>>b;
cout<<"Enter Power:";
cin>>ex;
cout << b << " ^ " << ex << " = "
<< raiseToPower(b,ex);
return 0;
}
Function doesn’t need the size of the first dimension as two dimensional array is an array of arrays. It
doesn’t need to know how many elements there are, but it does need to know how big each element
is. Far Example:
void display(char[][3]);
PROGRAM 8: Demonstrates a double dimensional array by creating a board for tic-tac-toe by using
a function which is taking array as an argument.
#include<iostream>
#include<conio.h>
using namespace std;
void display(char[3][3]);
int main(){
char arr[3][3]={{' ',' ',' '},
{' ',' ',' '},
{' ',' ',' '}};
for (int i=0 ; i<3 ; i++)
for (int j=0 ; j<3 ; j++)
{
display(arr);
cout<<"Please Enter X or O";
cin>>arr[i][j];
system("cls");
}
}
void display(char a[3][3])
{
cout<<"\n\n\n -----------\n";
for (int i=0 ; i<3 ; i++){
for (int j=0 ; j<3 ; j++)
cout<<" | "<<a[i][j];
cout<<" |\n -----------\n\n";
}
}
Exercise 1:
Write a program which contain a user define function to convert the temperature from Fahrenheit to
degree Celsius. The function should take one argument and return one value. Take the value of
Fahrenheit from user and the program should give the value in Celsius.
Use the formula: C = (F - 32) × 5/9
Exercise 2:
Write a function called hms_to_secs() that takes three int values—for hours, minutes, and seconds—
as arguments, and returns the equivalent time in seconds (type long). Create a program that uses this
function by obtaining a time value in hours, minutes, and seconds from the user (format 24:59:59),
calling the function, and displaying the value of seconds it returns. If user enters hour value greater
than 24 or minuets or second value greater than 60 the program should again ask for the values.
Enter Hours: 2
Enter Min: 23
Enter Sec: 12
The Value in Seconds is: 8592
Exiting Program
Enter Hours: 12
Enter Min: 70
Enter Hours: 1
Enter Min: 20
Enter Sec: 44
The Value in Seconds is: 4844
Exiting Program
Exercise 3:
Write a function called reversit() that reverses a C-string (an array of char). Use a for loop that swaps
the first and last characters, then the second and next-to-last characters, and so on. The string should
be passed to reversit() as an argument. Write a program to exercise reversit(). The program should
get a string from the user, call reversit(), and print out the result. Use an input method that allows
embedded blanks. Test the program with Napoleon’s famous phrase, “Able was I ere I saw Elba.”
#include <iostream>
using namespace std;
int main() {
void order(int&, int&); //prototype
int n1=99, n2=11; //this pair not ordered
int n3=22, n4=88; //this pair ordered
cout<<"Before Ordering:"<<endl;
cout << "n1=" << n1 << " n2=" << n2 << endl;
cout << "n3=" << n3 << " n4=" << n4 << endl;
#include <iostream>
using namespace std;
// finds integer and fractional parts of real number
void intfrac(float n, float& intp, float& fracp) {
long temp = (long)(n); //convert to long int,
intp = (float)(temp); //back to float
fracp = n - intp; //subtract integer part
}
int main() {
float number, intpart, fracpart; //float variables
do {
cout << "\nEnter a real number: "; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << "Integer part is " << intpart //print them
<< ", fraction part is " << fracpart << endl;
} while( number != 0.0 ); //exit loop on 0.0
return 0;
}
OVERLOADED FUNCTION
C++ allows you to specify more than one definition for a function in the same scope, which is called function
overloading. Overloaded functions have the same name except that both declarations have different
arguments and obviously different definition (implementation). The compiler determines the most
appropriate definition to use, by comparing the argument types you have used to call the function.
The definition of the function must differ from each other by the types and/or the number of arguments in the
argument list. You cannot overload function declarations that differ only by return type.
#include <iostream>
using namespace std;
void repchar(); //declarations
void repchar(char);
void repchar(char, int);
int main()
{
repchar();
repchar(‘=’);
repchar(‘+’, 30);
return 0;
}
// displays 45 asterisks
void repchar()
{
for(int j=0; j<45; j++) // always loops 45 times
cout << ‘*’; // always prints asterisk
cout << endl;
}
// displays 45 copies of specified character
void repchar(char ch)
{
for(int j=0; j<45; j++) // always loops 45 times
cout << ch; // prints specified character
cout << endl;
}
// displays specified number of copies of specified character
void repchar(char ch, int n)
{
for(int j=0; j<n; j++) // loops n times
cout << ch; // prints specified character
cout << endl;
}
RECURSION
Recursion involves a function calling itself. This sounds rather improbable, and indeed a function calling itself
is often a bug. However, when used correctly this technique can be surprisingly powerful. Every recursive
function must be provided with a way to end the recursion. Otherwise it will call itself forever and crash the
program.
VARIABLE SCOPE
Where a variable was declared, determines where it can be accessed from
Contains two parameters:
Variable visibility
Variable lifetime
LOCAL VARIABLE:
Variables that are declared inside a function or block are local variables. They can be used only by statements
that are inside that function or block of code. Local variables are not known to functions outside their own.
Visibility: Inside function or block
Lifetime: when the function or blocks ends
GLOBAL VARIABLE:
Global variables are defined outside of all the functions, usually on top of the program. The global variables
will hold their value throughout the life-time of your program. A global variable can be accessed by any
function. That is, a global variable is available for use throughout your entire program after its declaration.
Visibility: Everywhere in program
Lifetime: When program ends
#include <iostream>
#include <conio.h>
using namespace std;
void getachar()
{ //getachar() accesses ch
ch = getch();
}
void putachar()
{ //putachar() accesses ch
cout << ch;
}
int main()
{
cout<<”Enter a Phrase”<<endl;
while( ch != '\r' ) //main() accesses ch
{
getachar();
putachar();
}
cout << endl;
return 0;
}
STATIC VARIABLE
A static local variable has the visibility of an automatic local variable (that is, inside the function containing it).
However, its lifetime is the same as that of a global variable, except that it doesn’t come into existence until
the first call to the function containing it. Thereafter it remains in existence for the life of the program.
Visibility: Can be local or global
Lifetime: When Program ends
#include <iostream>
using namespace std;
int main() {
float data=1, avg;
while( data != 0 )
{
cout << "Enter a number: ";
cin >> data;
avg = getavg(data);
cout << "New average is " << avg << endl;
}
return 0;
}
EXERCISE 1:
Write a function that, when you call it, displays a message telling how many times it has been called: “I have
been called 3 times”, for instance. Write a main() program that calls this function at least 10 times (you can
use a loop to call the function multiple times).
EXERCISE 2:
Write a program which has 3 overloaded function with same name sum() but have different number or types
of arguments.
RETURN BY REFRENCE
In C++ Programming, not only can you pass values by reference to a function but you can also return a value
by reference.
#include <iostream>
using namespace std;
int x; // global variable
int& setx(); // function declaration
int main()
{ // set x to a value, using
setx() = 92; // function call on left side
cout << “x=” << x << endl; // display new value in x
return 0;
}
//--------------------------------------------------------------
int& setx()
{
return x; // returns the value to be modified
}
In program above, the return type of function setx() is int&. Hence, this function returns a reference of the
variable x.
The return statement is return x;. Unlike return by value, this statement doesn't return value of x, instead it
returns the variable itself (address).
So, when the variable is returned, it can be assigned a value as done in setx() = 92;
This stores 92 to the variable x, which is displayed onto the screen.
Ordinary function returns value but this function doesn't. Hence, you cannot return a constant from the
function.
int& test() {
return 2;
}
INTRODUCTION
There are many instances in programming where we need more than one variable in order to represent an
object. For example, to represent yourself, you might want to store your name, your birthday, your height,
your weight, or any other number of characteristics about yourself. You could do so like this:
char myName[30];
int myBirthYear;
int myBirthMonth;
int myBirthDay;
int myHeightInches;
int myWeightPounds;
However, you now have 6 independent variables that are not grouped in any way. If you wanted to pass
information about yourself to a function, you’d have to pass each variable individually. Furthermore, if you
wanted to store information about someone else, you’d have to declare 6 more variables for each additional
person! As you can see, this can quickly get out of control.
Fortunately, C++ allows us to create our own user-defined aggregate data types. An aggregate data type is a
data type that groups multiple individual variables together. One of the simplest aggregate data type is the
struct. A struct (short for structure) allows us to group variables of mixed data types together into a single
unit.
Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can
begin using it. To do this, we declare our struct using the struct keyword. Here is an example of a struct
declaration:
struct Employee
{
short id;
int age;
double wage;
};
This tells the compiler that we are defining a struct named Employee. The Employee struct contains 3
variables inside of it: a short named id, an int named age, and a double named wage. These variables that are
part of the struct are called members (or fields). Keep in mind that Employee is just a declaration -- even
though we are telling the compiler that the struct will have member variables, no memory is allocated at this
time. By convention, struct names start with a capital letter to distinguish them from variable names.
In order to use the Employee struct, we simply declare a variable of type Employee:
Employee joe;
// struct Employee is capitalized, variable joe is not
This defines a variable of type Employee named joe. As with normal variables, defining a struct variable
allocates memory for that variable.
When we define a variable such as Employee joe, joe refers to the entire struct (which contains the member
variables). In order to access the individual members, we use the member selection operator (which is a
period). Here is an example of using the member selection operator to initialize each member variable:
As with normal variables, struct member variables are not initialized, and will typically contain junk. We must
initialize them manually.
In the above example, it is very easy to tell which member variables belong to Joe and which belong to Frank.
This provides a much higher level of organization than individual variables would. Furthermore, because Joe’s
and Frank’s members have the same names, this provides consistency across multiple variables of the same
struct type. Struct member variables act just like normal variables, so it is possible to do normal operations on
them:
INITIALIZER LISTS
Initializing structs by assigning values member by member is a little cumbersome, so C++ supports a faster way
to initialize structs using an initializer list. This allows you to initialize some or all the members of a struct at
declaration time.
struct Employee {
short id;
int age;
double wage;
};
#include <iostream>
using namespace std;
struct Employee {
short id;
int age;
double wage;
};
int main() {
Employee joe;
joe.id = 14;
joe.age = 32;
joe.wage = 24.15;
ARRAYS OF STRUCTURES
Arrays can contain structures as well as simple data types
#include <iostream>
using namespace std;
const int SIZE = 4; //number of parts in array
int main()
{
int n;
part apart[SIZE]; //define array of structures
for(n=0; n<SIZE; n++) //get values for all members
{
cout << endl;
cout << “Enter model number: “;
cin >> apart[n].modelnumber; //get model number
cout << “Enter part number: “;
cin >> apart[n].partnumber; //get part number
cout << “Enter cost: “;
cin >> apart[n].cost; //get cost
}
cout << endl;
for(n=0; n<SIZE; n++) //show values for all members
{
cout << “Model “ << apart[n].modelnumber;
cout << “ Part “ << apart[n].partnumber;
cout << “ Cost “ << apart[n].cost << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
EXERCISE 2:
Use code of program 3and delete the Box structure
Create a structure called Cube from Distance structure.
Create four variable of Distance structure in cube structure for height, width, depth and volume.
Initialize height, width and depth and multiply the values of 3 distance variables and get value of
volume. Finally print the results.
PROGRAM 6: Demonstrate passing a structure to function and returning a function from structure.
#include <iostream>
using namespace std;
int main()
{
Distance d1, d2, d3; //define three lengths
//get length d1 from user
cout << “\nEnter feet: “; cin >> d1.feet;
cout << “Enter inches: “; cin >> d1.inches;
//get length d2 from user
cout << “\nEnter feet: “; cin >> d2.feet;
cout << “Enter inches: “; cin >> d2.inches;
d3 = addengl(d1, d2); //d3 is sum of d1 and d2
cout << endl;
engldisp(d1); cout << “ + “; //display all lengths
engldisp(d2); cout << “ = “;
engldisp(d3); cout << endl;
return 0;
}