C and C++ Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 89

PROGRAMMING IN C & C++

UNIT-1

[OSMANIA UNIVERSITY]
By
B.C.SANGEETHA
DEPT-IT.
STANLEY COLLEGE OF
ENGINEERING & TECH
BLOCK DIAGRAM OF COMPUTER
1. Input unit
2. Output unit
3. Memory unit( RAM, ROM,
Buffers, Shift registers)
4. Arithmetic and logic unit
(ALU)
5.Central processing unit
(CPU) The brains of the
computer that run your
program
Runs the Operating System (e.g.
windows) and all the software)
1. Secondary storage unit
Operating Systems:

Exploits the hardware resources of one or
more processors
Provides a set of services to system users
Manages secondary memory and I/O
devices.
Computer applications today require a single machine to
perform many operations and the applications may compete for
the resources of the machine.
This demands a high degree of coordination
This coordination is handled by system software known as the
operating system

1.4 Evolution of Operating Systems

Batch processing
Do only one job or task at a time

Operating systems
Manage transitions between jobs
Increased throughput - amount of work computers process

Multiprogramming
Many jobs or tasks sharing the computer resources

Timesharing
Runs a small portion of one users job then moves on to service the next user


Program execution required significant preparation of equipment
Program execution (job)
OS was a system to simplify program setup and simplify transition
between jobs
Physical separation of users and equipment led to computer operators
Machine Languages, Assembly Languages, and High-level
Languages
Three types of programming languages
1. Machine languages
Strings of numbers giving machine specific instructions
Example:
+1300042774
+1400593419
+1200274027
2. Assembly languages
English-like abbreviations representing elementary computer
operations (translated via assemblers)
Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
3.High-level languages:


Codes similar to everyday English
Use mathematical notations (translated via compilers)
Example:
grossPay = basePay + overTimePay


Other high-level languages
FORTRAN
Used for scientific and engineering applications
COBOL
Used to manipulate large amounts of data
Pascal
Intended for academic use
A language that provides a richer
(more English like) set of instructions
C History
Developed between 1969 and 1973 along
with Unix
Due mostly to Dennis Ritchie
Designed for systems programming
Operating systems
Utility programs
Compilers
Filters.
The C Standard Library
C programs consist of pieces/modules called
functions
A programmer can create his own functions
Advantage: the programmer knows exactly how it works
Disadvantage: time consuming
Programmers will often use the C library functions
Use these as building blocks
Avoid re-inventing the wheel
If a pre-made function exists, generally best to use it rather
than write your own
Library functions carefully written, efficient, and portable
Hello World in C
#include <stdio.h>

void main()
{
printf(Hello, world!\n);
}
Preprocessor used to
share information among
source files
- Clumsy
+ Cheaply implemented
+ Very flexible
Program mostly a collection of
functions
main function special: the entry
point
void qualifier indicates function
does not return anything
I/O performed by a
library function: not
included in the
language

10
2.4 Memory Concepts
Variables
Variable names correspond to locations in the computer's memory
Every variable has a name, a type, a size and a value
Whenever a new value is placed into a variable (through scanf, for
example), it replaces (and destroys) the previous value
Reading variables from memory does not change them
A visual representation



integer1

45

Every variable has a name, type and value
Variable names correspond to locations in computer memory
New value over-writes the previous value Destructive read-in
Value reading called Non-destructive read-out
integer1 45
integer2 72
sum
117

Operators
Arithmetic (+,-,*,/,%)
Relational (<,>,<=,>=,==,!=)
Logical (&&,||,!)
Bitwise (&,|)
Assignment (=)
Compound assignment(+=,*=,-
=,/=,%=,&=,|=)
Shift (right shift >>, left shift <<)
Example:
if (x != y) && (c == b)
{
a=c + d*b;
a++;
}
Arithmetic Operators
The value of i % j is the remainder when i is divided by j. For example, the
value of 10 % 3 is 1; the value of 12 % 4 is 0. The % operator requires integer
operands; all other operators allow either integer or floating-point operands.

If both operands are integers, / truncates the result toward 0.
There is no exponentiation operator.
Must use pow function defined in <math.h>
The arithmetic operators are:
+ unary plus
- unary minus
+ addition
- subtraction
* multiplication
/ division
% remainder (modulus)
Example
if ( num % 2 == 0 )
printf(%d is an even
number\n, num);
else
printf(%d is an odd
number\n, num);
DECISION MAKING

is
A>B
Print
B
Print
A
Y N
Simple C program
#include<stdio.h>
int main()
{
printf(Hello);
return 0;
}

This program prints Hello on the screen when we
execute it

15
Decision Making: Equality
and Relational Operators
Executable statements
Perform actions (calculations, input/output of data)
Perform decisions
May want to print "pass" or "fail" given the value of a
test grade
if control structure
Simple version in this section, more detail later
If a condition is true, then the body of the if
statement executed
0 is false, non-zero is true
Control always resumes after the if structure
Keywords
Special words reserved for C
Cannot be used as identifiers or variable names

16
Decision Making: Equality
and Relational Operators
Standard algebraic
equality operator or
relational operator
C equality or
relational
operator
Example of C
condition
Meaning of C
condition
Equality Operators

=
==
x == y
x is equal to y
not =
!=
x != y
x is not equal to y
Relational Operators

>
>
x > y
x is greater than y
<
<
x < y
x is less than y
>=
>=
x >= y
x is greater than or
equal to y
<=
<=
x <= y
x is less than or
equal to y

ALGORITHMS AND FLOWCHARTS
A typical programming task can be divided into two
phases:
Problem solving phase
produce an ordered sequence of steps that describe solution
of problem
this sequence of steps is called an algorithm
Implementation phase
implement the program in some programming language
ALGORITHMS AND FLOWCHARTS
A typical programming task can be divided into two
phases:
Problem solving phase
produce an ordered sequence of steps that describe solution
of problem
this sequence of steps is called an algorithm
Implementation phase
implement the program in some programming language
Steps in Problem Solving
First produce a general algorithm (one can use
pseudocode)
Refine the algorithm successively to get step by
step detailed algorithm that is very close to a
computer language.
Pseudocode is an artificial and informal language
that helps programmers develop algorithms.
Pseudocode is very similar to everyday English.
Pseudocode & Algorithm
Example 1: Write an algorithm to determine
a students final grade and indicate whether it
is passing or failing. The final grade is
calculated as the average of four marks.
Pseudocode:
Input a set of 4 marks
Calculate their average by summing and dividing
by 4
if average is below 50
Print FAIL
else
Print PASS
Detailed Algorithm
Step 1: Input M1,M2,M3,M4
Step 2: GRADE
(M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print FAIL
else
Print PASS
endif

The Flowchart
A Flowchart
shows logic of an algorithm
emphasizes individual steps and their interconnections
e.g. control flow from one action to the next
Flowchart Symbols


Example
PRINT
PASS
Step 1: Input
M1,M2,M3,M4
Step 2: GRADE
(M1+M2+M3+M4)/4
Step 3: if (GRADE <50)
then
Print FAIL
else
Print PASS
endif

START
Input
M1,M2,M3,M4
GRADE(M1+M2+M3+M4)/4
IS
GRADE<5
0
PRINT
FAIL
STOP
Y
N
Example 2
Write an algorithm and draw a flowchart to
convert the length in feet to centimeter.
Pseudocode:
Input the length in feet (Lft)
Calculate the length in cm (Lcm) by
multiplying LFT with 30
Print length in cm (LCM)
Example 2
Algorithm
Step 1: Input Lft
Step 2: Lcm Lft x 30
Step 3: Print Lcm

START
Input
Lft
Lcm Lft x
30
Print
Lcm
STOP
Flowchart
Example 3
Write an algorithm and draw a flowchart that
will read the two sides of a rectangle and
calculate its area.
Pseudocode
Input the width (W) and Length (L) of a rectangle
Calculate the area (A) by multiplying L with W
Print A
28
3.3 Pseudocode
Pseudocode
Artificial, informal language that helps us
develop algorithms
Similar to everyday English
Not actually executed on computers
Helps us think out a program before writing
it
Easy to convert into a corresponding C++ program
Consists only of executable statements

Introduction to Logical Operators
About a dozen logical operators
Similar to algebraic operators + * - /
In the following examples,
p = Today is Friday
q = Today is my birthday

29
29
Logical operators: Not
A not operation switches (negates) the truth value
Symbol: or ~
In C++ and Java,
the operand is !
p = Today is not Friday
p p
T F
F T

30
Logical operators: And
An and operation is true if both operands are true
Symbol: .
Its like the A in And
In C++ and Java,
the operand is &&
p.q = Today is Friday and
today is my birthday
p q p.q
T T T
T F F
F T F
F F F

31
Logical operators: Exclusive Or
An exclusive or operation is true if one of the operands are true,
but false if both are true
Symbol:
Often called XOR
pq (p v q) . (p . q)
In Java, the operand is ^
(but not in C++)
pq = Today is Friday or today
is my birthday, but not both
p q pq
T T F
T F T
F T T
F F F

32
Logical operators: Nand and Nor
The negation of And and Or, respectively
Symbols: | and , respectively
Nand: p|q (p.q)
Nor: pq (pvq)

p q p.q pvq p|q p+q
T T T T F F
T F F T T F
F T F T T F
F F F F T T

33
Logical operators: Conditional 1
A conditional means if p then q
Symbol:
pq = If today is
Friday, then today
is my birthday
pq pvq

p q pq pvq
T T T T
T F F F
F T T T
F F T T
the
antecedent
the
consequence

34
Logical operators: Conditional 2
Let p = I am elected and q = I will lower taxes
I state: p q = If I
am elected, then I
will lower taxes
Consider all
possibilities
Note that if p is false, then
the conditional is true regardless of whether q is true or
false
p q pq
T T T
T F F
F T T
F F T

35
Logical operators: Conditional 3
Conditional Inverse Converse Contra-
positive
p q p q pq pq qp qp
T T F F T T T T
T F F T F T T F
F T T F T F F T
F F T T T T T T

36
Logical operators: Conditional 4
Alternate ways of stating a conditional:
p implies q
If p, q
p is sufficient for q
q if p
q whenever p
q is necessary for p
p only if q
I dont like this one

37
Logical operators: Bi-conditional 1
A bi-conditional means p if and only if q
Symbol:
Alternatively, it means
(if p then q) and
(if q then p)
pq pq . qp
Note that a bi-conditional
has the opposite truth values
of the exclusive or
p q pq
T T T
T F F
F T F
F F T

38
Logical operators: Bi-conditional 2
Let p = You take this class and q = You get a
grade
Then pq means
You take this class if
and only if you get a
grade
Alternatively, it means If
you take this class, then
you get a grade and if you get a grade then you take
(took) this class
p q pq
T T T
T F F
F T F
F F T
Operators
Arithmetic (+,-,*,/,%)
Relational (<,>,<=,>=,==,!=)
Logical (&&,||,!)
Bitwise (&,|)
Assignment (=)
Compound assignment(+=,*=,-
=,/=,%=,&=,|=)
Shift (right shift >>, left shift <<)
Example:
if (x != y) && (c == b)
{
a=c + d*b;
a++;
}
Arithmetic Operators
The value of i % j is the remainder when i is divided by j. For example, the
value of 10 % 3 is 1; the value of 12 % 4 is 0. The % operator requires integer
operands; all other operators allow either integer or floating-point operands.

If both operands are integers, / truncates the result toward 0.
There is no exponentiation operator.
Must use pow function defined in <math.h>
The arithmetic operators are:
+ unary plus
- unary minus
+ addition
- subtraction
* multiplication
/ division
% remainder (modulus)
Example
if ( num % 2 == 0 )
printf(%d is an even
number\n, num);
else
printf(%d is an odd
number\n, num);
INCREMENT AND
DECREMENT OPERATORS
number = number + 1;
number = number 1;
Increment and Decrement
Operators
The ++ and -- operators increment and decrement variables.
Both operators have the same precedence as negation.
Either operator can be prefix or postfix:
++i
i++
--i
i--
When used as a prefix operator, ++ increments the variable
before its value is fetched:

i = 1;
printf("i is %d\n", ++i); /* prints "i is 2" */
Increment and decrement operators can only be
applied to variables, not to constants or
expressions
Increment and Decrement
Operators
When used as a postfix operator, ++ increments the variable
after its value is fetched:

i = 1;
printf("i is %d\n", i++); /* prints "i is 1" */
printf("i is %d\n", i); /* prints "i is 2" */

The -- operator has similar properties:
i = 1;
printf("i is %d\n", --i); /* prints "i is 0" */

i = 1;
printf("i is %d\n", i--); /* prints "i is 1" */
printf("i is %d\n", i); /* prints "i is 0" */

44
Increment Operator
If we want to add one to a variable, we can
say:
count = count + 1;
Programs often contain statements that
increment variables, so to save on typing,
Javascript provides these shortcuts:
count++; OR ++count;
Both do the same thing. They change the
value of count by adding one to it.

45
Decrement Operator
If we want to subtract one from a variable, we
can say:
count = count - 1;
Programs often contain statements that
decrement variables, so to save on typing,
Javascript provides these shortcuts:
count--; OR --count;
Both do the same thing. They change the
value of count by subtracting one from it.
46
3.12 Increment and Decrement Operators
If c equals 5, then
printf( "%d", ++c );
Prints 6
printf( "%d", c++ );
Prints 5
In either case, c now has the value of 6
When variable not in an expression
Preincrementing and postincrementing have the same effect
++c;
printf( %d, c );
Has the same effect as
c++;
printf( %d, c );

47
Assignment Operators
= += -= *= /= %=
Statement Equivalent Statement
a = a + 2; a += 2;
a = a - 3; a -= 3;
a = a * 2; a *= 2;
a = a / 4; a /= 4;
a = a % 2; a %= 2;
b = b + ( c + 2 ); b += c + 2;
d = d * ( e - 5 ); d *= e - 5;
Example 3
Algorithm
Step 1: Input W,L
Step 2: A L x W
Step 3: Print A

START
Input
W, L
A L x W
Print
A
STOP

49
Decision Making: Equality
and Relational Operators
Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Steps in Problem Solving
First produce a general algorithm (one can use
pseudocode)
Refine the algorithm successively to get step by
step detailed algorithm that is very close to a
computer language.
Pseudocode is an artificial and informal language
that helps programmers develop algorithms.
Pseudocode is very similar to everyday English.
IFTHENELSE
STRUCTURE
The algorithm for the flowchart is as
follows:
If A>B then
print A
else
print B
endif
is
A>
B
Print
B
Print
A
Y N
Relational Operators
Relational Operators
Operator Description
> Greater than
< Less than
= Equal to
> Greater than or equal to
s Less than or equal to
= Not equal to
Comments in C
Single line comment
// (double slash)
Termination of comment is by pressing enter
key
Multi line comment
/*.
.*/
This can span over to multiple lines
Data types in C
Primitive data types
int, float, double, char
Aggregate data types
Arrays come under this category
Arrays can contain collection of int or float or
char or double data
User defined data types
Structures and enum fall under this category.
Variables
Variables are data that will keep on changing
Declaration
<<Data type>> <<variable name>>;
int a;
Definition
<<varname>>=<<value>>;
a=10;
Usage
<<varname>>
a=a+1; //increments the value of a by 1
Input and Output
Input
scanf(%d,&a);
Gets an integer value from the user and stores it
under the name a
Output
printf(%d,a)
Prints the value present in variable a on the
screen

Summary:
%d is the format specifier. This informs to the compiler that the incoming value is
an integer value.

Other data types can be specified as follows:
%c character
%f float
%lf double
%s character array (string)

Printf and scanf are defined under the header file stdio.h
Keywords
These are reserved words of the C language. For
example int, float, if, else, for,
while etc.
Loop Statements:

While loop:
Do While:

Loops that do not end are called infinite loops.
Loop Statements -While
The syntax for while loop
while(condn)
{
statements;
}
Eg:
a=10;
while(a != 0)
{
printf(%d,a);
a--;
}
While the condition is true,
the statements will execute
repeatedly.
The while loop is a pretest
loop, which means that it will
test the value of the condition
prior to executing the loop.
A while loop executes 0 or more
times since if the condition is
false, the loop will not execute.
60
The while loop Flowchart
statement(s)
true
boolean
expression?
false
Loop Statements -Do While
The syntax of do while loop
do
{
set of statements
}while(condn);

Eg:
i=10;
do
{
printf(%d,i);
i--;
}while(i!=0)
The do-while loop is a post-
test loop, which means it will
execute the loop prior to
testing the condition.
The do-while loop, more
commonly called a do loop,
takes the form:
62
The do-while Loop Flowchart
statement(s)
true
boolean
expression?
false
Loop Statements - For
For statement:
for (initialization; condition; increment) {statements}

initialization done before statement is executed

condition is tested, if true, execute statements
do increment step and go back and test condition again

repeat last two steps until condition is not true
Example: for loop:
for (n = 0; n<1000; n++)
n++ means n = n + 1

Be careful with signed integers!

for (i=0; i < 33000; i++) LED = ~LED;
The for loop is a specialized
form of the while loop,
meaning it is a pre-test loop
The for loop allows the programmer to
initialize a control variable, test a
condition, and modify the control
variable all in one line of code.
64
The for Loop Flowchart
statement(s)
true
boolean
expression?
false
update
65
Deciding Which Loops to Use
The while loop:
Pretest loop
Use it where you do not want the statements to execute
if the condition is false in the beginning.
The do-while loop:
Post-test loop
Use it where you want the statements to execute at least
one time.
The for loop:
Pretest loop
Use it where there is some type of counting variable
that can be evaluated.
Conditional statement
switch(var)
{
case 1: //if var=1 this case executes
stmt;
break;
case 2: //if var=2 this case executes
stmt;
break;
default: //if var is something else this will execute
stmt;
}
Decision Making if statement
if (condition1)
{statements1}
else if (condition2)
{statements2}

else
{statementsn}
Checking falsity or truth of
a statement
Equality operators have
lower precedence than
relational operators
Relational operators have
same precedence
Both associate from left to
right
Examples
if ( age >= 18 )
{
printf(Vote!\n) ;
}

if ( value == 0 )
{
printf (The value you entered was zero.\n) ;
printf (Please try again.\n) ;
}
Selection: the if-else statement
if ( condition )
{
statement(s) /* the if clause */
}
else
{
statement(s) /* the else clause */
}
Example
if ( age >= 18 )
{
printf(Vote!\n) ;
}
else
{
printf(Maybe next time!\n) ;
}
Nesting of if-else Statements
if ( condition
1
)
{
statement(s)
}
else if ( condition
2
)
{
statement(s)
}
. . . /* more else clauses may be here */
else
{
statement(s) /* the default case */
}
Example
if ( value == 0 )
{
printf (The value you entered was zero.\n) ;
}
else if ( value < 0 )
{
printf (%d is negative.\n, value) ;
}
else
{
printf (%d is positive.\n, value) ;
}
Prof. Cherrice Traver
EE/CS-152: Microprocessors and
Microcontrollers
Decision switch statement
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}

Header Files
Header files
Contain function prototypes for library
functions
<stdlib.h> , <math.h> , etc
Load with #include <filename>
#include <math.h>
Custom header files
Create file with functions
Save as filename.h
Load in other files with #include
"filename.h"
Reuse functions
75
The break And continue Statements
The break statement can be used to abnormally
terminate a loop.
The use of the break statement in loops bypasses
the normal mechanisms and makes the code
hard to read and maintain.
It is considered bad form to use the break
statement in this manner.
76
The continue Statement
The continue statement will cause the currently executing
iteration of a loop to terminate and the next iteration will
begin.
The continue statement will cause the evaluation of the
condition in while and for loops.
Like the break statement, the continue statement should be
avoided because it makes the code hard to read and debug.

The Switch Statement
Performs multi-way branches

switch (expr)
{
case 1:
break;
case 5:
case 6:
break;
default:
break;
}

tmp = expr;
if (tmp == 1) goto L1
else if (tmp == 5) goto L5
else if (tmp == 6) goto L6
else goto Default;
L1:
goto Break;
L5:;
L6:
goto Break;
Default:
goto Break;
Break:
Code:
78
File Input and Output
Reentering data all the time could get tedious for
the user.
The data can be saved to a file.
Files can be input files or output files.
Files:
Files have to be opened.
Data is then written to the file.
The file must be closed prior to program termination.
In general, there are two types of files:
binary
text
Lectures on Numerical
Methods 79
Precedence and Order of evaluation
Operator Precedence
Examples:

i + j * k means i + (j * k)
-i * -j means (-i) * (-j)
+i + j / k means (+i) + (j / k)
Lectures on Numerical
Methods 81
Type Conversions
The operands of a binary operator must have a the same type and the
result is also of the same type.
Integer division:
c = (9 / 5)*(f - 32)
The operands of the division are both int and hence the result also
would be int. For correct results, one may write
c = (9.0 / 5.0)*(f - 32)
In case the two operands of a binary operator are different, but
compatible, then they are converted to the same type by the compiler.
The mechanism (set of rules) is called Automatic Type Casting.
c = (9.0 / 5)*(f - 32)
It is possible to force a conversion of an operand. This is called
Explicit Type casting.
c = ((float) 9 / 5)*(f - 32)
C Types
Basic types: char, int, float, and double
Meant to match the processors native types
Natural translation into assembly
Fundamentally nonportable
Declaration syntax: string of specifiers
followed by a declarator
Declarators notation matches that in an
expression
Access a symbol using its declarator and get
the basic type back.

C Statements
Expression
Conditional
if (expr) { } else {}
switch (expr) { case c1: case c2: }
Iteration
while (expr) { } zero or more iterations
do while (expr) at least one iteration
for ( init ; valid ; next ) { }
Jump
goto label
continue; go to start of loop
break; exit loop or switch
return expr; return from function
Summary
C evolved from the typeless languages BCPL and
B
Array-of-bytes model of memory permeates the
language
Original weak type system strengthened over time
C programs built from
Variable and type declarations
Functions
Statements
Expressions
Summary of C types
Built from primitive types that match processor
types
char, int, float, double, pointers
Struct and union aggregate heterogeneous objects
Arrays build sequences of identical objects
Alignment restrictions ensured by compiler
Multidimensional arrays
Three storage classes
global, static (address fixed at compile time)
automatic (on stack)
heap (provided by malloc() and free() library calls)
Summary of C expressions
Wide variety of operators
Arithmetic + - * /
Logical && || (lazy)
Bitwise & |
Comparison < <=
Assignment = += *=
Increment/decrement ++ --
Conditional ? :

Expressions may have side-effects
Summary of C statements
Expression
Conditional
if-else switch
Iteration
while do-while for(;;)
Branching
goto break continue return

Awkward setjmp, longjmp library routines
for non-local goto
Eg:The C Standard Library
#include <stdio.h>

main()
{
int i;
for (i = 0; i < 10;i ++)
{
printf ("Hello World!\n");
}
}
INITIALIZATION
CONDITION
INCREMENT

You might also like