Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

C/C++ Programming 1

Computer Languages:- It is defined as the way of communication between a person and a


computer, and between two computers. A person can communicate with a digital computer in
computer languages, e.g., C/C++, FORTRAN, PASCAL, BASIC, etc, just as human
communicate in natural languages, e.g., ENGLISH, PASHTO, URDU, etc. There are hundreds
of computer languages used for communication with a computer and these languages are also
called Artificial Languages. Computer languages are of the following types.
1. Low-Level Languages:- The lowest and most elementary language of a computer is the
Machine language also called Binary Language or Language of 0 and 1. This is also
called the language of computer, because computer directly understands it. But it is very
much difficult for users and are machine depended i.e it varies from machine to machine.
All the program codes are in pure binary form, which are very much difficult for the
humans to memorize or understand. A little bit highest level of this language becomes the
Assembly language also called symbolic programming language, which carry English
like instructions and is human-readable but still it needs the knowledge of computer
internal hardware/working structure.

2. High level Languages:- The languages, which are one step higher than Low-level
languages in human understanding, are called High-Level Languages. These languages
have their own set of characters, words and symbols in which a programmer can write his
own programs according to certain rules similar to the Natural Languages. The high-
Level Languages are also called Compiler or Procedural Languages. Programs written in
these languages are easier and understandable to humans than the Low-level Languages.
These languages are machine independed because these languages are more User-
oriented than the machine internal structure, i.e. Programs written in these languages
using one computer can easily be run on another computer, e.g., BASIC, FORTRAN,
COBOL, etc.
Computer Languages and Packages:- In computer languages we define the problems and
give our own instructions to the computer, e.g. BASIC, FORTRAN, PASCAL,C/C++ etc. But
in computer packages we can solve our problems without giving our instructions to the
computer. They need only a few keystrokes and ready-made commands to help in solving our
specific problems. Computer languages are versatile to solve the problems where as the
computer packages are not versatile and are specific to problem solutions.

What is C ? C is a general purposes high-level programming language developed by Dennis


Ritchie at Bell Labs in the mid 1970s. Although originally designed as a systems programming
language, C has proved to be a powerful and flexible language that can be used for a variety of
applications, from business programs to engineering. C is a particularly popular language for
personal computer programmers because it is relatively small -- it requires less memory than
other languages.
The first major program written in C was the UNIX operating system, and for many years C
was considered to be inextricably linked with UNIX. Now, however, C is an important
language independent of UNIX.
Although it is a high-level language, C is much closer to assembly language than are most other
high-level languages. This closeness to the underlying machine language allows C programmers
to write very efficient code. The low-level nature of C, however, can make the language
difficult to use for some types of applications.

What is C++?
C++ is an object oriented programming language created by Bjarne Stroustrup in 1985. It
implements “data abstraction” using a concept called “Classes”, along with other features to
allow Object Oriented Programming. Parts of the C++ program are easily reusable and
extensible, existing code is easily modifiable without actually having to change to code. C++
adds a concept called “operator overloading” not seen in the earlier OOP languages and it
makes the creation of libraries much cleaner.
C++ maintains the aspect of the C programming language, yet has features which simplify
memory management. Additionally, some of the features of C++ allow low level access to
memory but also contain high level features.
2

C++ is a superset of C. C programs will run in C++ compilers. C uses structural programming
concepts and techniques while C++ uses object oriented programming and classes which focus
on data.
History of C: By 1960 a hoarde of computer languages had come into existence, almost each
for a specific purpose. For example, COBOL was being used for Commercial Applications,
FORTRAN for Engineering and Scientific Applications and so on. At this stage people started
thinking that instead of learning and using so many languages, each for a different purpose, why
not use only one language, which can program all possible applications. Therefore, an
international committee was set up to develop such a language. This committee came out with a
language called ALGOL 60. However, ALGOL 60 never really became popular because it
seemed too abstract, too general. To reduce this abstractness and generality, a new language
called Combined Programming Language (CPL) was developed at Cambridge University. CPL
turned out to be so big, having so many features, that it was hard to learn and difficult to
implement.
Basic Combined Programming Language (BCPL), developed by Martin Richards at Cambridge
University aimed to solve this problem by bringing CPL down to its basic good features. But
unfortunately it turned out to be too less powerful and too specific. Around same time a
language called B was written by Ken Thompson at AT&T Bell Labs, as a further
simplification of CPL. But like BCPL, B too turned out to be very specific. Ritchie inherited the
features of B and BCPL, added some of his own and developed C. Ritchie’s main achievement
is the restoration of the lost generality in BCPL and B, and still keeping it powerful.
Advantages of C

• Programs written in C are very efficient and fast. This is due to its variety of data types and
powerful operators. It is many time faster than BASIC. This helps developers in saving their
valuable time.

• C is a powerful and flexible language, which helps system developers to deliver various
complex tasks with ease. C is used for diverse projects as operating systems, word processors,
graphics, spreadsheets, and even compilers for other languages.

• C is popular among professional programmers for programming, as a result, a wide variety of


C compilers and helpful accessories are available.

• C is highly portable language. This means that a C program written for one computer system
can be run on another system with little or no modification.

• C’s another striking feature is its ability to extend itself. A C program is basically a collection
of various function supported by C library (also known as header files). We can also add our
own functions to the C library. These functions can be reused in other applications or programs
by passing pieces of information to the functions, you can create useful, reusable code.

• Writing C program with user-defined functions makes program more simple and easy to
understand. Breaking a problem in terms of functions makes program debugging, maintenance
and testing easier.
Disadvantages of C
 C does not have OOPS feature that's why C++ is developed.
 There is no runtime checking in C language.
 There is no strict type checking (for ex: we can pass an integer value for the
floating data type).
 C doesn't have the concept of namespace.
 C doesn't have the concept of constructors and destructors.
Difference between C and C++
C++ is an extension of C language. This means that you can not only use the new features
introduced with C++ but can also use the power and efficiency of C language. C++ is a direct
descendant of C that retains almost all of the C features as a subset. Here is a list of differences
between C and C++.
3

1. The main difference between C and C++ is that C++ is object oriented while C is a
function or procedure oriented language.
2. C++ provides stronger types of checking that C and directly support a wider range of
programming styles than C.
3. C does not have any classes or object. It is procedure and function driven.
4. C structures have a different behaviour compared to C++ structure.
5. The standard input & output functions differ in the two languages
C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output
functions
6. C input/output is based on library and the processes are carried out by including it
functions. C++ input/output is made through console commands cin and cout.
7. C functions do not support overloading.
8. C does not support new or delete commands. The memory operations to free or allocate
memory in C are carried out by malloc() and free().
9. Undeclared functions in C++ are not allowed. The function has to have a prototype define
before the main() before use in C++ although in C the functions can be declared at the
point of use.
10. After declaring structures and enumerators in C we cannot declare the variable for the
structure right after the end of the structure as in C++.
11. C has top down approach whereas C++ has a bottom up approach.
12. In C a character constant is automatically elevated to an integer whereas in C++ this is
not the case.
13. In C declaring the global variable several times is allowed but this is not allowed in C++.
Structure of C/C++ program
A C/C++ program consists of three main parts. These are
1. Pre-processor Directives
2. The main( ) Function
3. C/C++ statements (Body of the program)
Preprocessor Directives
The instructions that are given to the computer before the beginning of the actual program are
called Preprocessor Directives. These are also known as Compiler Directives. The preprocessor
directives consist of instructions for the compiler. The compiler adds special instructions of
code from these directives into the program at the time of compilation.
These pre-processor directives normally start with a number sing,( # ) and the keyword
“include”. Pre-processor directives are used to include header files in the program.
Example.
# include <iostream.h>
main( )
{
Statements;
Statements;
}
The main( ) Function
The only component that is required in every C/C++ program is the main( ) function. In its
simplest form, the main( ) function consists of the name main followed by a pair of empty
parentheses (( )) and a pair of braces ({ }). Within the braces are statements that make up the
main body of the program. Under normal circumstances, program execution starts at the first
statement in main( ) and terminates at the last statement in main( ).

Body of the program (C/C++ statements) : The statements of the program are written under
the main( ) function between the curly braces { }. These statements are the body of the
program. Each statement in C/C++ ends with a semicolon. ( ; )
The #include Directive
The #include directive instructs the C/C++ compiler to add the contents of an include file into
your program during compilation. An include file is a separate disk file that contains
4

information needed by your program or the compiler. Several of these files (sometimes called
header files) are supplied with your compiler. You never need to modify the information in
these files; that's why they're kept separate from your source code. Include files should all have
an .H extension (for example, conio.h).
C/C++ character set.
A character denotes any alphabet, digit or symbols to represent information. The following are
the valid alphabets (letters), numbers (digits) and special symbols permitted in C / C++

1. Alphabets (Letters) :
C/C++ language comprises the following set of letters to form a standard program. They are :
A to Z in Capital letters.
a to z in Small letters.

2. Numbers/Digits :
C/C++ language comprises the following sequence of numbers to associate the letters. 0 to 9
digits.

3. Arithmetic Operations:
+, -, *, /, %(Mod)
4. Special Characters:
C language contains the following special character in association with the letters and digits.
@,#,%,^,&,*, etc
Keywords / Reserve words
Keywords (Reserved words) are the words that are reserved for specific purpose and can not be
used for other purpose. They have special meaning for the compiler and the computer knows
their meaning. In C/C++ all the keywords are in lowercase. Since the C/C++ language is case
sensitive. Therefore the keywords must be entered in lowercase. Keywords cannot be used as
variable name in program. Some example of the keywords are:
break, default, for, case, do , return, if, int, float, long, double, else etc

User defined words (Identifiers)


The programmers supplied words are known as the identifiers, because they are supplied by the
programmer. They are not reserved by the computer for special meaning. Such words are also
known as identifiers. Data names are the most common type of the user defined words.
The rule for the formation of an identifier are:
 An identifier can consist of alphabets, digits and/or underscores.
 It must not start with a digit
 C/C++ is case sensitive that is upper case and lower case letters are considered different
from each other.
 It should not be a reserved word.
Variables:
A quantity whose value may change during execution of the program is called variable. It is
represented by a symbol or a name.
A variable represents a storage or memory location in the computer memory. Data is stored into
the memory location. The name of the memory location i.e. the variable name, remain fixed
during execution of the program but the data stored in that location may change from time to
time.

Rules for writing variable name. (Rule for naming variables)


The following are the rules for writing a variable name is a program in C/C++
 The first character of variable name must be an alphabetic.

 Underscore can be used as first character of variable name.

 Blank spaces are not allowed in a variable name.

 Special characters such as arithmetic operators, $,#,@,% etc cannot be used in a variable

name.
 Reserved words (keywords) cannot be used as variable name.
5

 The maximum length of a variable name depends upon the compiler of C/C++.
 A variable name declared for one data type can not be used to declared for another data
type.

Local variable and Global variable


Local variable
Variables that are declared within the body of the function are known as local variables. These
are the variables that the function needs for itself. They are activated only when the function is
called. They may not be read or written to from outside the function in which they are declared.
When the function returns, such variables no longer available.
Consider the following example:
#include <iostream.h>

void main( )
{
clrscr( );
int a,b,c;
}
In the program the variables a,b and c are local variables because they are available only in
main function. They can not be used in other function.
Global Variables
The variables that are declared outside of any function are known as the global variables. Such
variables can be seen, accessed and changed from any function down in the program. These
variables are declared at the top of the program, before a function or between two functions in
the program. Unlike the local variable the value of the global variable can be changed in any
functions. Consider the following programming example in which a , b and c are the global
variables and d is local variable.
#include <iostream.h>
#include <conio.h>
int a,b,c;
void main( )
{
int d;

Declaration of variables: Assigning the name and data type that a variable can hold is called
declaration of the variable. All variables that are used in a program are declared using variable
declaration statement. The syntax to declare a variable in C/C++ is
Type list of variables;
Where
type : Specifies data type of variables. For example, it may be int, float , char etc.
list of variables : Specifies a list of variables separated by commas, in a single statement more
than one variable, separated by commas, of same data type can be declared.
For example, to declare variables “abc” , “xyz” , and “s” of integer type, the statement is written as .
int abc, xyz , s;
To declare variable with different data types the statement can be written as.
int abc;
float xyz;
char name[15];
Initialization of variables:
When a variable is declared, a memory location is assigned to it. A know value can be assigned
to the variable at the time of its declaration. If we assign a value to a variable at the time of its
declaration, it is called initialization of variable. For example to declare variables a,b and c of
integer type and assigning values a = 110 and b = 60, the statement is written as:
int a = 110, b = 60, c;
6

Constants :
A quantity that cannot change its value during execution of the program is called constant. It is
represented by a symbol or a name. Constants have fixed value. There are four types of
constants in C/C++. These are.
1. Integer constants 2. Floating point constants
3. Character constants 4. String constants

Integer Constants:
A numerical value without a decimal part is called integer constant. The plus (+) and minus ( - )
signs can also be used with an integer constant. Integer constants are used in expression for
calculations. To print an integer constant, it is given in the output statement without quotation
marks. For example, to print integer constants 510 and 662 the output statement is written as:
cout<< 520;
cout<< 662;
Floating point constants: Numeric values that have an integer as well as a decimal part are
called floating point values. These values can also be written in exponential notation. In
exponential notation, a floating point constant is written as 123.5E2. The symbol E represents
the exponent. A floating point constant may be a positive or a negative value. The exponent
may also be a +ve or a –ve value.
Character constants: A single character enclosed in single quotation marks is called character
constant. For example ‘a’ , ‘/’ , ‘b’ etc represents character constants.
String constants : A sequence of characters consisting of alphabets, digits and/or special
characters enclosed in double quotation marks is called string constant. For example, “Pakistan”
and “Lahore” are examples of string constants.
Data types in C/C++
The variable type specifies the type of data that can be stored in it. Each variable is declared by
its type.
C/C++ has the five basic data types.
1. Bool Boolean
2. int Integer
3. float Floating Point
4. double Double Precision
5. char Character
The Bool data type:
The word bool stands for Boolean. It is used to declare logic type variables. In logic type
variables only two values can be stored. The true is equivalent to 1 and false is equivalent to 0.
The int Data type
The int represent the integer data. It is used to declared integer type variable. An integer is a
whole number, i.e a number without a fraction or a decimal point. For example, 601, 250 , -6
and 501 etc are integers. The range of values that can be stored in int data type variables
depends upon the computer system being used. In MS DOS, an integer type variable takes two
bytes in the memory and the range of values stored is form –32768 to 32767.
The storage capacity for integer type variable can be changed by applying the integer qualifiers.
There are three qualifiers that can be applied to int type variables. These are
1. short int 2. long int 3. unsigned int

The short int: The storage capacity of a short int type variable is two bytes. It can store integer
values form –32768 to 32767.
The long int: The storage capacity of a long int type variable is four bytes. It can store integer
from –2147483648 to 2147483647

The unsigned int: The unsigned int can store only positive whole-numbers. Its storage capacity
is tow bytes. It can store integer values form 0 to 65535.

The float data type: The float represent real or floating type data. The real type data is
represented in decimal or exponential notation. Float data may be signed or unsigned. For
7

example, 23.23 , 16.21 , 0.56 , -9.87 are examples of floating type data. The storage capacity of
float type variable is four bytes and it can store real values form 3.4x10-38 to 3.4x10+38.
The long float data type: The storage capacity of a long float type variable is twice the storage
capacity of float type variable. Its storage capacity is 8 bytes.
The double data type: The double is the real or floating type data. Its storage capacity is twice
the capacity of float data type. It is used to store large real values. The storage capacity for a
double variable type is 8 bytes and it can store real values from 1.7x10-308 to 1.7x10+308
The long double data type: The long double type variables are used to store very large real data
values. The storage capacity for long double variables is ten bytes. A long double variable can
store real values from 3.4x10-4932 to 3.4x10+4932
The char data type: The char stands for character. It is used to declare character type variable.
In character type variables, alphabetic characters, numeric digits and special characters can be
stored. The storage capacity for a single character is 8 bits or one byte. A char type variable can
hold from 1 byte to 65535 bytes.
Operators
An operator is a symbol that instructs C/C++ to perform some operation, or action, on one or
more operands. An operand is something that an operator acts on. In C/C++, all operands are
expressions. C/C++ operators fall into several categories:
Operators are special symbols used for specific purposes. C/C++ provides six types of
operators. Arithmetical operators, Relational operators, Logical operators, Unary operators,
Assignment operators, Conditional operators, Comma operator .
Arithmetical operators (Binary Operators)
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation.
You can use the operators +, -, *, and / with both integral and floating-point data types.
Modulus or remainder % operator is used only with the integral data type.
Operators that have two operands are called binary operators.
Example
Operator Symbol Action Example
Addition + Adds two operands x+y
Subtraction - Subtracts the second operand from the first operand x-y
Multiplication * Multiplies two operands x*y
Division / Divides the first operand by the second operand x/y
Gives the remainder when the first operand is divided
Modulus % x%y
by the second operand
All arithmetic operators, except the remainder operator, are used for all type of numeric data.
The remainder or the modulus operator (%) can only be used for integer type data. It returns the
remainder when one integer is divided by another integer. For example, 10%3 returns the
remainder 1.
Note: These operators are also called binary operators.
Relational operators
The relational operators are used to test the relation between two values. All relational operators
are binary operators and therefore require two operands. A relational expression returns zero
when the relation is false and a non-zero when it is true. The following table shows the
relational operators.
Relational Operators Meaning
< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to
Examples
Operator SymbolQuestion Asked Example
Equal == Is operand 1 equal to operand 2? x == y
8

Greater than > Is operand 1 greater than operand 2? x>y


Less than < Is operand 1 less than operand 2? x<y
Greater than or equal to >= Is operand 1 greater than or equal to operand 2? x >= y
Less than or equal to <= Is operand 1 less than or equal to operand 2? x <= y
Not equal != Is operand 1 not equal to operand 2? x != y

Logical Operators
Sometimes you might need to ask more than one relational question at once. For example, "If
it's 7:00 a.m. and a weekday and not my vacation, ring the alarm." C/C++ logical operators let
you combine two or more relational expressions into a single expression that evaluates to either
true or false.
C/C++ logical operators.
Operator Symbol Example
AND && exp1 && exp2
OR || exp1 || exp2
NOT ! !exp1
The Assignment Operator
The assignment operator is the equal sign (=). Its use in programming is somewhat different
from its use in regular math. If you write x = y;
in a C/C++ program, it doesn't mean "x is equal to y." Instead, it means "assign the value of y to
x." In a C assignment statement, the right side can be any expression, and the left side must be a
variable name. Thus, the form is as follows:
variable = expression;
When executed, expression is evaluated, and the resulting value is assigned to variable.

x = y = z = 32;

This code stores the value 32 in each of the three variables x, y, and z.

Compound Assignment Operators


C/C++ compound assignment operators provide a shorthand method for combining a binary
mathematical operation with an assignment operation. For example, say you want to increase
the value of x by 5, or, in other words, add 5 to x and assign the result to x. You could write
x = x + 5;
Using a compound assignment operator, which you can think of as a shorthand method of
assignment, you would write x += 5;
In more general notation, the compound assignment operators have the following syntax :
exp1 operator= exp2
This is equivalent to writing
exp1 = exp1 operator exp2;
You can create compound assignment operators using the five binary mathematical operators.
C/C++ compound assignment operators.
When you write this... It is equivalent to this
x *= y x=x*y
Y -= z + 1 y=y-z+1
a /= b a=a/b
X += y / 8 x=x+y/8
y %= 3 y=y%3
The compound operators provide a convenient shorthand, the advantages of which are
particularly evident when the variable on the left side of the assignment operator has a long
name. As with all other assignment statements, a compound assignment statement is an
expression and evaluates to the value assigned to the left side. Thus, executing the following
statements results in both x and z having the value 14:
x = 12;
z = x += 2;
9

Increment and Decrement Operators


C++ provides two special operators viz '++' and '--' for incrementing and decrementing the
value of a variable by 1. The increment/decrement operator can be used with any type of
variable but it cannot be used with any constant. Increment and decrement operators each have
two forms, pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x,y;
int i=10,j=10;
x = ++i; //add one to i, store the result back in x
y= j++; //store the value of j to y then add one to j
cout<<x; //11
cout<<y; //10
Operator Symbol Action Examples
Increment ++ Increments the operand by one ++x, x++
Decrement -- Decrements the operand by one --x, x--
The Conditional Operator (Ternary operator)
The conditional operator is C/C++ only ternary operator, meaning that it takes three operands.
Its syntax is
exp1 ? exp2 : exp3;
If exp1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2.
If exp1 evaluates to false (that is, zero), the entire expression evaluates as the value of exp3. For
example, the following statement assigns the larger of x and y,
z = (x > y) ? x : y;

The conditional operator can't be used in all situations in place of an if...else construction, but
the conditional operator is more concise. The conditional operator can also be used in places
you can't use an if statement.

The comma operator


The comma operator gives left to right evaluation of expressions. When the set of expressions
has to be evaluated for a value, only the rightmost expression is considered.
int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i
Would first assign the value of a to i, and then assign value of b to variable i. So, at the end,
variable i would contain the value 2.
The sizeof operator
As we know that different types of Variables, constant, etc. require different amounts of
memory to store them The sizeof operator can be used to find how many bytes are required for
an object to store in memory. For example
sizeof (char) returns 1
sizeof (int) returns 2
sizeof (float) returns 4
If k is integer variable, the sizeof (k) returns 2.
the sizeof operator determines the amount of memory required for an object at compile time
rather than at run time.
The order of Precedence
The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is called
the order of precedence. The following table shows the order of precedence.
10

Order Operators
First ()
Second *, /, %
Third +, -
Statements
Statements are the instructions given to the computer to perform any kind of action. Action may
be in the form of data movement, decision making etc. Statements form the smallest executable
unit within a C++ program. Statements are always terminated by semicolon.
Compound Statement
A compound statement is a grouping of statements in which each individual statement ends
with a semi-colon. The group of statements is called block. Compound statements are enclosed
between the pair of braces ({}.). The opening brace ({) signifies the beginning and closing brace
(}) signifies the end of the block.
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This is
quite useful when the syntax of the language needs to specify a statement but the logic of the
program does not need any statement. This statement is generally used in for and while looping
statements.
Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++
provides the following statements for implementing the selection control structure.
if statement
if else statement
nested if statement
switch statement
The if Statement
The fundamental decision making statement in C/C++ is the “if statement”. This statement is
also called as conditional jump statement or conditional transfer of control statement, because it
is mostly used to transfer the control to another statement if and only if a condition is true. If the
condition is not fulfilled i.e if the condition is false, transfer of control does not occur and the
program execution moves on the next statement following the if structure. If condition has the
following form:
if(condition)
statement;
or
if(condition)
{
statement;
statement;
statement;
}
The reserved word “if” is followed by a condition which is followed by a statement to be
carried out if the condition is true. A statement may be a single statement or a block of
statements or nothing. When more than one statements are going to be executed after the if
statement, then the statements must be grouped by enclosing them within a pair of braces.
Every statement in the if block must end with a semicolon. Consider the following example.
if(marks<33)
cout<<”Fail”;
In the above example the condition (marks<33) is tested. In case the marks is less than 33 , then
the condition is true, the statement in the if block will be executed and the message “ Fail “ will
be printed. The flowchart of the if statement is as below.

False True
is
condition?
11

If-else statement
The second form of the if statement is if-else statement. With the if-else statement, we test a
condition and we perform one of two alternatives. When one conditions is true then action first
is performed and a different action is performed when the condition is false. The general syntax
of the if-else statement is as below.
if(condition)
statement;
else
statement;
OR
if(condition)
{
statement;
statement;
statement;
}
else
{
statement;
statement;
statement;
}
If the condition is true then the statements following the condition are executed. If the condition
is false, the else clause is executed. The flowchart of the if-else statement could be as.

False True
is
condition
?

Action 2
Action 1

Next statement
in the program
Consider the following example.
if (marks>=33)
cout<<”Pass”;
else
cout<<”Fail”;
In the above example “Pass” will be printed if marks is greater than or equal to 33 else “Fail”
will be printed.
Nested if statement
The if structure can be nested within one other i.e when an if statement is contained with in
another, they are known to be nested. The nested if statement is used for multiple way decision
making. In case of nested statement one need to know which else goes with which if. The rule is
each else is paired with the previous if that does not have else. The general form could be as:
If(condition)
{
if(condition)
{
statement;
12

}
else
{
statement;
}
}
esle
{
statement;
}
Consider the following example.
if(marks>=33)
if(marks>=45)
if(marks>=60)
cout<<”First Division”;
else
cout<<”Second Division”;
else
cout<<”Third Division”;
else
cout<<”Fail”;
In the above example if marks obtained is greater than 60, then “First division” will be printed,
if marks obtain is less than 60 but greater than 45 then “Second Division” will be printed, if
marks obtained is less 45 but greater than 33 then “Third Division” will be printed and if marks
obtained is less than 33 then “Fail” will be printed.
The nested if-else structure
When an “if-else” structure is placed in another “if-else” structure, it is called “nested if-else”
structure. Is is ued for multiple selection. Its general syntax is:
if(condtion-1)
statement-1;
else if(condtion-2)
statement-2;
else if(condition-3)
statemetn-3
The Switch-Case statement (Decisions using switch statements)
The switch-case statement is a special form of multiple alternative decision making i.e when
multiple chice possibilities are based on a single value; the switch statement is best choice.
Actually switch statement is more efficient way of representing nested-if statement. This
statement is used to transfer the control to a selected case of any one of the several stated cases;
depending on the value of the switch expression. It has the following general form.
Switch(expression)
{
case valueone: statement(s);
break;
case valuetwo: statement(s);
break;
---------------------------------
case valuen: statement(s);
break;
default: statement(s);
}
1. Any legal C/C++ expression may be used in switch expression but it must be enclosed
in the parenthesis.
2. After evaluation of the expression, control is transferred directly to the statement
whose case value matches the result.
13

3. If no match is found then control is transferred to the default statement. The default
statement is optional.
4. The break statement is used to break switch statement i.e it is used to transfer the
control out of the entire switch statement to the first statement following the switch
statement.
5. Any integer or a character constant follows the reserved word case.
6. If more than one statement are required to be executed in case body, no need to
enclose them with in the braces.

Consider the following program.


#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr( );
int op = 2;
switch(op)
{
case 1: cout<<” I am in case 1”;
case 2: cout<<” I am in case 2”;
case 3: cout<<” I am in case 3”;
case 4: cout<<” I am in case 4”;
default: cout<<” I am in default”;
}
getch( );
{
The output for the following program would be as:
I am in the case 2.
Looping : ( Define loop)
A loop is an essential part of programming technique that permits the repetitive execution of a
statement or a group of statements, whereas the counter is a technique for controlling a looping
process. C/C++ has three looping statements, the “for statement” the “while statement” and the
“do-while statement”.
The for Statement (loop)
The “for statement (loop)” is used to execute a set of statements repeatedly for a fixed number
of times. It is also know as counter loop. The structure of this loop is different both the “while”
and the “do while” loops. It has the following parts.
1. Initialization
2. Condition
3. Increment or decrement
4. Body of the loop
The general syntax of the for loop is as follows.
For(initialization; condition; increment/decrement)
1. In initialization part, the value in the variable is assign when control enters into the loop
first time.
2. The condition part, the test condition is given. The body of the loop executes as long as
this condition remains true.
3. In increment or decrement part, the value in the variable is incremented or decremented.
4. The statements under the “for” loop are the body of the loop. If more than one statement
are to be executed ,these are enclosed in braces.
Consider the following example
#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr( );
for(int num = 1; num<=10; num++)
14

{
cout<<num;
}
getch( );
}
The output is:
1 2 3 4 5 6 7 8 9 10
In the above program the initial value of the num variable is 1. So the first iteration 1 is printed.
Then at the end of the loop the value of num is incremented by 1 which is 2. The value is
compared with 10 which is less than ten. So again the body of the loop is executed and 2 is
printed. Then again at the end of the loop the value of num is incremented by 1. The condition
is checked and the next number is printed. This process goes on until the value of number
becomes greater than 10.
Nested for loop
When a for loop is placed within the other loop, it is then called nested loop. In other words, we
can say that loops that occur within other loops are called nested loops. In the nested loop it is
important that the control variable of the nested loops need to be different. Consider the
following example.
#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr( );
for(outer=1; outer<=5; outer++)
{
for(inner = 1; inner <= outer ; inner++)
{
cout<<”Pakistan ”;
}
cout<<endl;
}
getch( );
}
The output of the above program will be as;
Pakistan
Pakistan Pakistan
Pakistan Pakistan Pakistan
Pakistan Pakistan Pakistan Pakistan
Pakistan Pakistan Pakistan Pakistan Pakistan
The while Statement (while loop)
The while statement, also called the while loop, executes a block of statements as long as a
specified condition is true. The while statement has the following form:
while(condition)
{
statement-1;
statement-2;
statement-3;
-------------
-------------
}
As long as the conditional expression in the while statement is true, the statement or group of
statements in the body of the loop will be repeated and this process continues until the condition
becomes false and the control skips down to the statement after the while loop.
Example.
15

#include <iostream.h>
#include <conio.h>

void main( )
{
clrscr( );
int num = 1;
while <num<=5)
{
cout<<num;
cout<<endl;
num++;
}
getch( );
}
output of the above program will be as under.
1
2
3
4
5
The do-while statement (the do-while loop)
C/C++ third loop construct is the do...while loop, which executes a block of statements as long
as a specified condition is true. The do...while loop tests the condition at the end of the loop
rather than at the beginning, as is done by the for loop and the while loop. The do while loop is
the same while loop but with a minor difference. The difference is the place where the condition
is tested. The while loop tests the condition before the executing any of the statement inside the
loop, the do while loop tests the condition after having executed the statement within the loop.
Thus in this loop either the condition is true or false, the body of the loop executes at least once.
The structure of the do...while loop is as follows:
do
{
statement-1;
statement-2;
statement-3;
statement-4;
}while (condition);
condition is any C/C++ expression, and statement is a single or compound C/C++ statement.
When program execution reaches a do...while statement, the following events occur:
1. The statements in statement are executed.
2. The condition is evaluated. It it is true, execution returns to step 1. If it is false, the
loop terminates.
Example
#include <iostream.h>
#include <conio.h>
void main( )
{
clrscr();
int num = 1;
do
{
cout<<num;
cout<<endl;
num++;
}while(num<=5);
getch();
16

}
Output of the above program will be as:
1
2
3
4
5
The break statement
The break statement, when executed in a switch structure, provides an immediate exit from the
switch structure. Similarly, you can use the break statement in any of the loop. When the break
statement executes in a loop, it immediately exits from the loop.
The continue statement
The continue statement is used in loops and causes a program to skip the rest of the body of the
loop.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips rest of the loop body and starts a new iteration.
The exit ( ) function
The execution of a program can be stopped at any point with exit ( ) and a status code can be
informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of the
code varies depending upon the operating system.
printf( ):
The printf( ) statement is a library function which is used to print on creen the value contained
in a variable. The printf( ) statement can display a simple text message or a message and the
value of one or more program variables.
The general form of printf statement is
Printf(“<format string>”, <list of variables>);
<format string> could be.
%f for printing real values
%d for printing integer values
%c for printing character values
scanf( ): The scanf( ) statement is another library function. It reads data from the keyboard and
assigns that data to one or more program variables.
The cout output stream
By default, the standard output of a program is the screen, and the C++ stream object defined to
access it is cout.
cout is used in conjunction with the insertion operator, which is written as << (two "less than"
signs).
1 cout << "Output sentence"; // prints Output sentence on screen
2 cout << x; // prints the content of x on screen
3 cout << 120; // prints number 120 on screen
The << operator inserts the data that follows it into the stream preceding it. In the examples
above it inserted the constant string Output sentence, the numerical constant 120 and variable x
into the standard output stream cout. Notice that the sentence in the first instruction is enclosed
between double quotes (") because it is a constant string of characters. Whenever we want to
use constant strings of characters we must enclose them between double quotes (") so that they
17

can be clearly distinguished from variable names. For example, these two sentences have very
different results:
1 cout << "Hello"; // prints Hello
2 cout << Hello; // prints the content of Hello variable
The clrser ( ) function
This is used for clearing the output screen i.e console.
Suppose you run a program, alter it and run it again you may find that the previous output is
still stucked there itself, at this time clrscr(); would clean the previous screen.
One more thing to remember always use clrscr(); after the declaration like
int a,b,c;
float total;
clrscr();
Functions
A function is a self-contained block of statements that performs a coherent task of some kind.
Every C/C++ program can be thought as a collection of these functions. Writing functions
avoids rewriting the same code over and over. Using functions it becomes easier to write
program and keep track of what they are doing. If the operation of a program can be divided
into separate activities, and each activity placed in different function, the each could be written
and checked more or less independently and easily. Separating the code into modular functions
also makes the program to design and understand.
The most common syntax to define a function is:
type name ( parameter1, parameter2, ...) { statements }
Where:
type is the type of the value returned by the function.
 name is the identifier by which the function can be called.
 parameters (as many as needed):
Each parameter consists of a type followed by an identifier, with each parameter being
separated from the next by a comma. Each parameter looks very much like a regular
variable declaration (for example: int x), and in fact acts within the function as a regular
variable, which is local to the function. The purpose of parameters is to allow passing
arguments to the function from the location where it is called from.
 statements is the function's body. It is a block of statements surrounded by braces { } that
specify what the function actually does.
Types of functions
There are basically two types of functions.
1. Library functions / Built-in Functions. 2. User defined functions.
1. Library functions / Built-in Functions
As the name suggests, library/built-in functions are nothing but commonly required functions
grouped together $ stored in what is called library. These functions are also called built-in or
intrinsic functions. These functions are present on the disk & are written for us by expert
programmers who write compilers for us. Almost always a compiler comes with a library of
standard functions the procedure of calling both types of functions is exactly same.
Example;
clrscr( ), get( ), getch( ), sqrt( ), main( ), scanf( ) etc
2. User defined functions.
User defined functions are those functions which are written by the programmers for a special
purpose or task & can be called in main program. The user defined functions are written for
formulas for which built-in functions are not available in the library of C/C++.
Structure of User defined functions
The structure of user defined functions consists of three steps.
 Function declaration
 Calling of the function
18

 Functions definition
Accessing Built-in Functions:
The built-in functions are accessed through header files. Each built-in function is defined in its
related header file. If a built-in function is to be used in a program, its header files must be
included in the program.
For example: “clrscr” function is defined in “conio.h” header file. If this function is to be used
in a program, the “conio.h” header file must be included in the program.
Arguments of Functions
To perform an operation, a function may require data. It performs operations on the data and
produces result. The data that is passed to a function is called arguments of the function.
The arguments of a function may be of different types. These may be int, float, string, double,
etc. Some functions may need more than one parameters, separated by comma. Some functions
need no parameter.
The “conio.h” function
The “conio.h” stands for console input output. This header file contains basic input and output
functions that are used to get data from the keyboard and to send results from the memory to the
output screen.
The “clrscr( )” function
The “clrscr” stands for clear screen. This function is used to clear the screen of the computer.
When this functions is executed, the screen is cleared and the cursor shifts to upper left
corner, i.e to row 1 and column 1 of the screen.
Its syntax is : slrscr( );
The “getch( )” function
The “getch” stands for get character. This function is used to get a single character form the
keyboard during program execution. When a key is pressed.
 The entered character is not displayed on the screen.
 Pressing of the Enter key is not required to complete the input. The control shifts to the
next statement as soon as any key is pressed.
This function is normally used to pause the execution of program.
Its syntax is : getch( );
The “getche( )” function
This function is similar to “getch” function. It is also used to get a single character from
keyboard during the program execution. The main difference between “getch” and “getche” is
that the entered character is displayed on the screen when “getche” function is used.
Its syntax is : getche( );
The “getchar( )” function
This function is similar to “getch” and “getche” functions of “conio.h” header file. It is also
used to get a single character from a standard input device, i.e. from the keyboard during
program execution. The main features of this function are:
 When a character is entered, it is displayed on the screen.
 Enter key must pressed to complete the input.
Its syntax is : gechar( );
The “putchar( )” function
The “putchar” stands for put a character. This function is used to put or print a single
character on the standard output device, i.e. the computer screen.
The “gets( )” function
This function is used to get (input) data into a string variable from the keyboard.
Any type of characters, including space & special characters can be entered using this function.
Enter key is pressed after entering the string. When Enter key is pressed, a null character is
appeared at the end of the string.
Its syntax is : gets( stravar);
Where
19

Strvar : represent the string type variable into which data is to be entered.
The “puts( )” function
This function is used to print a string on the computer screen. The new line is inserted after
printing the string.
It syntax is: puts(string);
The “string” may be a string constant or string type variable.
In case of a string constant, the string is enclosed in double quotes.
In case of a string variable, it is written without using quotes.
The “strlen” function
The “strlen” stands for string length. This function is used to find the length of a string. It
counts the total number of characters including spaces. Null character is excluded.
Its syntax is: in strlen(string)
Where
string : represents the string whose number of characters are to be counted. It may be a
constant string or a string type variable. It return integer type value.
The “strcmp” function
The “strcmp” stands for string compare. This function is used to compare two strings. It
compares first string whit the second string character by character.
Its syntax is: int strcmp(string1,string2)
Where:
string1: represents the first string. It may be a string constant or a string variable.
String2: represents the first string. It may be a string constant or a string variable.
This function returns integer type output as follows.
If string1 is equal to string2. it returns 0.
If string1 is equal to string2. it returns 0.
The “strlwr( )” function
The “strlwr” stands for string lower. This function is used to convert uppercase alphabetic
characters (A to Z) in the input string str into lowercase characters. All other characters are
unchanged.
Its syntax is: strlwr(string);
Where
string:represents the string whose characters are to be converted to lower case. It may be a
constant string or a string type variable.
The “strupr( )” function
The “strupr” stands for string upper. This function is used to convert lowercase alphabetic
characters (A to Z) in the input string str into uppercase characters. All other characters are
unchanged.
Its syntax is: strupr(string);
Where
string:represents the string whose characters are to be converted to upper case. It may be a
constant string or a string type variable.
The “strrev( )” function
The “strrev” stands for string reverse. This function is used to reverse alphabetic characters ( A
to Z) or (a to z) in the input string str.
Its syntax is: strrev(string);
Where
string:represents the string whose characters are to be reversed. It may be a constant string or
a string type variable.
The “pow10( )” function
This function is used to calculate 10 to the power of a given integer number x.
Its syntax is: pow10(x);
Where
x: is an integer number that represents the exponent of the number 10.
20

Example: If the value of 103 is to be calculated. The function is written as


Pow10(3).

The “Abs( )” function


This function is used to return absolute value of integer number.
Its syntax is: Abs(x);
Where
x: is an integer number. It may be an integer constant or integer type variable.
Example. If x = -9 then Abs(x) returns 9.
The “strncmp” Function
This function is similar to the “strcmp” function but it compares the specified number of
characters of the two strings.
Its syntax is : int strncmp(string1, string2, n);
Where
String1: represents the first string. It may be a string constant or a string type variable.
String2: represents the second string. It may be a string constant or a string type variable.
n: represents a specified number of characters that are to be compared. It may be an
integer constant or integer type variable.
This function returns the int type output as follows.
 If the “n” characters of string1 are equal to the first “n” characters of string2, it returns 0.
 If the “n” characters of string1 are less than the first “n” characters of string2, it returns
less than 0.
 If the “n” characters of string1 are greater than the first “n” characters of string2, it
returns greater than 0.
The “strcpy” Function
The “strcpy” stands for string copy. This function is used to copy the contents of one string to
another string variable including the null character.
Its syntax is: strcpy(string1, string2);
Where
string1: represents the first string. It must be a string type variable because the contents of
string2 are to be copied on to it.
string2: represents the second string. It may be a string constant or string variable.
For example to copy the string “ I love Pakistan” into the string variable “pak”, the statement
is written as: strcpy(pak, “I love Pakistan”)
The “strncpy” Function
This function is similar to “strcpy” function but is used to copy a specified number of
characters from one string to another string variable.
Its syntax is: strincpy(string1, string2, n);
Where
string1: represents the first string. It must be a string type variable because the first “n”
characters of string2, are to be copied into it.
string2: represents the second string. It may be a string constant or a string type variable. The
first “n” characters of this string are copied into the string1.
n: represents the number of characters of string2 that are to be copied into string1. It may
be an integer constant or an integer type variable.
For example to copy the first three characters of string “Pakistan” into the string variable pak,
the statement is written as: strncpy(pak, “Pakistan”, 3)
The “strcat” Function
The “strcat” stands for string concatenate. This function is used to append or combine the
contents of one string to another string variable including the null characters.
Its syntax is: strcat(string1,string2);
Where
21

string1: represents the first string. It must be a string type variable because the contents
of string2 are to be added at the end of this string.
string2: represents the second string. it may be a string constant or a string type variable. The
contents of this string are added at the end of the string1.
For example to add the string “istan” into the string variable abc that already contains the
string “Pak”, the statement is written as: strcat(abc, “istan”);
After executing the above function, the content of variable “abc” will be “Pakistan”.
The “strncat” Function
This function is similar to “strcat” function but it is used to append a specified number of
characters of one string to another string variable.
Its syntax is: strncat(string1,string2,n);
Where
string1: represents the first string. It must be a string type variable because the specified
number of characters of string2 are to be appended at the end of this string.
string2: represents the second string. it may be a string constant or a string type variable. The
specified number of characters of this string are appended at the end of the string1.
n: represents the number of characters of string2 that have to be appended at the end of
string1. It may be an integer constant value or an integer type variable.
For example to append the first 8 characters of string “Pakistan is my country” into the string
type variable “str” that already contains the contents “I live in”, the statement is written as.
strncat(str, “Pakistan is my country”, 8);
After executing this function, the contents of variable “str” will be “I live in Pakistan”.
The “pow()” Function
This function is used to calculate the exponential power of a given integer number.
Its syntax is: pow(x,y)
Where
x: is an integer number whose power is to be calculated.
y: is an integer number that represents the exponential of the number.
Example: If the value of 23 is to be calculated, the function is written as: pow(2,3)
The “sqrt()” Function
This function is used to calculate the square root of a given positive number.
Its syntax is: sqrt(x);
Where
x: is the positive number of type double (or variable). It also returns a value of type double.
Example: if x = 9.0 then: sqrt(x) returns 3.0
The “floor()” Function
This function is used to round a given float value to the integer value. The given float value is
converted to the largest integer than the given float value.
Its syntax is: floor(x);
Where
x: is a float or double value/variable.
Example: if x = 9.6 then floor(x) returns 9.0
If x = -9.6 then floor(x) returns -10.0

The “ceil()” Function


This function is similar to the “floor()” function but if returns the rounded integer value greater
than the given float or double number.
Its syntax is: ceil(x);
Where
x: is the given float or double type given number or value.
Example: if x = 19.2 then ceil(x) returns 20.0
22

If x = -19.2 then ceil(x) returns -19.0


The “fmod()” Function
This function is used to calculate the remainder by dividing one floating number by another
floating number.
Its syntax is: fmod(x,y)
Where
x: represent the nominator. It is a floating number or variable.
y: represent the denominator. It is a floating number or variable.
Example: if x = 9.50 and y = 4.00 then fmod(x,y) returns 1.5
The “cos()” Function
This function is used to calculate the trigonometric cosine of a given angle. The angle is given
in radians as a floating number.
Its syntax is: cos(x);
Where
x: represents an angle in radians.
Example if x = 0.0 the cos(x) returns 1.0
The “sin()” Function
This function is used to calculate the trigonometric sine of a given floating number. The angle
is given in radians as a floating number.
Its syntax is: sin(x);
Where
x: represents an angle or value in radians
Example : if x = 0.0 then sin(x) returns 0.
The “tan()” Function
This function is used to calculate the trigonometric tangent of a given floating number. The
angle is given in radians as a floating number.
Its syntax is: tan(x);
Where
x: represents an angle or value in radians
Example : if x = 0.0 then tan(x) returns 0.
The “log()” Function
This function is used to calculate the natural logarithm (base e) of a given floating number.
Its syntax is: log(x);
Where
x: represents a given floating number.
The “log10()” Function
This function is used calculate the logarithm (base 10) of a given floating number.
Its syntax is: log10(x);
x: represents a given floating number.

You might also like