0% found this document useful (0 votes)
55 views99 pages

Pandit Deendayal Petroleum University Gandhinagar

C and C++ are widely used programming languages. Some key points: - C was developed in the 1970s and C++ was developed in the 1980s as an extension of C with object-oriented capabilities. - They are used for operating systems, compilers, databases, games, drivers, and more. Popular applications include Windows and Linux kernels. - Programs are made up of functions that perform tasks. Functions are declared with a return type, name, and parameters. Common functions include printf() for output and scanf() for input. - Variables and constants are declared with specific data types like int, float, char. Programs follow syntax rules and use statements, expressions, comments and

Uploaded by

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

Pandit Deendayal Petroleum University Gandhinagar

C and C++ are widely used programming languages. Some key points: - C was developed in the 1970s and C++ was developed in the 1980s as an extension of C with object-oriented capabilities. - They are used for operating systems, compilers, databases, games, drivers, and more. Popular applications include Windows and Linux kernels. - Programs are made up of functions that perform tasks. Functions are declared with a return type, name, and parameters. Common functions include printf() for output and scanf() for input. - Variables and constants are declared with specific data types like int, float, char. Programs follow syntax rules and use statements, expressions, comments and

Uploaded by

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

C/C++

Pandit Deendayal Petroleum University


Gandhinagar
HISTORY OF C++
• Developed by BJARNE STROUSTRUP
• at AT&T’s BELL LABS in the early ’80s.
• Main Purpose:
– Writing programs easier for the programmer.
• C++ is based on C (superset of C).
• C++’s OOP aspect was inspired by
another computer simulation language
called SIMULA67.
USE OF C/C++
• OPERATING SYSTEMS
• EDITORS
• COMPILER CONSTRUCTION
• INTERPRETERS
• ASSEMBLERS
• DBMS/RDBMS
• APPLICATION SOFTWARE
• GENERAL-PURPOSE SOFTWARE
USE OF C/C++
• DEVELOPING GAMES
• COMMUNICATION PROTOCOLS
• DEVICE DRIVER PROGRAMMING
• PROGRAMS FOR MOBILE DEVICES
• ROBOTICS
STEPS FOR WRITING A
PROGRAM
PROGRAM

INSTRUCTION INSTRUCTION INSTRUCTION

CONSTANTS
VARIABLES
KEYWORDS

SPECIAL
ALPHABETS DIGITS SYMBOLS
C/C++ CHARACTER SET
• ALPHABETS : A … Z , a … z
• DIGITS : 0 … 9
• SPECIAL
SYMBOLS : ~ ` ! @ #
% ^ & * () _ - + =
| \ {} [] :
; “ ‘ < > , . ? /
C/C++ CHARACTER SET
• ALPHABETS : A … Z , a … z
• DIGITS : 0 … 9
• SPECIAL
SYMBOLS : ~ ` ! @ #
% ^ & * () _ - + =
| \ {} [] :
; “ ‘ < > , . ? /
VARIABLES/CONSTANTS
• VARIABLE:
Whose value can be changed.
• CONSTANT:
That never changes.
A Variable B
100 Constant ‘i’
TYPES OF CONSTANTS
CONSTANTS

PRIMARY SECONDARY
CONSTANTS CONSTANTS

Integer Constant Array, Pointer


Real Constant Structure, class
Character Constant Union, Enum
RULES: INTEGER CONSTANTS

• It must have at least one digit.


• It must not have a decimal point.
• It can be +ve or –ve.
• If no sign precedes, it is assumed
to be positive.
• No commas or blanks are allowed
within it.
RULES: INTEGER CONSTANTS

• Range:
16-bit Compiler: -32768 to +32767
32-bit Compiler:
-2147483648 to +2147483647
• Examples:
1802 +1972 -4000 -32500
RULES: REAL CONSTANTS
• It must have at least one digit.
• It must have a decimal point.
• It can be + ve or – ve.
• If no sign precedes, it is assumed
to be positive.
• No commas or blanks are allowed
within it.
• EXAMPLES: +9.02 -19.72
RULES: CHARACTER
CONSTANTS
• Any alphabet, any digit or a special
symbol enclosed within single
inverted commas is known as
character constant.
e.g. 'a' '7' '+'

• The maximum length of a character


constant can be 1 character.
DATA TYPES
DATA TYPE RANGE SIZE FORMAT
(BYTES)
signed char -128 to +127 1 %c
unsigned char 0 to 255 1 %c
short signed -32768 to 2 %d
int +32767
short unsigned 0 to 65535 2 %u
int
signed int -32768 to 2/4 (32-bit %d
+32767/-231 to Compiler)
+231-1
DATA TYPES
DATA RANGE SIZE FORMAT
TYPE (BYTES)
unsigned int 0 to 65535/ 2/4 (32-bit %u
0 to 232-1 Compiler)
long signed -2147483648 4 %ld
int to 2147483647
long 0 to 4 %lu
unsigned int 4294967295
float -3.4e38 to 4 %f
+3.4e38
double -1.7e308 to 8 %lf
+1.7e308
DATA TYPES
DATA RANGE SIZE FORMAT
TYPE (BYTES)
long double -1.7e4932 to 10 %Lf
+1.7e4932
The size and ranges of int, short and long are compiler
dependent. Sizes in this figure are for 16-bit compiler.
RULES: VARIABLE NAMES
• A variable name is any combination of 1
to 31 alphabets, digits or underscores.
• The first character in the variable name
must be an alphabet or underscore.
• No commas or blanks are allowed within
a variable name.
• No special symbol other than an
underscore ( as in tot_marks) can be
used.
RULES: VARIABLE NAMES
• No Reserve Words (Keywords) are
allowed as the name of variables.
• e.g. a A b c hr min
name1 gross_salary
• a and A are different variables.
( Case sensitive )
• These rules remain same for all types
of primary and secondary variables.
KEYWORDS
• Keywords are those words whose
meaning has been explained to the
C/C++ compiler.
• Also known as "Reserved Words".
• Can’t be used as the name of
variable.
LIST OF KEYWORDS
asm auto break case
catch char class const
continue default delete do
double else enum extern
float for friend goto
if inline int long
new operator private public
protected register return short
signed sizeof static struct
switch template this throw
LIST OF KEYWORDS
try typedef union unsigned
virtual void volatile while
ANSI C++ KEYWORDS
bool reinterpret_cast explicit
typename const_cast false
using static_cast true
mutable dynamic_cast typeid
wchar_t namespace
RULES: C/C++ PROGRAM
• Each instruction is written as a separate
statement. Series of Instruction will make
a program.
• Statement in a program must appear in
the same order in which we wish them to
be executed.
• Blank spaces may be inserted between
two words to improve the readability.
• It is a free form language.
– e.g. c = a+ b; printf ( "%d\n" , c);
RULES: C/C++ PROGRAM
• All statements are written in small case
letters.
• Every statement must end with a ; (Semi-
colon). Thus, ; acts as a statement
terminator.
Program to Add Two Numbers
Algorithm #include <stdio.h> // header file
#include <conio.h> // header file
void main( ) // function
{ /* Program to add 2 Nos. */
int a, b, c; clrscr();
printf( " Enter 2 Nos. ");
INPUT A, B scanf ("%d %d",&a,&b); // input
C=A+B c = a + b; // add 2 nos.
PRINT C printf("%d + %d = %d\n", a,b,c);
getch();
}
C Program
Header Files
• Preprocessor adds the contents of the
"stdio.h" header file to the program.
• It contains declarations for the functions
called printf ( ) , scanf ( ), etc.
• Header files are included at the beginning
of all programs.
• For using different functions, we need to
include different header files.
Header Files
• stdio.h • math.h
– printf ( ) – abs ( )
– scanf ( ) – pow ( )
• conio.h – sin ( )
– clrscr ( ) – tan ( )
– getch ( ) – sqrt ( )
– getche ( ) • Find out other
names of header
files.
FUNCTION
• Function is a self-contained block of
statements that perform a coherent task of
some kind.
• Every C/C++ program is collection of these
functions.
void main ( )
{

}
TYPES OF FUNCTION

• Built-in Functions
• User-defined Functions
FUNCTION

function name

void main ( )
{

}
FUNCTION

Return type

void main ( )
{

}
FUNCTION

void main ( arguments, if any )


{

}
FUNCTION

void main ( )
{
statement(s);
}
FUNCTION

Return type function name

void main ( arguments, if any )


{
statement(s);
}
printf() function
• Displays output on monitor.
• prototype available in stdio.h header file.
• general form
– printf(“format string”, list of variables or
constants or expression);
data
– format string
types
– Format string can contain other characters
also. They will be printed as they are.
printf() function
Examples
• printf(“%f”, 3.1415); // constant
– output : 3.1415
• printf(“%d %d %d”, p , r , n); // variable(s)
– output : 10000 10 3
• printf(“area = %.2f sqr.mtr \n” , area);
– output : area = 25.00 sqr.mtr
• cursor will be in next line because of \n.
data
printf() function
More Examples
• printf(“simple interest = %.2f”, p*r*n/100);
// expression
– output : simple interest = 3000.00
• Use of ESCAPE SEQUENCE
is allowed in format string.
in C++, we use cout object instead of printf()
function.
data
scanf() function
• used to receive input from the user.
• prototype available in stdio.h header file.
• similar to cin object in C++.
• general form
– scanf (“format string”, list of addresses of
variables);
– e.g. scanf( “%d %f %c”, &i, &pi, &ch);
• ‘&’ is address of operator.
data
scanf() function
• When you enter the data via keyboard,
they must be separated by either blank(s),
tab(s) or newline(s) characters.

• Try out this in the lab.


– scanf(“%d:%d:%d”,&hh, &mm, &ss);
• hh, mm, ss are int variable.
ESCAPE SEQUENCE
• \n New Line : cursor in the next line.
• \r carriage return : cursor at the 1st
position in current line.
• \b Backspace : moves cursor 1
position to the left from
its current pos.
• \f Form Feed : used on printer to
move to next page.
ESCAPE SEQUENCE
• \t Tab : moves to next tab stop
• \’ Single quote : displays single quote
• \” Double Quote : displays double quote
• \\ Backslash : displays backslash
• \a Alert : output on speaker.
(ascii value : 7)
Program to Add Two Numbers
Algorithm #include <iostream.h>// header file
void main( ) // function
{ /* Program to add 2 Nos. */
int a, b, c;
cout << " Enter 2 Nos. ";
INPUT A, B cin >> a >> b; // input
C=A+B c = a + b; // add 2 nos.
PRINT C cout <<“Answer=“<< c << endl;
}
C++ Program
FUNCTION PROTOTYPE
• It is a declaration that defines:
– the return type &
– The parameters of a function (arguments) &
– Type of order of the arguments.
• e.g.
– void add (void);
– void add ( int , int );
– float add (void);
– float add ( float, float );
FUNCTION PROTOTYPE
• Each declaration clearly specifies:
– the number of arguments
– the order of arguments
– type of arguments
– The type of value that each function would
return.
FUNCTION PROTOTYPE
• Compiler uses the prototype to crosscheck
the above details when you call any
function. ( also known as STRONG TYPE
CHECKING)
WHY FUNCTION?
• We can write the whole logic in main()
function itself. Then why to write separate
Function?
– Writing functions avoids rewriting the same
code over and again. (Reusability)
– Top-Down Approach can be adapted.
– Program development becomes very easy.
WHY FUNCTION?
– Divide the operation of a single program into
separate activities.
– Put each activity in a different function.
– Writing and Checking of individual function
becomes more easy.
– To maintain secrecy of code.
Various forms of Functions
• Function with No Return Value and no arguments.
– void add ( void );
• Functions with arguments but no return value.
– void add ( int , int );
• Functions with return value but having no
arguments.
– int add (void);
• Functions with return value and with arguments.
– float add ( float , float );
Functions
No Arguments/No Return Value
#include <iostream.h> void add(void)
#include <conio.h> {
void main() int a, b, c;
{ cout << “\nEnter 2 Nos.”;
// function prototype cin >> a >> b;
declaration. c = a + b;
void add(void); cout << “Answer = “ << c;
clrscr(); }
add(); // calling function.
getch();
}
Functions
With Arguments/No Return Value

#include <iostream.h> add (a , b);


#include <conio.h> getch();
void main() }
{
int a, b; void add( int x, int y)
void add( int , int ); {
clrscr(); int z;
cout << “\nEnter 2 Nos.”; z = x + y;
cin >> a >> b; cout << “Answer = “ << z;
}
How memory looks like?
function main() a b

10 20

function add() x y z

10 20 30
Functions
No Arguments/With Return Value
#include <iostream.h> float add(void)
#include <conio.h> {
void main() float x, y, z;
{ cout << “\nEnter 2 Nos.”;
float c; cin >> x >> y;
float add(void); z = x + y;
clrscr(); return z;
c = add(); }
cout << “Answer = “ << c;
getch();
}
How memory looks like?
function main() c

30

function add() x y z

10 20 30
Functions
With Arguments & Return Value

#include <iostream.h> c = add (a, b);


#include <conio.h> cout << “Answer = “ << c;
void main() getch();
{ }
float a, b, c;
float add (float, float); float add( float x, float y)
clrscr(); {
cout << “\nEnter 2 Nos.”; return x+y;
cin >> a >> b; }
How memory looks like?
function main() a b c

10 20 30

function add() x y

10 20
WHEN TO USE WHICH
FUNCTION
INPUT PROCESS OUTPUT
VOID FN FN FN
FN(VOID)
VOID MAIN FN FN
FN(INT)
INT FN FN MAIN
FN(VOID)
INT MAIN FN MAIN
FN(INT)
CONTROL STRUCTURES
• SEQUENCE STRUCTURE
• SELECTION STRUCTURE
• LOOP STRUCTURE
SEQUENCE STRUCTURE
entry
Action 1

Action 2

Action 3
exit
SELECTION STRUCTURE
entry
true false
condition

Action 1 Action 2

exit
Action 3
SELECTION STRUCTURE
• if-else
• switch
if-else (various forms)
1) if (condition) e.g. if ( a > 5)
statement; cout << a;

2) if (condition) e.g. if ( x > y )


{ {
statement(s); cout << x;
}; cout << y;
}
• Condition is evaluated in terms of zero and
non-zero.
• Non-zero means true and zero means false.
if-else (various forms)
3) if (condition)
{
statement(s)1;
} // no semicolon over here.
else
{
statement(s)2;
}; // semicolon at the end only.
if-else (various forms)
4) if (condition1) e.g. if ( avg >= 70)
{ statement(s)1; } cout << “D”;
else else
if (condition2) if ( avg >= 60)
{ statement(s)2; } cout << “1st”;
else else
{ statement(s)3; }; cout << “oth”;
if-else (various forms)
5) if (c1) C1 C2 ACTION
{
if (c2) T T S1
{ s1; } T F S2
else F - S3
{ s2; };
} T means (Non-zero)
else F means (zero)
{ s3; };
Relational Operators
• == Equality operator.
– (do not use =, as = is assignment operator.)
• > Greater than
• < Less than
• >= Greater than or Equal to
• <= Less than or Equal to
• != Not equal to
Logical Operators
• You can join two conditions within one
condition with the help of logical operators.
• &&and (Binary Operator)
• || or (Binary Operator)
• ! Not (Unary Operator)

• Binary Operator requires 2 operands.


• Unary Operator requires only 1 operand.
Logical Operators
• Examples:
(1) if ( (a>b) && (a > c) )
cout << a << “ is largest.”;
(2) if ( (p < 35) || (c < 35) || (m < 35))
cout << “You are fail.”;
(3) if (! flag) // if (flag == 0)
cout << “ You can’t go ahead.“;
Short Circuit
• || and && have a feature of short circuiting an
expression.

• ||
– if the first expression evaluates to true, the following
expression is not evaluated.
• &&
– if the first expression evaluates to false, the following
expression is not evaluated.
Examples of Short Circuit
int a, b, c;
a = 4; b = 10; c = 30;

if ( ( a < b ) || ( a < c ) )
/* (4<10)||(4<30) */
...

if ( ( a > b ) && ( a > c ) )


/* (4>10)&&(4>30) */
The Conditional Operators
• ()?:

• (Expression1) ? Expression2 : expression3

• y = ( x > 5) ? 3 : 4;
means if x > 5, y = 3 otherwise y = 4

• int big, a, b, c;
• big = ((a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) );
Increment/Decrement Operators
• Unary
• ++ increment
• -- decrement
• Each has two flavours, pre and post
• Applies to integer data-types only
Pre Increment
• Value of variable is incremented and then
used in expression
• Syntax

++variableName
Example
int a, c;
a = 10;

/* increment first, then take value */


c = ++a;
i.e. a = a + 1; c = a;

/* a is 11 */
/* c is 11 */
Post Increment
• Value of variable is used in expression
and later incremented
• Syntax

variableName++
Example
int a, c;
a = 10;

/* take value first, then increment */


c = a++;
i.e. c = a; a = a + 1;

/* a is 11 */
/* c is 10 */
Decrement operator
• Pre Decrement
– Similar to Pre Increment
– Syntax :
--variableName
• Post Decrement
– Similar to Post Increment
– Syntax :
variableName--
Operator Precedence
• Multiple operators in an expression
• Precedence decides the order of application of
operators
• Specified by a precedence table
• Operators at the top have higher precedence
• Operators in the same row have same
precedence
• () can be used to override precedence rules
Precedence of operators
() [] -> (Highest precedence)
! ~ ++ -- (type)* & sizeof
* / %
+ -
<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= (Lowest precedence)
Exercise-Write C++ Program for
the following.
1. Find out largest and smallest of two values.
2. Find out largest and smallest of three values.
3. Find out net salary where net salary = gross
salary + allowances – deductions.
If gross salary > 10000, allowances are 10%,
deductions are 3% of gross salary.
If gross salary > 5000, allowances are 7%,
deduction are 2% of gross salary.
Exercise-Write C++ Program for
the following.
4. Calculate total, average of marks of three
subjects. Give following grades to the
student.
If average >= 70, distinction, if average >=
60, first class,
if average >= 50, second, if average >= 35,
third class,
Otherwise fail. If student secures < 35 marks
in any subject then declare student fail.
Exercise-Write C++ Program for
the following.
5. Find out whether a given no. is divisible by 7
or not.
6. Find out net sales where net sales = gross
sales – discount.
If gross sales > 20000, discount is 15%
If gross sales > 10000, discount is 10%
otherwise 5%.
SWITCH-CASE-DEFAULT
• Control statement
• Allows us to make a decision from the
number of choices.
• switch( integer expression)
{
case constant1 : { statements1 }
break;
case constant2 : { statements2 }
default : { statement3 }
}
SWITCH-CASE-DEFAULT

expression

has value constant 1 statements 1 break

constant 2 statements 2
missing break
control falls through

statements 3
default
SWITCH-CASE-DEFAULT
int i = 25;
switch (i)
{
case 121: cout << 121 << endl;
break;
case 7: cout << 7 << endl; break;
default: cout << “ I am in default “;
}
SWITCH-CASE-DEFAULT

if i ==

has value 121 cout << 121; break

7 cout << 7;

default cout << “default”;


SWITCH-CASE-DEFAULT
char c = ‘x’;
switch (c)
{
case ‘v’ : cout << “ I am in case v.\n”;
case ‘a’ : cout << “ I am in case a.\n”;
case ‘x’ : cout << “ I am in case x.\n”;
default : cout << “ I am in default.\n”;
}
SWITCH-CASE-DEFAULT
The output will be
I am in case x.
I am in default.
why?
we have not written break statement.
SWITCH-CASE-DEFAULT
char c = ‘a’;
switch (c)
{
case ‘a’ :
case ‘A’ : cout << “ I am in case a.” << endl;
break;
case ‘1’ : cout << “ I am in case 1.” << endl;
break;
}
LOOP STRUCTURE
entry
Let us
Understand
loop
do…while
true
condition Action 1
while
false
Action 2 for
exit
Flow of do…while loop

initialization

Update/
statement
loop back

yes no
condition
DO…WHILE LOOP STRUCTURE
A
A
E B
E
F
do
D C {
G D

} while ( C );
G
Examples of do…while loop
Print 1st 10 natural numbers. Print 1st N natural numbers.
INPUT N
I=0 1 I=0 1

PRINT I PRINT I
+1 10 +1 N

cout << “Enter a Value.”;


i = 0; cin >> n; i = 0;
do do
{ {
i ++; ++i;
cout << i << endl; cout << i << endl;
} while ( i < 10 ); } while ( i < n ) ;
Flow of while loop

initialization

no
condition
loop back
yes
Update/
statement
WHILE LOOP STRUCTURE
A
A
E B
E
F

while ( C )
D C
G
{
D

F
};
G
Examples of while loop
Print 1st 10 natural numbers. Print 1st N natural numbers.
INPUT N
I=0 1 I=0 1

PRINT I PRINT I
+1 10 +1 N

cout << “Enter a Value.”;


i = 0; cin >> n; i = 0;
While ( i < 10 ) while ( i < n )
{ {
i ++; i += 1;
cout << i << endl; cout << i << endl;
}; };
Flow of for loop

initialization

loop back no
condition

yes
update

statement
FOR LOOP STRUCTURE
Steps for writing Algorithm
A
A: Statements to be
E B executed before loop begins
B: Starting Value
F C: Ending Value
D: Difference
D C E: Control Variable (C.V.)
G = Initial Value (I.V.)
F: Loop Statements
G: Statements to be
executed after loop ends.
for ( C.V.= B ;C.V. <= C ; C.V. + D )
{
F
};
Examples of for loop
Print 1st 10 natural numbers. Print 1st N natural numbers.
INPUT N
I=0 1 I=0 1

PRINT I PRINT I
+1 10 +1 N

cout << “Enter a Value.”;


cin >> n;
for ( i = 1 ; i <= 10 ; i = i + for ( i = 1 ; i <= n ; i = i + 1 )
1) {
{ cout << i << endl;
cout << i << endl; };
};
Comparison of
while and do…while
• while is top-tested loop.
– Condition is checked before loop body is being
executed.
– If condition is true, then only loop gets executed.
– It may happen that loop may not be executed at all.
• do…while is bottom-tested loop.
– Condition is checked after loop body is executed.
– Even if condition is false, it will execute the loop
body once.
Keywords break and continue
• Keywords break and continue are used
with for, do…while and while loop.
• break brings you out of the innermost
loop.
• continue skips the remaining statements
of the same loop but keeps you within the
same loop only.
For Practice work, refer to the list given in chapter 3.

You might also like