0% found this document useful (0 votes)
47 views

NOTES C++ (Week 1-12)

This document provides an overview of programming fundamentals and C++. It introduces the C++ programming language, its history and evolution from C. It describes the hierarchy of computer languages from machine language to assembly to high-level languages like C++. It also discusses integrated development environments and the compilation process for converting source code into executable programs.

Uploaded by

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

NOTES C++ (Week 1-12)

This document provides an overview of programming fundamentals and C++. It introduces the C++ programming language, its history and evolution from C. It describes the hierarchy of computer languages from machine language to assembly to high-level languages like C++. It also discusses integrated development environments and the compilation process for converting source code into executable programs.

Uploaded by

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

LECTURE NOTES / LAB HANDOUTS

PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12


OBJECT:
 Introduction of C++ programming Language
 Introduction of Dev C++ Programming Environment
 Basic Program writing and error correction.
 Output using cout, Preprocessor Directives

INTRODUCTION TO PROGRAMMING LANGUAGES


A computer is a computational device which is used to process the data under the control of a computer
program. Program is a sequence of instruction along with data. While executing the program, raw data is
processed into a desired output format. These computer programs are written in a programming language
which are high level languages. High level languages are nearly human languages which are more complex
than the computer understandable language which are called machine language, or low level language.

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.

HIERARCHY OF COMPUTER LANGUAGE


Programmers write instructions in various programming languages, some directly understandable by
computers and others requiring intermediate translation steps. Hundreds of computer languages are in use
today. These may be divided into three general types

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

Course Instructor: Nazish Basir Page: 1/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
directly, although much more slowly. Interpreters are popular in program development environments in
which new features are being added and errors corrected. Once a program is fully developed, a compiled
version can be produced to run most efficiently.

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.

HISTORY OF C AND C++


C++ evolved from C, which evolved from two previous programming languages, BCPL and B. BCPL was
developed in 1967 by Martin Richards as a language for writing operating-systems software and compilers for
operating systems. Ken Thompson modeled many features in his language B after their counterparts in BCPL
and used B to create early versions of the UNIX operating system at Bell Laboratories in 1970.

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.

THE INTEGRATED DEVELOPMENT ENVIRONMENT (IDE):


Turbo C++ compiler has its own built-in text editor. The files you create with text editor are called source files,
and for C++ they typically are named with the extension .CPP, .CP, or .C.
The C++ Developing Environment, also called as Programmer’s Platform, is a screen display with windows and
pull-down menus. The program listing, error messages and other information are displayed in separate
windows. The menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution.

Course Instructor: Nazish Basir Page: 2/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

USING DEV C++ IDE


Dev-C++ is a full-featured integrated development environment (IDE), which is able to create Windows or
DOS-based C/C++ programs. You have to install the Dev C++ IDE then to invoke the IDE double click on the
icon available on desktop.

Figure 1: Dev C++ IDE

CREATING NEW SOURCE FILE


Click on “new” icon and select “Source File” see figure 2. You can also press the ctrl + N shortcut.

Figure 2: Creating new Source File.

TYPING AND COMPILING YOUR FIRST PROGRAM


Now type your program as shown in figure 3. Save you program by pressing “ctrl + S”, give any name to you
file. Now click on “Compile and Run” icon to see the output of your program.

Course Instructor: Nazish Basir Page: 3/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Figure 3: Typing and running the program

THE COMPILATION PROCESS


A program goes from text files (or source files)to processor instructions as follows:

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.

Course Instructor: Nazish Basir Page: 4/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 5/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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.

#include <iostream> //preprocessor directive


using namespace std;

int main() //function name main


{ //start of function body
cout << “This is my first program in C++”; //statement
return 0; //statement
} //end function body

THE #INCLUDE DIRECTIVE


Include the contents of another file, commonly called a header file, in your file. The header file contains the
declaration of different functions and objects. We have included “iostream.h” to use “cout”, “cin” and “endl”
in our program.

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 */

THE MAIN() FUNCTION


When you run a C++ program, the first statement executed will be at the beginning of a function called main().
If there is no function called main() in your program, an error will be reported when you run the program.

OUTPUT USING COUT


The cout causes the phrase in quotation marks (called a string constant) to be displayed on the screen. The
identifier cout (pronounced “C out”) is actually an object. It is predefined in C++ to correspond to the standard
output stream. A stream is an abstraction that refers to a flow of data. The operator << is called the insertion
or put to operator. It directs the contents of the variable on its right to the object on its left.

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;

Course Instructor: Nazish Basir Page: 6/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
ASSIGNMENT STATEMENTS
The equal sign (=) causes the value on the right to be assigned to the variable on the left.
var1 = 10;

PROGRAM 2:

Write down the following program and compile it.

#include <iostream> //preprocessor directive


using namespace std;

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.

#include <iostream> //preprocessor directive


using namespace std;

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;
}

Course Instructor: Nazish Basir Page: 7/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
INPUT WITH CIN
The cin causes the program to wait for the user to type in a value. The value is placed in a variable. The
keyword cin (pronounced “C in”) is an object, predefined in C++ to correspond to the standard input stream.
This stream represents data coming from the keyboard. The >> is the extraction or get from operator. It takes
the value from the stream object on its left and places it in the variable on its right. For Example:
cin >> var1;

ARITHMETIC OPERATORS
The symbols +, -, *, / are the arithmetic operator used to perform addition, subtraction, multiplication and
division between two numbers or variables.

PROGRAM 4:

Write down the following program and compile it.

#include <iostream> //preprocessor directive


using namespace std;

int main() {
int a, b; //Two Integer type variable declaration
float c; //float type variable declaration

cout << “Enter first value”;


cin>>a;
cout << “Enter second value”;
cin>>b;
c = a + b; //addition
cout << “a + b = ” << c << endl;
c = a - b; //subtraction
cout << “a - b = ” << c << endl;
c = a * b; //multiplication
cout << “a * b = ” << c << endl;
c = a / b; //devision
cout << “a / b = ” << c ;
return 0;
}

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

Course Instructor: Nazish Basir Page: 8/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 9/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT:

 Simple data types, variables and constants,


 Arithmetic operators, arithmetic assignment operators, increment and decrement operators
 Escape sequences.

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.

Data Type Range No. of Bits in Memory


Integers: Used to store whole numbers. C++ supports several integer types, having different sizes for storing
signed (both negative and positive) and unsigned numbers
Short -32768  32767 16 bit
unsigned short 0  65535 16 bit
int -32768  32767 16 bit or
-2147483648  2147483647 32 bit
unsigned int 0  65535 16 bit or
0  4294967295 32 bit
long -2147483648  2147483647 32 bit
unsigned long 0  4294967295 32 bit
Floating point: Floating point types are used to store numbers that contain decimal point (real numbers). C++
supports several floating point types, having different sizes.
float 10-38  1038 32 bit
double 10  10
-308 308
64 bit
long double 10-4932  104932 80 bit
Character: Used to hold single character can also store number (ASCII Code of a character)
Char Can also store integers (-128  127) 8 bit
unsigned char Can also store integers (0  255) 8 bit
Boolean: Used two store only two types of values TRUE or FALSE. Can be used in decision making statements.
Bool True / False 8 bit

RULES FOR NAMING VARIABLES:

 Variable names must begin with a letter.


 Variable names can contain letters, numbers and the underscore.
 Variable names cannot contain spaces
 Variable name cannot be a keyword or a reserved word
 Variable names cannot contain special characters such as all operators, #, <, +, etc.
 C++ is a case-sensitive language. Variable names written in capital letters differ from variable names
with the same name but written in small letters. For example, the variable name EXFORSYS differs
from the variable name exforsys.

Course Instructor: Nazish Basir Page: 10/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
CONSTANTS:
Constants, like variables, contain data type but constants have fixed value and that value cannot be changed
in the program. There are 2 ways to declare a constant
 const data_type const_name = value; (Example: const int PI = 3.14; )
 #define const_name value (Example: #define PI 3.14 )

REMAINDER (MODULUS) OPERATOR

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.

INCREMENT AND DECREMENT OPERATORS


The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand.
x = x+1; is the same as x++;
And
x = x-1; is the same as x--;
Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand.
For example:
x = x+1; can be written as
++x; // prefix form
or as
x++; // postfix form
When an increment or decrement is used as part of an expression, there is an important difference in prefix
and postfix forms. If you are using prefix form then increment or decrement will be done before rest of the
expression, and if you are using postfix form, then increment or decrement will be done after the complete
expression is evaluated.

ARITHMETIC ASSIGNMENT OPERATORS:

+= 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

Course Instructor: Nazish Basir Page: 11/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
ESCAPE SEQUENCES SUMMARY:

Escape Sequence Description


\' Single quote
\” Double quote
\\ Backslash
\nnn Octal number (nnn)
\0 Null character (really just the octal number zero)
\a Audible bell
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\xnnn Hexadecimal number (nnn)

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;
}

Course Instructor: Nazish Basir Page: 12/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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;
}

Course Instructor: Nazish Basir Page: 13/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 5:

#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:

Enter First Number: 45


Enter Second Number: 34
45 + 34 = 79
45 - 34 = 11
45 x 34 = 1530
45 / 34 = 1.3235
45 % 34 = 11

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;
}

Course Instructor: Nazish Basir Page: 14/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 15/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT:
 To understand some library functions.
 To demonstrate setw() manipulator
 Data type automatic conversion and casting.

PROGRAM 1: Demonstrating the library function sqrt().

#include <iostream> //for cout, etc.


#include <cmath> //for sqrt()
using namespace std;
int main()
{
double number, answer; //sqrt() requires type double
cout << “Enter a number: “;
cin >> number; //get the number
answer = sqrt(number); //find square root
cout << “Square root is “ << answer << endl; //display it
return 0;
} //end function body

PROGRAM 2: Demonstrating the library function pow().

#include <iostream> //for cout, etc.


#include <cmath> //for pow()
using namespace std;
int main()
{
int num, power;
double ans;
cout << "Enter a number: ";
cin >> num; //get the number
cout<<"Enter power";
cin>>power;
ans = pow(num, power);
cout << num << " power " << power << " = " << ans << endl;
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

Course Instructor: Nazish Basir Page: 16/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
THE SETW() MANIPULATOR
The setw manipulator causes the number (or string) that follows it in the stream to be printed within a field n
characters wide, where n is the argument to setw(n). The value is right justified within the field. The
declarations for the manipulators (except endl) are not in the usual IOSTREAM header file, but in a separate
header file called IOMANIP. When you use these manipulators you must #include this header file in your
program.

PROGRAM 3: Demonstrating the setw() Manipulator.


#include <iostream>
#include <iomanip> // for setw
using namespace std;
int main(){
int m1=512, m2=612, m3=92;
cout << setw(15) << "NAME" << setw(8) << "MARKS" << endl
<< setw(15) << "Ali Ahmed" << setw(8) << m1 << endl
<< setw(15) << "Nabeel Arif" << setw(8) << m2 << endl
<< setw(15) << "Adeel Rasheed" << setw(8) << m3 << endl;
return 0;
}

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

Course Instructor: Nazish Basir Page: 17/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 4: Demonstrating the automatic conversion in expressions.


#include <iostream>
using namespace std;

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;
}

Course Instructor: Nazish Basir Page: 18/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 19/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

OBJECT: To understand Relational Operators and Loops


RELATIONAL OPERATORS SUMMARY
Two expressions can be compared using relational and equality operators. For example, to know if two values
are equal or if one is greater than the other. The result of such an operation is either true or false (i.e., a
Boolean value).

> Greater Than < Less Than


== Equal To != Not Equal To
>= Greater Than or Equal To < Less Than or Equal To

THE FOR LOOP


for ( initialization ; Test Condition ; increment or decrement )
{
Body of the Loop;
}

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.

THE WHILE LOOP


while ( condition is true )
{
Body of the Loop;
}

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.

THE DO-WHILE LOOP


do
{
Body of the Loop;
}
while(condition is true);

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.

Course Instructor: Nazish Basir Page: 20/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 1: Demonstrating the simple for loop

#include <iostream>
using namespace std;
int main() {
for (int k = 1 ; k <= 10 ; k++ )
cout << "Name" <<endl;
return 0;
}

PROGRAM 2: Demonstrating the simple for loop

#include <iostream>
using namespace std;
int main()
{
for (int k = 1 ; k <= 1000 ; k+=10 )
cout << k << " ";
return 0;
}

PROGRAM 3: Demonstrating the simple for loop

#include <iostream>
using namespace std;
int main()
{
for (int k = 10 ; k >= 0 ; k-- )
cout << k << " ";
return 0;
}

PROGRAM 4: Demonstrating the simple for loop

#include <iostream>
using namespace std;
int main()
{
for (int k = 1 ; k <= 10000 ; k = (k+k)*10 )
cout << k << " ";
return 0;
}

Course Instructor: Nazish Basir Page: 21/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 5: Demonstrating the simple for loop

#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;
}

PROGRAM 6: Demonstrating the simple for loop

#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;
}

Course Instructor: Nazish Basir Page: 22/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 7: Demonstrating the nested for loops

#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;
}

for (i=N; i>=1; i--)


{
for (j=1; j<=i; j++)
cout << "* ";
cout << endl;
}

return 0;
}

Course Instructor: Nazish Basir Page: 23/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

Course Instructor: Nazish Basir Page: 24/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 8: Demonstrating the simple while loop

#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;
}

PROGRAM 9: Demonstrating the simple do-while loop

#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;
}

Course Instructor: Nazish Basir Page: 25/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 26/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT: To understand if-else statement and switch statement

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;

THE IF-ELSE STATEMENT


Often your program will want to take one branch if your condition is true, another if it is false. If only one
statement is to be followed by the ‘if’ or ‘else’ condition then there is no need of parenthesis. The keyword
else can be used to perform this functionality:
if (expression)
{
statement/s;
}
else
{
statement/s;
}

PROGRAM 1: Demonstrating the simple if 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;
}

Course Instructor: Nazish Basir Page: 27/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 2: Demonstrating the simple if-else statement

#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter age: "; cin >> age; //get number

if (age <= 15)


cout << " Welcome to children gift shop";
else
cout << " Welcome to glossary shop";

return 0;
}

PROGRAM 3: Demonstrating the if-else statement inside a for loop

#include <process.h> //for exit()


#include <iostream>
using namespace std;
int main()
{
unsigned long n, j;
cout << "Enter a number: "; cin >> n; //get number to test

for(j=2; j <= n/2; j++) //divide by every integer from


if(n%j == 0) //2 on up; if remainder is 0,
{ //it's divisible by j
cout << "It's not prime; divisible by " << j << endl;
exit(0); //exit from the program
}
cout << "It's prime\n";
return 0;
}

Course Instructor: Nazish Basir Page: 28/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 4: Demonstrating the if-else statement inside a while loop

#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'

cout << "Enter a phrase: ";


while( ch != '\r' ) //loop until Enter typed
{
ch = getche(); //read one character
if( ch==' ' ) //if it's a space
wdcount++; //count a word
else //otherwise,
chcount++; //count a character
} //display results
cout << "\nWords=" << wdcount << endl
<< "Letters=" << (chcount-1) << endl;
return 0;
}

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.

PROGRAM 5: Demonstrating the rand() function

#include <iostream>
#include <conio.h>
#include <cstdlib> // for rand() function
#include <iomanip> // for setw()

using namespace std;


int main() {
cout<<"RAND_MAX = "<<RAND_MAX<<endl;
for (int a=1 ; a<=10 ; a++)
if(a%4) //to display 4 values in one line
cout<<setw(8)<<rand();
else
cout<<setw(8)<<rand()<<endl;
return 0;
}

Course Instructor: Nazish Basir Page: 29/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 6: Demonstrating the if-else inside do-while loop

#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;
}

Course Instructor: Nazish Basir Page: 30/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
IF...ELSE IF...ELSE STATEMENT
An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement. Once an else if succeeds, none of the remaining else if's or else's
will be tested.

PROGRAM 7: Demonstrate the else-if structure

#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;
}

THE SWITCH STATEMENT


Unlike if, which evaluates one value, switch statements allow you to branch on any of a number of different
values. There must be break at the end of the statements of each case otherwise all the preceding cases will
be executed including the default condition. The general form of the switch statement is:

switch (identifier variable)


{
case identifier One:
statement(s);
break;
case identifier Two:
statement(s);
break;
....
case identifier N:
statement(s);
break;
default:
statement(s);
}

PROGRAM 8: Demonstrating the switch statement

Course Instructor: Nazish Basir Page: 31/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

#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;
}

Course Instructor: Nazish Basir Page: 32/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 9 Demonstrating the switch statement

#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;
}

Course Instructor: Nazish Basir Page: 33/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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)

Course Instructor: Nazish Basir Page: 34/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 35/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT: To understand Conditional Operator, Logical Operators, break keyword, continue keyword,
nested loops, and combination of all these statements.

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:

(expression1) ? (expression2) : (expression3)

It replaces the following statements of if else structure


if(a>b)
c=a;
else
c=b;
can be replaced by
c = (a>b) ? a : b

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.

PROGRAM 1: Demonstrates conditional operator

#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;
}

PROGRAM 2: Demonstrates conditional operator

#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;
}

Course Instructor: Nazish Basir Page: 36/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 3: Demonstrates nested conditional operator

#include <iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter a, b and c: ";
cin>>a>>b>>c;

cout<<"Larger number is: "


<<((((a>b)? a : b) > c) ? ((a>b)? a : b) : c);
return 0;
}

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:

Operator Symbol Form Operation


Logical NOT ! !x true if x is false, or false if x is true
Logical AND && x && y true if both x and y are true, false otherwise
Logical OR || x || y false if both x and y are false, true otherwise

The operators return true or false, according to the rules of logic:

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

Examples using logical operators (assume x = 6 and y = 2):

!(x > 2) → false


(x > y) && (y > 0) → true
(x < y) && (y > 0) → false
(x < y) || (y > 0) → true

Course Instructor: Nazish Basir Page: 37/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 4: Demonstrates && (AND) operator

#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;
}

PROGRAM 5: Demonstrates || (OR) operator

#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++){

Course Instructor: Nazish Basir Page: 38/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
for (j=1; j<=k; j++)
cout<<'*';
cout<<endl;
}
cout<<"Enter Number of rows:";
cin>>r;
cout<<"Enter Number of columns:";
cin>>c;
cout<<"Printing rectangle:"<<endl;
for (k=1; k<=r ; k++){
for (j=1; j<=c; j++)
cout<<'*';
cout<<endl;
}
cout<<"Do U want to print more shapes??? (Y / N)";
ch = getche();
}
while(ch == 'y' || ch == 'Y');
return 0;
}

BREAK STATEMENT
The break; statement terminates a loop (for, while and do..while loop) and a switch statement immediately
when it appears.

Course Instructor: Nazish Basir Page: 39/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
C++ CONTINUE STATEMENT
It is sometimes necessary to skip a certain test condition within a loop. In such case, continue; statement is
used in C++ programming.

PROGRAM 7: Demonstrating the break statement

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;
}

Course Instructor: Nazish Basir Page: 40/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 8: Demonstrating the continue statement

#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;
}

Course Instructor: Nazish Basir Page: 41/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

Course Instructor: Nazish Basir Page: 42/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 43/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

ACCESSING ARRAY ELEMENTS


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary variable. Following
is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and
accessing arrays

Course Instructor: Nazish Basir Page: 44/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

SOME IMPORTANT POINTS ABOUT ARRAYS

• We can access array randomly by using any index


• We can use a Loop to access all elements of an array in one by one
• Reduces code as we create many variables in one statement and use loop to access them
• Sorting and searching becomes easy as it can be accomplished by writing less line of code
• Allows a fixed number of elements to be entered which is decided at the time of declaration

PROGRAM 1: Demonstrating Simple Array.

#include<iostream>
using namespace std;

int main() {
int arr[5];
int k;

cout<<"An Integer Array..."<<endl;


cout<<"Enter 10 elements in array"<<endl;

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


cout<<"Enter arr[" << k << "]:";
cin>>arr[k];
}

cout<<"The elements in array are:"<<endl;

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


cout<<"arr[" << k << "]: " << arr[k] << endl;

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.

Course Instructor: Nazish Basir Page: 45/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 2: Finding largest elements in an 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;
}

Exercise 2: Write a program which finds the smallest element in an array

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;
}

Course Instructor: Nazish Basir Page: 46/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 4: Demonstrates different array types and their use.

#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];

cout<<"\nPlease enter the data for 10 students..."<<endl;


for(int i=0 ; i<size ; i++)
{
cout<<"\nPlease Enter Student No."<<i+1<<" data..."<<endl;
cout<<"Roll No.:";
cin>>roll_no[i];
cout<<"Marks out of (500):";
cin>>marks[i];
per[i] = (float)marks[i] / 500 * 100;

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';
}

cout<<"\n\nPress any key to continue....";


getch();

cout<<"\n \n \n \t \t RESULT LIST \n \n";


cout<<setw(9)<<"ROLL NO."<<setw(7)<<"MARKS"
<<setw(12)<<"PERCENTAGE"<<"\tGRADE"<<endl;

for(int i=0 ; i<size ; i++)


cout<<setw(9)<<roll_no[i]<<setw(7)<<marks[i]
<<setw(12)
<<setprecision(2) //Digit after decimal point
<<setiosflags(ios::fixed) //Do not show number in exponential form
<<setiosflags(ios::showpoint) //Alway show decimal point
<<per[i]<<"%\t"<<grade[i]<<endl;

return 0;
}

Course Instructor: Nazish Basir Page: 47/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
MULTI DIMENSIONAL ARRAY
C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
TWO-DIMENSIONAL ARRAYS
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in
essence, a list of one-dimensional arrays. To declare a two-dimensional array of size x,y, you would write
something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of columns.
A 2-dimensional array a, which contains three rows and four columns can be shown as below:

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.

INITIALIZING TWO-DIMENSIONAL ARRAYS


Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row have 4 columns:
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

ACCESSING TWO-DIMENSIONAL ARRAY ELEMENTS


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the
array. For example:
int val = a[2][3];

The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram.

Course Instructor: Nazish Basir Page: 48/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 5: Demonstrates a double dimensional array.
#include<iostream>
using namespace std;

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;

Course Instructor: Nazish Basir Page: 49/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

Input elements in the second matrix:


[0][0] : 1
[0][1] : 2
[0][2] : 3
[1][0] : 4
[1][1] : 5
[1][2] : 6
[2][0] : 7
[2][1] : 8
[2][2] : 9

The First matrix is :


9 8 7
6 5 4
3 2 1
The Second matrix is :
1 2 3
4 5 6
7 8 9
The Addition of two matrix is :
10 10 10
10 10 10
10 10 10

Course Instructor: Nazish Basir Page: 50/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 51/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT: To Understand C-Strings, C-String Variables, Reading Embedded Blanks, Reading
Multiple Lines, Arrays Of Strings, String Class In C++, Defining And Accessing String
Objects And Understanding Some String Class Member Functions.

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";

INPUT/OUTPUT WITH C-STRINGS

Input: cin>> str ; Output: cout<<str ;

To access single character: cout<<str[4];

Reading Embedded Blanks


cin.get(str, SIZE);
Here str represents string array and SIZE is maximum number of characters
Reading Multiple Lines
cin.get(str, SIZE, TERMINATING_CHARCTER);
Here str represents string array, SIZE is maximum number of characters and
TERMINATING_CHARCTER is a single character which stops the input

Course Instructor: Nazish Basir Page: 52/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 1: Demonstrate Simple C-string

#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;
}

PROGRAM 2: Demonstrate multiline input

#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;
}

PROGRAM 3: Demonstrate array of String


#include <iostream>
using namespace std;
int main()
{
const int DAYS = 7;
const int MAX = 10;
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
for(int j=0; j<DAYS; j++)
cout << star[j] << endl;
return 0;
}

Course Instructor: Nazish Basir Page: 53/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

THE STRING CLASS IN C++


The standard C++ library provides a string class type that supports all the operations mentioned
above, additionally much more functionality.

DEFINING AND ASSIGNING STRING OBJECTS


You can define a string object in several ways:
string s1(“Man”);
string s2 = “Beast”;
string s3;

You can concatenate one string object with another:


s3 = “Neither “ + s1 + “ nor “;

You can also use the += operator to append a string to the end of an existing string:
s3 += s2;

You can exchange the values of strings:


s1.swap(s2);

INPUT/OUTPUT WITH STRING OBJECTS

Input: cin>> s1 ; Output: cout<<s1 ;

To access single character: cout<<str[4];

Reading Embedded Blanks


getline(cin, str);
First argument is stream object from which the input will come in this case (cin) and second
argument str represents string object
Reading Multiple Lines
getline(cin, str, TERMINATING_CHARCTER);
First argument is stream object from which the input will come in this case (cin), second
argument str represents string object and TERMINATING_CHARCTER is a single character which
stops the input

Course Instructor: Nazish Basir Page: 54/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 4: Demonstrate defining and assigning string objects


#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(“Man”); //initialize
string s2 = “Beast”; //initialize
string s3;
s3 = s1; //assign
cout << “s3 = “ << s3 << endl;
s3 = “Neither “ + s1 + “ nor “; //concatenate
s3 += s2; //concatenate
cout << “s3 = “ << s3 << endl;
s1.swap(s2); //swap s1 and s2
cout << s1 << “ nor “ << s2 << endl;
return 0;
}

PROGRAM 5: Demonstrate string class input/output

#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;
}

Course Instructor: Nazish Basir Page: 55/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

SOME STRING FUNCTIONS


 The length() member function, which returns the number of characters in the string object.
 The find() function looks for the string used as its argument in the string for which it was
called.
 The find_first_of() function looks for any of a group of characters, and returns the position of
the first one it finds.
 The function find_first_not_of() finds the first character in its string that is not one of a
specified group.
 The erase() function removes a substring from a string. Its first argument is the position of the
first character in the substring, and the second is the length of the substring.
 The replace() function replaces part of the string with another string. The first argument is the
position where the replacement should begin, the second is the number of characters in the
original string to be replaced, and the third is the replacement string.
 The insert() function inserts the string specified by its second argument at the location
specified by its first argument.
 The append() function add characters at the end of the sentence the first argument is the
number of characters to append, and the second is the character to be appended.
 The substr() member function. It returns a substring of the string for which it was called. Its
first argument is the position of the substring, and the second is the number of characters. If
second argument is not passed, string till end is taken as substring
 The clear() function deletes all character from string

PROGRAM 6: Demonstrates finding substrings in string objects

#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;
}

Course Instructor: Nazish Basir Page: 56/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 7: Demonstrates changing parts of string objects


#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("Quick! call the Police.");
string s2("Doctor");
string s3("Don't ");
s1.erase(0, 7); //remove "Quick! "
s1.replace(9, 6, s2); //replace "Police" with "Doctor"
s1.replace(0, 1, "C"); //replace 'S' with 's'
s1.insert(0, s3); //insert "Don't " at beginning
s1.erase(s1.size()-1, 1); //remove '.'
s1.append(3, '!'); //append "!!!"
int x = s1.find(' '); //find a space
while( x < s1.size() ) //loop while spaces remain
{
s1.replace(x, 1, "/"); //replace with slash
x = s1.find(' '); //find next space
}
cout << "s1: " << s1 << endl;
return 0;
}

PROGRAM 8: Demonstrates substring of string objects

#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;
}

Course Instructor: Nazish Basir Page: 57/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PASSING ARRAYS TO FUNCTIONS


Arrays can be used as arguments to functions. In a function declaration, array arguments are
represented by the data type and size of the array. For Example:
void display(char[3][3]);

You can also write declaration without size:


void display(char[][3]);

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";
}
}

Course Instructor: Nazish Basir Page: 58/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

Enter car registration number: GF121


Sorry Enter again
Enter car registration number: B121N1
Sorry Enter again
Enter car registration number: BAN123
Registration Number Verified

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.

Enter URL: www.youtube.com


Name of Site: youtube

Course Instructor: Nazish Basir Page: 59/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 60/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT: To understand functions in C++ along with function declaration, definition and calling of
function. To understand function return type and parameters.

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

1. Declaring a function or Prototype:


A function declaration tells the compiler about a function's name, return type, and parameters. The
general structure of a function declaration is as follows:

return_type function_name( Parameter List );

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 function_name( parameter list ) {


body of the function
}

A function definition consists of a function header and a function body.

 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.

Course Instructor: Nazish Basir Page: 61/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
3. Calling a function:
To use a function, you will have to call or invoke that function. When a program calls a function, program
control is transferred to the called function. A called function performs defined task and when it’s return
statement is executed or when its function-ending closing brace is reached, it returns program control
back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:

return_type = function_name(arguments);

Course Instructor: Nazish Basir Page: 62/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 1: Demonstrates a simple function

#include <iostream>
using namespace std;

void starline(); //function declaration (prototype)


int main()
{
starline(); //call to function
cout << “Data type Range” << endl;
starline(); //call to function
cout << “char -128 to 127” << endl
<< “short -32,768 to 32,767” << endl
<< “int System dependent” << endl
<< “long -2,147,483,648 to 2,147,483,647” << endl;
starline(); //call to function
return 0;
}

// function definition
void starline() //function declarator
{
for(int j=0; j<45; j++) //function body
cout << ‘*’;
cout << endl;
}

PROGRAM 2: Demonstrates a function which takes arguments

#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;
}

Course Instructor: Nazish Basir Page: 63/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 3: Passing variable and expression to a function. Demonstrates function definition
preceding function calls eliminating declaration.
#include <iostream>
using namespace std;
void repchar(char ch, int n) {
for(int j=0; j<n; j++) //function body
cout << ch;
cout << endl;
}
int main() {
for (int a = 180; a<=190 ; a++)
repchar(a, a-179);
return 0;
}

PROGRAM 4: Demonstrate a function which return value.


#include <iostream>
using namespace std;
float lbstokg(float);
int main() {
float lbs, kgs;
cout << "\nEnter your weight in pounds: ";
cin >> lbs;
kgs = lbstokg(lbs);
cout << "Your weight in kilograms is " << kgs << endl;
return 0;
}
float lbstokg(float pounds) { // converts pounds to kilograms
float kilograms = 0.453592 * pounds;
return kilograms;
}

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;
}

Course Instructor: Nazish Basir Page: 64/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PROGRAM 6: Demonstrate that return statement can come anywhere in function.

#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;
}

PROGRAM 7: Demonstrate power function.

#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;
}

Course Instructor: Nazish Basir Page: 65/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
PASSING ARRAYS TO FUNCTIONS
Arrays can be used as arguments to functions. In a function declaration, array arguments are
represented by the data type and size of the array. For Example:
void somefunc( int elem[5] );
void display(char[3][3]);

You can also write declaration without size:


void somefunc( int elem[] );

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";
}
}

Course Instructor: Nazish Basir Page: 66/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

Enter Temperature in Fahrenheit: 100


Temperature in Celsius is: 37.7778

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

Wrong Value Renter

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.”

Enter a String: welcome all


Reversed: lla emoclew

Course Instructor: Nazish Basir Page: 67/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 68/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

OBJECT: To Understand Reference Arguments, Passing Simple Data Types By Reference,


Overloaded Functions, Different Numbers Of Arguments, Different Kinds Of Arguments,
Recursion, Variables And Storage Classes, Automatic Variables, External (Global)
Variables, Static Variables, Returning By Reference.

PASSING PARAMETERS BY REFERENCE:


The call by reference method of passing arguments to a function copies the reference of an argument into the
formal parameter. A reference to the original variable, in the calling program, is passed. Reference means
actually the memory address of the variable is passed. As function has an actual memory address as an
argument it can access the actual variables in the calling program, this provides a mechanism for passing more
than one value from the function back to the calling program.

PROGRAM 1: Demonstrates a passing variable by reference to function

#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;

order(n1, n2); //order each pair of numbers


order(n3, n4);
cout<<"After Ordering:"<<endl;
cout << "n1=" << n1 << " n2=" << n2 << endl;
cout << "n3=" << n3 << " n4=" << n4 << endl;
return 0;
}
void order(int& numb1, int& numb2){ //orders two numbers
if(numb1 > numb2) { //if 1st larger than 2nd,
int temp = numb1; //swap them
numb1 = numb2;
numb2 = temp;
}
}

Course Instructor: Nazish Basir Page: 69/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 2: Demonstrates a passing variable by reference to function

#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.

PROGRAM 3: Demonstrates function overloading with different Number of Arguments

#include <iostream>
using namespace std;
void repchar(); //declarations
void repchar(char);
void repchar(char, int);
int main()
{
repchar();
repchar(‘=’);
repchar(‘+’, 30);
return 0;
}

Course Instructor: Nazish Basir Page: 70/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

// 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.

PROGRAM 4: Calculates factorials using recursion


#include <iostream>
using namespace std;
unsigned long factfunc(unsigned long); //declaration
int main()
{
int n; //number entered by user
unsigned long fact; //factorial
cout << “Enter an integer: “;
cin >> n;
fact = factfunc(n);
cout << “Factorial of “ << n << “ is “ << fact << endl;
return 0;
}
// calls itself to calculate factorials
unsigned long factfunc(unsigned long n)
{
if(n > 1)
return n * factfunc(n-1); //self call
else
return 1;
}

Course Instructor: Nazish Basir Page: 71/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 72/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

PROGRAM 6: Demonstrates global variable

#include <iostream>
#include <conio.h>
using namespace std;

char ch = 'a'; //global variable ch

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;
}

Course Instructor: Nazish Basir Page: 73/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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

PROGRAM 7: Demonstrates static variable

#include <iostream>
using namespace std;

// finds average of old plus new data


float getavg(float newdata) {

static float total = 0; //static variables are initialized


static int count = 0; // only once per program

count++; //increment count


total += newdata; //add new data to total
return total / count; //return the new average
}

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.

Course Instructor: Nazish Basir Page: 74/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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.

PROGRAM 8: Demonstrate returning reference values

#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;
}

You cannot return a local variable from this function.


int& test()
{
int n = 2;
return n;
}

Course Instructor: Nazish Basir Page: 75/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 76/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
OBJECT: To understand structures, declaring and defining structure variables, accessing structure
members and structure initializer lists. Operations on structure variables. Structures within
Structures.

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.

DECLARING AND DEFINING STRUCTS

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.

Course Instructor: Nazish Basir Page: 77/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
It is possible to define multiple variables of the same struct type:

Employee joe; // create an Employee struct for Joe


Employee frank; // create an Employee struct for Frank

ACCESSING STRUCTURE MEMBERS

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:

Employee joe; // create an Employee struct for Joe


joe.id = 14; // assign a value to member id within struct joe
joe.age = 32; // assign a value to member age within struct joe
joe.wage = 24.15; // assign a value to member wage within struct joe

Employee frank; // create an Employee struct for Frank


frank.id=15; // assign a value to member id within struct frank
frank.age = 28; // assign a value to member age within struct frank
frank.wage = 18.2; //assign value to member wage within struct frank

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:

int totalAge = joe.age + frank.age;

if (joe.wage > frank.wage)


cout << "Joe makes more than Frank\n";
else if (joe.wage < frank.wage)
cout << "Joe makes less than Frank\n";
else
cout << "Joe and Frank make the same amount\n";

// Frank got a promotion


frank.wage += 2.50;

// Today is Joe's birthday


++joe.age; // use pre-increment to increment Joe's age by 1

Course Instructor: Nazish Basir Page: 78/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

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;
};

Employee joe = { 1, 32, 60000.0 };


// joe.id = 1, joe.age = 32, joe.wage = 60000.0
Employee frank = { 2, 28 };
// frank.id = 2, frank.age = 28, frank.wage = ??? (uninitialized)

PROGRAM 1: Demonstrate a simple structure

#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;

Employee frank = { 15, 28, 18.27 };


int totalAge = joe.age + frank.age;
if (joe.wage > frank.wage)
cout << "Joe makes more than Frank\n";
else if (joe.wage < frank.wage)
cout << "Joe makes less than Frank\n";
else
cout << "Joe and Frank make the same amount\n";

// Frank got a promotion


frank.wage += 2.50;

// Today is Joe's birthday


++joe.age; // use pre-increment to increment Joe's age by 1
return 0;

Course Instructor: Nazish Basir Page: 79/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12
}
EXERCISE 1: Modify program no 1 and add name variable in the structure and print all records of Joe and
Frank in a Table like format.

NAME ID AGE WAGE


Joe 14 32 24.15
Frank 15 28 18.27

ARRAYS OF STRUCTURES
Arrays can contain structures as well as simple data types

PROGRAM 2: Demonstrates array of structures.

#include <iostream>
using namespace std;
const int SIZE = 4; //number of parts in array

struct part //specify a structure


{
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
};

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;
}

Course Instructor: Nazish Basir Page: 80/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 3: Demonstrates structures of structures & how to create structures of structures.

#include <iostream>
using namespace std;

struct Distance{ // Creating Structure


int feets;
double inches;
};

struct Box{ // Creating Box Structure by using Distance Structure


Distance height; // Creating Distance variable for the height
Distance width; // Creating Distance variable for the width
};

int main()
{

Box box1; // Declaring one variables of Box structure

box1.height.feets = 5; // Adding values for height


box1.height.inches = 9.5; // Adding values for height
box1.width.feets = 4; // Adding values for width
box1.width.inches = 2.4; // Adding values for width

cout<< "Height: "


<<box1.height.feets<<"\'-" //Printing the height of the box
<< box1.height.inches<<"\"" // Printing the height of the box
<< endl << "Width: "
<< box1.width.feets<<"\'-" // Printing the width of the box
<< box1.width.inches<<"\""; // Printing the width of the box
}

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.

Course Instructor: Nazish Basir Page: 81/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

PROGRAM 6: Demonstrate passing a structure to function and returning a function from structure.

#include <iostream>
using namespace std;

struct Distance { //English distance


int feet;
float inches;
};

Distance addengl(Distance, Distance); //declarations


void engldisp(Distance);

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;
}

// adds two structures of type Distance, returns sum


Distance addengl( Distance dd1, Distance dd2 )
{
Distance dd3; //define a new structure for sum
dd3.inches = dd1.inches + dd2.inches; //add the inches
dd3.feet = 0; //(for possible carry)
if(dd3.inches >= 12.0) //if inches >= 12.0,
{ //then decrease inches
dd3.inches -= 12.0; //by 12.0 and
dd3.feet++; //increase feet
} //by 1
dd3.feet += dd1.feet + dd2.feet; //add the feet
return dd3; //return structure
}

// display structure of type Distance in feet and inches


void engldisp( Distance dd )
{
cout << dd.feet << “\’-” << dd.inches << “\””;
}

Course Instructor: Nazish Basir Page: 82/83


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES / LAB HANDOUTS
PROGRAMMING FUNDAMENTALS (320-321) WEEK. 1 - 12

Course Instructor: Nazish Basir Page: 83/83


Institute of Information and Communication Technology, University of Sindh.

You might also like