Anda di halaman 1dari 402

Programming in C– An


Lecture 1-2
Character set, Variables and Identifiers, Built-in Data
Types, Variable Definition ,Expressions,Constants and
Literals ,Simple assignment statement, Basic input/output
statement, Simple C Programs
C Programming Language
• What is C?
– C is a structured, relatively low-level, portable
programming language.
• Why study C?
– Many popular software tools are written in C.
– Has strongly influenced many other languages.
• C-shell, java, C++, Perl, etc.
– Forces the user to understand fundamental aspects of
– Very concise language.
History of C
• C
– Evolved by Ritchie from two previous
programming languages, BCPL and B
– Used to develop UNIX
– Used to write modern operating systems
• Hardware independent (portable)
– By late 1970's C had evolved to "traditional C"
C, cont.
• Is C object-oriented?
– No. C++ (its successor) is.
• Can a non OO language be useful?
– Yes.
• Is C a hard language to learn?
– No, but it does take a little getting used to.
• What is the ANSI part?
– American national standards institute – uniform
standard definition of C for portability.
A Hello World Program
/*The first program.*/ Result is :
#include <stdio.h>
int main(void) //main function
printf(“Hello, world!\n”);
return 0;
• Source code
– Text of a program.
– The input to the C compiler.
• Object code
– Translation of the source code of a program into
machine code.
– The input to the linker.
• Linker
– A program that links separately compiled modules
into one program.
– The output is an executable program.
Terms (cont.)
• Library
– The file containing the standard functions that
a program can use.
• Complier time
– The time during which a program is being
• Run time
– The time during which a program is executing.
Language Types
• Three types of programming languages
1. Machine languages
• Strings of numbers giving machine specific
• Example:
2. Assembly languages
• English-like abbreviations representing elementary
computer operations (translated via assemblers)
• Example:
Add overpay
Language Types, Cont.
3. High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via
• Example:
grossPay = basePay +
High-level Languages
• “high-level” is a relative term
• C is a relatively low-level high-level language
• Pascal, Fortran, COBOL are typical high-level
• Java, Python, Perl, VB are examples of high-level
high-level languages
• Application specific languages (Matlab,
Javascript, VBScript) are even higher-level.
What is Data types in C
• A Data type is a collection of values with
shared properties
• Using types makes a program easier to read
and understand
• Using types makes it easier for the compiler
• Types makes it easier to detect certain
programming errors
Data types Contd……
• Each variable has a type and a value
– The type determines the meaning of the operations that can
be applied to the value
int i,j;
double d;
float x;
determine the operations and space requirements of the
• The data type of every variable must be declared before that
particular variable can appear in a statement
Data types Contd….
• Four basic types
– char – a single byte capable of holding just one
– int – an integer
– float – single-precision floating point
– double – double precision floating point
• No boolean type in C
– True and false are represented by 1 and 0
Fundamental Data Types
char signed char unsigned char

short int long

unsigned unsigned unsigned

short long
float double long double
Declaring types
• Declaration allocates a block of memory
– Type dictates the size of this block
• char – 1 byte (8 bits)
– ASCII character code
• int – 4 bytes
• long int – 4 bytes
• float – 4 bytes
• double – 8 bytes
• int is short for integer
• Integers are whole numbers
– (no fractional part, no decimal point)
• Can be positive and negative
• Short and long
• Signed and unsigned
• C has no specific standard on the size of an “int”,
it varies from one C system to another
• Normally, an int is stored in 2 bytes or 4 bytes
int contd…..
• Integer variables are declared
int variable_name;
e.g. int a; declares that you want to create an int
variable called a
• int is considered the “natural” type for working
with integers
• Sometimes extra digits are needed to store large
numbers not allowed in int
long int variable_name; /* 32 bits, not 16
• Whereas less storage is indicated
short int variable_name;
int contd….
• Unsigned integers contain only positive
values, e.g. unsigned int variable_name;
• Signed integers allow both positive and
negative numbers
• All int declarations default to signed, i.e.
signed int variable_name;
Is equivalent to
int variable_name;
{ int a, b, c, ;//declaration
unsigned u=10;// declaration
a =12; b =-24; //assignment
c =a+u;d=b+u;// assignment
printf(“a+u=%d,b+u=%d\n”,c, d);

a+u=22, b+u=-14
Integer overflow
• At run-time a variable may be assigned an
incorrect value. If a value is greater than the
maximum value which can be stored in a
variable of type int, we get integer overflow
Floating points
• A real or floating point number has an integral part
and a fractional part, separated by a decimal point,
e.g. 0.02, 170.234, 3e+5
• Floating point numbers can be either positive or
negative – always signed in C
• 3 floating types in ANSI C:
– float, double, long double
• The working floating type in C is double, not float
Floating points contd….
• The type float denotes normal precision real
• Single precision floating point numbers are
float variable_name;
Floating points contd….
• The type double denotes double precision
real numbers
• Double precision floating point numbers are
double variable_name;
Floating points contd….
• The possible values assigned to a floating
type are described in terms of attributes
called precision and range
– The number of significant decimal places that a
floating value carries is called precision
– The limits of the largest and smallest positive
floating point values that can be represented in
a variable of that type is called range
Lexical Elements of the C Language

• C Program is viewed as a sequence of Tokens

separated by White Space (i.e., spaces, tabs, new
lines). These tokens include:

– Keywords.
– Identifiers.
– Constants.
– String constants.
– Operators.
– Punctuators.
• Reserved words.
• Cannot be redefined or used in other
• Case sensitive.
• Have a special predefined meaning.
Reserved Words (Keywords) in C

int long
• auto break register return
• case char short signed
• const continue sizeof static
• default do struct switch
• double else
typedef union
• enum extern
unsigned void
• float for
volatile while
• goto if
• They refer to fixed values that the program
may not alter.
• They can be of any of the basic data types.
Integer: 1. Decimal 0, 77

2. Octal (Base 8) Digits 0. .7

3. Hexadecimal (Base 16)

Digits 0…9, A…F

Floating Point: Need a decimal pt or Scientific


Character: Any single printable character in single

quotes. „?‟, „A‟, „9‟…..
String Constant
• A character, or more likely a sequence of
characters, enclosed in “double quotes”.
A string is an array of characters.
“A” and „A‟ are not the same.
„A‟ is a string containing only one letter.

H e l l o ! \0
“A” is actually A followed by the null character
String Constants (cont.)

“a string of text”

“” // the null string

“” // a string of a blank character

“ a = b + c; ” // nothing is executed
• They are located by the compiler as tokens and
are used to separate language elements.
Parentheses ( ) Braces {}
Commas , Semicolons ;

int main(void)
int a, b=3, c=6;
a = 17 * (b + c);

• Multi-Line comments: /* this is a multiline
comment */

– May be placed anywhere in a program, as long as they

do not appear in the middle of a keyword or identifier.
x = 10+ /* add the numbers */5; //correct

swi/*this will not work*/tch(c) { . . .}; //wrong

– May not be nested.

/* this is an outer comment
x = y/a;
/* this is an inner comment - and causes an error */
*/ //wrong
• Single-Line Comments:
// this is a single-line comment
– A single-line comment can be nested within a
multi-line comment.

/* this is a // test of nested comments. */

– All but the most obvious functions should

have a comment at the top that states what the
function does, how it is called, and what it
Variables in C
• Naming Variables
• Declaring Variables
• Using Variables
• The Assignment Statement
What Are Variables in C?
• Variables in C have the same meaning as
variables in algebra. That is, they represent some
unknown, or variable, value.

z + 2 = 3(y - 5)
• Remember that variables in algebra are
represented by a single alphabetic character.
Naming Variables
• Variables in C may be given representations
containing multiple characters. But there are
rules for these representations.
• Variable names in C
– May only consist of letters, digits, and underscores
– May be as long as you like, but only the first 31
characters are significant
– May not begin with a number
– May not be a C reserved word (keyword)
Naming Conventions
• C programmers generally agree on the following
conventions for naming variables.
– Begin variable names with lowercase letters
– Use meaningful identifiers
– Separate “words” within identifiers with underscores
or mixed upper and lower case.
– Examples: surfaceArea surface_Area
Case Sensitivity
• C is case sensitive
– It matters whether an identifier, such as a variable
name, is uppercase or lowercase.
– Example:
are all seen as different variables by the compiler.
Declaring Variables
• Before using a variable, you must give the
compiler some information about the
variable; i.e., you must declare it.
• The declaration statement includes the
data type of the variable.
• Examples of variable declarations:
int balls ;
float area ;
Declaring Variables (con‟t)
• When we declare a variable
– Space is set aside in memory to hold a value of the
specified data type
– That space is associated with the variable name
– That space is associated with a unique address
• Visualization of the declaration
int balls ; balls

More About Variables
C has three basic predefined data types:
• Integers (whole numbers)
– int, long int, short int, unsigned int
• Floating point (real numbers)
– float, double
• Characters
– char
Using Variables: Initialization
• Variables may be be given initial values, or
initialized, when declared. Examples:

int length = 7 ; 7


float diameter = 5.9 ; 5.9


char initial = „A‟ ; ‘A’

Using Variables: Initialization
• Do not “hide” the initialization
– put initialized variables on a separate line
– a comment is always a good idea
– Example:
int height ; /* rectangle height */
int width = 6 ; /* rectangle width */
int area ; /* rectangle area */
Using Variables: Assignment
• Variables may have values assigned to them through the
use of an assignment statement.
• Such a statement uses the assignment operator =
• This operator does not denote equality. It assigns the
value of the righthand side of the statement (the
expression) to the variable on the lefthand side.
• Examples:
diameter = 5.9 ;
area = length * width ;
Note that only single variables may appear on the lefthand
side of the assignment operator.
Example: Declarations and
#include <stdio.h> garbage
int main( ) fathoms
int inches, feet, fathoms ; 7
fathoms = 7 ; 42
feet = 6 * fathoms ; inches

inches = 12 * feet ; 504

Example: Declarations and Assignments

printf (“Its depth at sea: \n”) ;
printf (“ %d fathoms \n”, fathoms) ;
printf (“ %d feet \n”, feet) ;
printf (“ %d inches \n”, inches) ;

return 0 ;
Input and Output Using stdio.h
• printf
– Provides formatted input and output
– Input for printf is a format specification followed
by a list of variable names to be displayed
– printf(“variable %d is %f\n”, myint, myfloat);
• scanf
– Provided an input format and a list of variables
– scanf(“%d”, &myint);
Escape characters
Escape Description
\n Newline, position cursor at the start of a new
\t Horizontal tab, move cursor to the next tab
\r Carriage return. Position cursor to the
beginning of the current line; do not
advance to the next line.
\a Alert, sound system warning beep
\\ Backslash, print a backslash character in a
printf statement
\” Double quote print a double quote character
in a printf statement.
Format Specifiers for printf and scanf
Data Type Printf specifier Scanf specifier
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long %lu %lu
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
A simple C Program that reads in two
numbers,stores them and prints out the sum

int x,y; /* places to store numbers */
printf("Enter x ");
printf("Enter y ");
printf("The sum of x and y was %d\n",x+y);
C Program Read string and show output.

#include <stdio.h>
int main(void)
char str[80];
printf("Enter a string: ");
scanf(''%s", str);
printf("Here's your string: %s", str);
return 0;}
How to read characters
• You can read char values with the scanf
• C provides a function called getchar()
which allows you to read characters one at a
time from a line of input.
• Function contained in stdio.h
• getchar() returns an int code for a character
typed on the standard input (the keyboard)
char c;
c = getchar() ;
How to print a char
• Can use printf with a format control string of %c.
• For example,
printf( “The character is %c\n”, c );
• Can use another function in stdio.h called
• For example,
putchar( c ) ;
• Prints a character to the standard output
• Is a function also referenced in stdio.h
Using getchar() example
#include <stdio.h>
int main()
{char c; /* declare character variable */
/* read a character and store it in c */
c = getchar() ;
/* print it twice, two different ways */
printf("%c\n", c );
putchar( c ) ;/* one character at a time so here‟s the
newline */
c = '\n' ;
putchar( c );} /* end program */
Field Width Specification

printf (“more numbers: %7.1f %7.2f %7.3f”, 4.0,

5.0, 6.0);

more numbers:_ _ _ _ 4.0 _ _ _ 5.00 _ _ 6.000

Field width. Precision

# of columns output. # of decimal digits to

including dec. pt. right of decimal pt.

Field Width Specification
Character Data:

printf (“%c %5c/n %4c”, „x‟, „y‟, „z‟);

x_ _ _ _ y
_ _ _z
Review questions
1. C's output function printf() is
• part of the 'C' language
• a library function
• a function users must write as part of every 'C'
• another name for the function print
2. An escape character can be included in a 'C'
string by including the following characters in the
• \e
• \033
• \0x1B
3.Conventionally 'C' source files have names ending in
4.The effect of writing print() rather than printf() is that
•The program will not compile
•The program will work as expected
•The program will display "hello world" in inverse
•The program will not link correctly
5. All 'C' programs must include
• The keyword 'program'
• A function called 'main'
• The name of the author
• A lest one use of the printf() function
• ___, ___, ____, _____, _______ are the
different data types in C.
• . String variables are terminated
automatically with _______ .
• . _____ is the escape sequence for bell.
• . Floating-point constant contains either a
_______ or an _______ or both.
• . Signed integers can range ______ and
unsigned integers can range ______
Programming With
Integers - Exercises
Write a C program to print out the sum
of two numbers in the form
The sum of 3 and 4 is 7 I.e. display the
numbers as well as their sum.

Write a program which inputs 2

characters using getchar() and swaps
Part A

Q 1: Fill in the blanks :

a) Basic data types in C are ________, _______, _______

and __________.

b) __________ terminates a statement in C.

c) The symbols _____ and ______ mark the beginning and end
of a comment.

d) Every C program must have a function called _________.

e) In a variable name the first character must be _______.

Q 2: State True/False:

a) All variables must be declared before their usage in a program.

b) An integer variable will be initialized to zero automatically if not done


c) Comments must be restricted to one line only.

d) Comments must begin at the start of a line only.

e) getchar(c) accepts the value of c from the terminal.

f) putchar() function prints a string on the terminal.

Part B

Q 1: Write a program which inputs 2 characters using getchar() and swaps

Lecture 3
• Arithmetic Operators

• Relational and Logical Operators

• Special Operators
Arithmetic Operators
Operator Action
– Subtraction, also unary minus
+ Addition
* Multiplication
/ Division
% Modulus
-- Decrement
++ Increment
Precedence and Associativity
• Precedence of the Arithmetic operators:

High ++ --
- (unary minus)
* / %
Low + -

-a*b–c ((- a) * b) – c
• Expressions inside parentheses are evaluated

1 * (2 - 3)

• Operators on the same level of precedence are

evaluated from left to right.

1 + 2 + 3 + 4 –5

(((1 + 2) + 3) + 4) –5
Increment & Decrement Operators
• Provide a concise notation for incrementing or
decrementing a variable by 1.
Are unary operators.
• ++x or x++ --x or x--

• Can be applied to variables but not to constants

or ordinary expressions.
++i; legal
cnt--; legal
777++; illegal
++(a * b -1); illegal
• May either prefix or postfix the operand.

Prefix ++x; or Postfix x++;

x = x + 1;

++ & -- both cause a value of a variable to

change in memory.
( Have a side effect).
Increment Postfix: i++;
Expression value is the current value (Before you
increment) then it increments.
“use - then increment”

Increment Prefix: ++i;

Expression value is the value After you increment.
“increment - then use”

Decrement Postfix: i--;

“use - then decrement”

Decrement Prefix: --i;

“decrement - then use”
x =10; y = ++x; y 11
x =10; y = x++; y 10

int i = 3, j = 2, k;

i++; i 4
j = ++i; j 5 i 5
k = i++; k 5 i 6
k = (--j+3) k 7 j 4
l = 4;
n = 3;
m = 2;

x = l * n + m++; x 14

After the assignment to x. 3

int a, b, c=0;
a = ++c;
b = c++;
a= ? b= ? c= ?

int b = 2, d = 4;
7--b*++d 7-((-
b)*(++d)) ?

int j = 2, k = 3, m = 4;
j=(j*(k=(m+5))) ?
int a,b;
a = 1;
b = 12;

printf (“a+++b = %d/n”, a+++b);

a = 1;
b = 12;
printf (“a++ +b = %d/n”, a++ +b);
a = 1;
b = 12;
printf (“a+ ++b =% d/n”, a+ ++b);
Relational and Logical Operators
• Relational refer to the relationship that
value can have with one another.

• Logical refers to the ways these

relationships can be connected.

• True is any value other than zero. False is

Relational Operators:
Operator Action
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
== Equal
!= Not equal

Logical Operators:
Operator Action
&& AND
|| OR
Precedence and Associativity

High !
> >= < <=
= = !=
Low ||

!0&&0||0 ((!0)&&0)||0 FALSE

int x;
x = 100;
printf(''%d", x>10); __?

• Both are lower in precedence than the

arithmetic operators.

10 > 1 + 12 10 > (1 + 12) FALSE 0

Associativity left to right.
!A is false (0) if A‟s value is: __.
is true (1) if A‟s value is: __.

!!5 ! (!5) ! (0) 1

NOT (Any NON-zero) 0

5 && 3 ?
int i, j = 1;

j = j && (i = 2); ( ) needed

1) (i=2) i 2

2) && j 1 && 2
true && true 1

3) = j 1
j 1 i 2
j = j && (i = = 3); ( ) not needed

1) (i = = 3) false 0

2) && j 1 && 0 0

3) = j 0
j 0 i 2

j = j || (i/2) ( ) not needed

1) (i/2) (2/2) 1

2) || j 0 || 1 true 1

3) = j 1
j 1 i 2
j = !j && (i = i + 1);

1) i+1 3

2) = i 3

3) ! !j !1 0

4) && 0 && 3

5) = j 0
The Comma Operator
Lowest precedence of all the operators.
Causes a sequence of operations, “do this
and this and this…”.
Is a binary operator.
expression_1, expression_2
Associates left to right.

expression_1 is evaluated first

expression_2 is evaluated second
x = (y=3, y+1); x 4 ( ) needed
 The Comma Expression as a whole has
the value and type of expression_2.

int i = 2;
j = 4;

j = i++, i - j;
*i 3
*j -1 (3-4)
• It allows multiple initializations and
multiple processing of indices.

for (sum=0, i=1; i<=n; ++i)

sum += i;

Comma Operators can be

useful in control statements
though many “C” advocates
discourage their use.
e.g. int i;
i = 0;
for ( ; i < 10; putchar („a‟ + i), i++);

will output?
3rd expression in the for statement is a comma

putchar is called ,executed.Then i is increased.

Most commas in a program DO NOT

represent comma operators.
The ( ) and [ ] Operators
• Parentheses are operators that increase the
precedence of the operations inside them.

• Square brackets perform array indexing

int main(void)
char s[80];
s[3] = 'X';
printf(''%c", s[3]);
return 0;
The Conditional Operator
• Ternary operator.
• A powerful and convenient operator that
replaces certain statements of the if-then-
else form.
Exp1 ? Exp2: Exp3

Stands for: if Exp1

then Exp2
else Exp3

x = 10;
x = 10;
y = x>9 ? 100 : 200; if(x>9)
y = 100;
y = 200;
( ) not needed
int i, h, j = 2;

i = (j==2) ? 1:3; i get 1

k get max of I
k = (i>j) ? i:j; or j
This statement does what?

c = (c > =„a‟ && c < = „z‟) ? c - („z‟ - „Z‟):c;

IF True - have a Lower case letter in the variable

Exper2: c - („z‟ - „Z‟) will give Capital
Letter of whatever is in C.

e.g. a - („z‟ - „Z‟)

97 - (122 – 90) = 65 which is „A‟.

IF False – Capital Letter and leaves it alone.

• An expression in C is any valid
combination of operators, constants,
functions and variables.
• An statement is a valid expression
followed by a semicolon.
func(); /* a function call */

a = b+c; /* an assignment statement */

b+f(); /* a valid, but strange statement */

; /* an NULL statement */
Null Statement: ; [A semi-colon
alone by itself].

Can be useful in loops & conditional

The body of a loop could be empty
Scanf(“%d”, &x);
While(printf(“%d”,x) ,scanf(“%d”,&x))
Expressions (cont.)
• Spacing and Parentheses
x = 10 / y - (127/x);
• Redundant or additional parentheses do not
cause errors or slow down the execution of
an expression.
x = y/3-34*temp+127;
x = (y/3) - (34*temp) + 127;
• Given a as 4. If b=a++, then b will be ___
and if b=++a, b will be ____ .
• The order of the evaluation of the
expression depends on ______ and ______
• In assignment operator, assignment is done
from _____ to ______ .
• The logical operators in C are
• ?: is similar to __________ construct of C.
Exercise Contd….
• The type of a variable decides the operators that
can at on them.
• Unary * has a greater precedence over ++.
• The ! Operator converts a zero to one and a non-
zero value to zero.
• = = is a logical operator to check the equality of
two operands.
• Type conversions involve converting a narrow
type to wider type
• += is one of the ternary operator in C.
• & and * are also kinds of unary bit wise
• ++p and p++ means the same in an assignment
Exercise contd….
•Write a program to read in 3 integers and print
their sum.
•Write a program to read in two integers and
display both the quotient and the remainder
when they are divided.
•How does your computer treat the results of
division by a negative number? What happens
when you try and divide by zero?
•What error message does your compiler give
when you write
x+1=x in a program?
Exercise contd…..
• Write a program to test the
behaviour of your computer
system when it processes
• printf("%d %d\n",x++,++x);

• How do you think the computer

will evaluate

What will be displayed in each of the following :

a) a = 7;
b = a++;
printf ("%d", b);
b) a = 7
b = ++a;
printf ("%d", b);
c) a = 5;
d) a = 5;
while(--a) printf("hello");

e) a = 5;
while(a--) printf("hello");

Write a program to calculate the area of a circle after accepting the

radius of the circle from the standard input.
Control constructs
Conditional Execution
Lecture 4
• if
• switch
if statement
• Conditional execution:

if (Boolean expression) statement;

else statement;

Where a statement may consist of a single

statement, a code block, or empty statement.

The else clause is optional.

if – logic: if (Boolean Expression) Yes-
For a
statement_1; Semi-colon

If-else-logic: if (Boolean Expression){

} No Semi-colon

• Conditional execution allows you write

code that reacts to tested conditions.
#include <stdio.h>
int main ( )
double salary, payrate;
int hours, union;
printf (“Please enter hours worked, payrate,
and union status”);
printf (“Enter 1 if a union member, 0 if
Example contd……

scanf (“%d%lf%d”, &hours, &payrate, &union);

if (hours > 40 && union = = 1)

salary = (40 * payrate) + ((1.5 * payrate) * (hours
- 40));
salary = payrate * hours;

printf (“Salary is: $ % 6.2 f”, salary);

Nested ifs
Nested: One statement coded within
another statement.

Nested ifs: An nested if is an if that is the

target of another if or else.

Why Nested ifs? A simple - if and if - else

statement are used to handle
2-choice tasks.
Nested ifs: Needed to handle tasks
where we have 3 or More
options that are mutually
#include <stdio.h> Nested IF statements
{ int score;
printf(“Please type in your score:”);
scanf(“%d”, &score);
printf(“Your grade is a “);
if (score >= 90) printf{“A”);
if (score >= 80) printf(“B”);
if (score >=70) printf(“C”);
if (score >=50) printf(“D”);
if (score >= 40) printf(“D”);
The if-else-if ladder

• General form:
if (expression) statement;
if (expression) statement;
if (expression) statement;
else statement;
• The conditions are evaluated from the top
• As soon as a true condition is found, the
statement associated with it is executed and the
rest of the ladder is bypassed.

• If none of the conditions are true, the final else

is executed. That is, if all other conditional tests
fail, the last else statement is performed.

• If the final else is not present, no action takes

place if all other conditions are false.
E.g. You are a salesperson for the Widget
Manufacturing Co. You will earn a salary
bonus according to the following rules:

Sales > = $50,000 earn $5,000

Sales > = $100,000 earn $15,000
Sales > = $150,000 earn $30,000
double sales, bonus;
printf (“please enter total sales”);
scanf (“%lf”, &sales);

if (sales < 50000)

bonus = 0;
else if (sales < 100000)
bonus = 5000;
else if (sales < 150000)
bonus = 15000;
bonus = 30000;
Conditional Expression
• The expressions must simply evaluate to
either a true or false (zero or nonzero)

• The expressions are not restricted to

involving the relational and logical
The ?: Alternative
Exp1 ? Exp2: Exp3

x = 10;
x = 10;
y = x>9 ? 100 : 200; if(x>9)
y = 100;
y = 200;
#include <stdio.h>
int f1(int n);
int f2(void);

int main(void)
int t;
printf("Enter a number: ");
scanf("%d", &t);
t ? f1(t) + f2() : printf("zero entered.");
return 0;
/* Divide the first number by the second. */
#include <stdio.h>

int main(void)
int a, b;
printf("Enter two numbers: ");
scanf(''%d%d", &a, &b);
if(b) printf("%d\n", a/b); if(b != 0) printf("%d\n", a/b);
else printf("Cannot divide by zero.\n");

return 0;
switch statement
• switch is a multiple-branch selection
statement, which successively tests the
value of an expression against a list of
integer or character constants (floating
point expression, for example, are not

• When a match is found, the statements

associated with that constant are executed.
General Form
switch (expression) {
case constant1:
statement sequence
case constant2:
statement sequence
statement sequence
} //ANSI C allowed at least 257 case statements.
• The value of the expression is tested against the
constants specified in the case statements in a
top-down order..
• When a match is found, the statement
sequence associated with that case is executed
until the break statement or the end of the switch
statement is reached.

• When break is encountered in a switch, program

execution "jumps" to the line of code following
the switch statement.
• The default statement is executed if no matches
are found.
• The default is optional.
• The switch differs from the if in that switch can
only test for equality, whereas if can evaluate
any type of relational or logical expression.

• No two case constants in the same switch can

have identical values. Of course, a switch
statement enclosed by an outer switch may have
case constants that are in common.

• If character constants are used in the switch

statement, they are automatically converted to
integers (as is specified by C's type conversion
• The switch statement is often used to process keyboard
commands, such as menu selection. The following
function will when called: display the options, allow the
user to make a selection, and then evoke the appropriate
function to perform the task selected.

void menu(void)
char ch;

printf("1. Check Spelling\n");

printf(''2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf("Strike Any Other Key to Skip\n");
printf(" Enter your choice: ");

ch = getchar(); /* read the selection from the keyboard */

switch(ch) {
case '1':
check_spelling ();

case '2':
correct_errors ();

case '3':
display_errors ();

default :
printf("No option selected");
int flag, k; /* Assume k is initialized */
•The break inside flag = -1;
the switch is
switch(k) {
optional. case 1: /* These cases have common */
case 2: /* statement sequences. */
•If the break is case 3:
omitted, flag = 0;
execution will break;
case 4:
continue on into
flag = 1;
the next case until case 5:
either a break or error(flag);
the end of the break;
switch is reached. default:
Calculates the range of marks a student has scored
Int calculate_marks (char grade)
{ switch (grade)
{ case `S‟:
printf (“Marks between 91-100”); break;
case `A‟:
printf (“Marks between 81-90”); break;
case `B‟:
printf (“Marks between 71-80”); break;
case `C‟:
printf (“Marks between 61-70”); break;
case `P‟:
printf (“Marks less than 50”); break;
printf (“Invalid grade”); break; }}
Nested Switch
• You can have a switch as a part of the
statement sequence of an outer switch.

• Even if the case constants of the inner and

the outer switch contain common values, no
conflict arise.
switch(x) {
case 1:
switch(y) {
case 0:
printf(''Divide by zero error.\n");
case 1:
process(x, y);
case 2:
• control constructs in C are ___________
and ___________.
• If- else statement is used for
• The case statement values are
• If values do not match any of the cases in
switch-case then the control is transferred to
___________, if present.
Exercise contd….
True / False
• if-then-else is an selective statement of C
• None of the case statements in switch- case
construct can have identical values.
• Case can exist where none of the code in switch-
case is executed.
• break statements should be compulsorily present
in every case.
• break statements can be used in iterative blocks
• break passes the control to the first statement in
the iterative block.
• : Differentiate between "break" and "continue" giving examples.

• Q 2: Find the sum of all odd no's between 1 and 100. Try to use different
looping techniques.

• Q 3: Write a program to count the number of blanks, tabs and newlines in
the input. (switch-case can be used)

• Q 4: Find the greatest of three numbers using the conditional operator.

• Q 5: Write a program to calculate the average of the non-negative
numbers in a list of n numbers.

For,do-while ,while
Lecture 5-6
• Iteration statements (also called loops)
allow a set of instructions to be
repeatedly executed until a certain
condition is reached.
• This condition may be predetermined
(as in the for and while loop) or open
ended (as do-while loops).
for loop
• General form
for (initialization; testing; increment)
Loop Body;
• The initialization is an assignment statement
that is used to set the loop control variable.

• The testing is a relational expression that

determines when the loop exits.

• The increment defines how the loop control

variable changes each time the loop is repeated.
• The for loop continues to execute as long as
the condition is true.

• Once the condition becomes false, program

execution resumes on the statement
following the body of the for loop.
#include <stdio.h>

int main(void)
int x;
for(x=1; x <= 100; x++)
printf("%d ", x);

return 0;

for(x=100; x != 65; x -= 5)
z = x*x;
printf(''The square of %d, %d", x, z);
The Elements of the For-loop
• The initialization, testing and
incrementation can be any valid C

for (x=0; Ajax>Manchester; Ajax=Q*7/i)

• Common use as a counting loop.

for (count=0; count <n; count=count+1)

• Pieces of the loop definition need not be
for(x=0; x != 123; ) scanf("%d", &x);

• The incrementation of the loop control

variable can occur outside the for
for( x=1 ; x < 10; )
printf("%d", x);
The Infinite Loop
• Since none of the three expressions that
form the for loop are required, you can
make an endless loop by leaving the
conditional expression empty.
for( ; ; ) printf("This loop will run forever.\n");

for( ; ; ) {
•Terminate ch = getchar(); /* get a character */
the infinite if(ch == 'A') break; /* exit the loop */
loop printf("you typed an A");
For Loops With No Bodies
• A loop body may be empty.

• This fact is used to simplify the coding of

certain algorithms and to create time delay
• Does what?

for(t=0; t < SOME_VALUE; t++) ;

Declaring Variables within a For
• A variable so declared has its scope
limited to the block of code controlled by
that statement.
/* i is local to for loop; j is known outside loop.*/
int j;

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

j = i * i;

i = 10; /*** Error ***-- i not known here! */

While Loop
• General form:

• Execution:
– Check the test condition at the top of the loop.
– The loop iterates while the condition is true.
– When the condition becomes false, program control
passes to the line of code immediately following the
char wait_for_char(void)
char ch;
ch = '\0'; /* initialize ch */
while(ch != 'A') ch = getchar();
return ch;

while((ch=getchar()) != 'A') ;
Example 2:

void func1()
int working;
working = 1; /* i.e., true */

while (working) {
working = process1();
if (working)
working = process2();
if (working)
working = process3();
For loop Vs While Loop
A-(Assignment), T-(testing), I-(Increment)

for (A; T; I)
While (T)
} Body;
Nested 1 loop syntax coded inside another
Loop syntax.

Why?- Single -Loop? Have a statement or

statements that you
want to repeat. A
repetitive task
that you must solve.

Why? - Nested - Loops? You have a single -

repetitive task - THAT
i.e., a repetition of an
already repetitive task.
General Format:
while (boolean expression){

while (boolean expression) {

You may have any combination of the 3 loop syntax

inside each other. The problem dictates what
combination should be used.
/* Find triples of integers that add up to n. */
#include <stdio.h>

{ int cnt = 0, j , k , m,n;
for(j = 0; j <= N; ++j)
for( k = 0; k <= N; ++k)
for( m = 0: m <= N; ++m)
if ( j + k + m == N) {
printf(“%d%d%d”, j , k , m);
printf(“\n Count: %d\n”, cnt);
How many times will “if” be executed?

512 times j range 0 7

k range 0 7
m range 0 7

8 * 8 * 8 = 512
do-while Loop
• General form:
do {
} while(condition);
• Execution:
– Always executes at least once.
– Iterates until condition becomes false.

do {
scanf(''%d", &num);
} while(num > 100);
•The most common use of the do-while
loop is in a menu selection function.
void menu(void)
char ch;

printf("1. Check Spelling\n");

printf("2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf(" Enter your choice: ");
do {
ch = getchar(); /* read the selection from
the keyboard */
switch(ch) {
case '1':
case '2':
case '3':

} while(ch=='1' || ch=='2' || ch=='3');

• break
• continue
• return (will be introduced in Ch. 4,
break Statement
#include <stdio.h>
Two uses: int main (void)
You can use it to terminate {
a case in the switch int t;

statement. for(t=0; t < 100; t++) {

printf(''%d ", t);
if(t == 10) break;
You can also use it to force
immediate termination of a
loop, bypassing the normal return 0;
loop conditional test. }
0 1 2 3 4 5 6 7 8 9 10
•A break causes an exit from only the
innermost loop.
for(t=0; t < 100; ++t) {
count = 1;
for(;;) {
printf(''%d ", count);
if(count == 10) break;
100 times
Breaking out of loops
• Sometimes loops need to be cut short:
– You can break out of any loop with break ;
– A break will cause the loop to be aborted
– The next statement executed is the statement
following the loop.
• Compare this with return:
– A return will cause a function to be aborted
– Control returns to the calling function.
continue Statement
• General form

• break forces termination of the loop.

• continue forces the next iteration of the

loop to take place, skipping any code in
• continue can expedite the exit from a loop
by forcing the conditional test to be
performed sooner.

– For the for loop, continue causes the

increment and then the conditional test
portions of the loop to execute.

– For the while and do-while loops, program

control passes to the conditional tests.
void code(void) This function codes a
{ message by shifting all
char done, ch; characters you type
one letter higher. For
done = 0;
example, an A
while(!done) { becomes a B. The
ch = getchar(); function will terminate
if(ch == „S') { when you type a S.
done = 1;
continue;} /* test the condition now */

What will be displayed in each of the following :
a) a = 7;
b = a++;
printf ("%d", b);
b) a = 7
b = ++a;
printf ("%d", b);
c) a = 5;
• Exercise Contd……..

d) a = 5;
while(--a) printf("hello");
e) a = 5;
while(a--) printf("hello");
2.Write a program that converts each lower-case
character in the standard input to uppercase and
each uppercase character to lower case. Pass all other
characters unchanged.
3. Write a program that reads nos. from the standard
input and prints the largest
value entered, the smallest value, the sum of all
values read and the mean of all values inputted.
Write a program that prints the number of occurrences of the
character ! in the
standard input.

Q 8: Write a program that tests whether there are the same

number of left brackets, [, as right brackets, ], in the standard

Q 9: Write a program that takes an integer keyed in from the

terminal and extracts and
displays each digit of the integer in English.

Q10: Write a program that converts each lower-case character in

the standard input to
uppercase and each uppercase character to lower case. Pass
all other characters
About Arrays
Lecture 7-9

• What is an "array"?
• A way to collect together data of a single
type in a single object
• A linear sequence of data objects e.g.
– array of ints
– array of chars (string)
Creating and using arrays
• One-dimensional array of three ints:
• int arr[3];
int sum;
arr[0] = 1;
arr[1] = 22;
arr[2] = -35;
sum = arr[0] + arr[1] + arr[2];
One-dimensional arrays (1)

• Arrays can be
– initialized
– partially initialized
– not initialized
• Uninitialized space contains?
– "garbage"
One-dimensional arrays (2)
• Examples:
int my_array[10];
/* not initialized */
int my_array[5] = { 1, 2, 3, 4, 5 };
/* initialized */
int my_array[] = { 1, 2, 3, 4, 5 };
/* OK, initialized */
int my_array[4] = { 1, 2, 3, 4, 5 };
/* warning */
int my_array[10] = { 1, 2, 3, 4, 5 };
/* OK, partially initialized */
One-dimensional arrays (3)

• Note on partial initialization:

int my_array[10] = { 1, 2, 3, 4, 5 };
– rest of array initialized to 0
int my_array[10];
– entire array uninitialized
– contains garbage
One-dimensional arrays (4)

• Explicit initialization of arrays:

int i;
int my_array[10];
for (i = 0; i < 10; i++) {
my_array[i] = 2 * i;
Usually the best approach
One-dimensional arrays (5)

• Some bad things that can happen...

int my_array[10];
/* What happens here? */
printf("%d\n", my_array[0]);
/* What happens here? */
printf("%d\n", my_array[1000]);
• No checking!
Program to generate the first 20 Fibonacci numbers
#include <stdio.h>
int fb[20], i;
fb[0] = 0 ; / * by definition * /
fb[1] = 1 ; / * by definition * /
/* store Fib. numbers in array */
for(i = 2; i < 20; ++i)
fb[i] = fb[i - 1] + fb[i - 2];
/* print the array */
for(i = 0; i < 20; ++i)
printf("%d\n", fb[i]);
# include <stdio.h>
int main (void)
int a [25];
int i, max = a[0]
for (i = 0; I< 25; i++)
{ printf(“Enter the %d number: “, i +1 );
scanf( “%d” , &a[i ]);
for ( i = 1, i <25; i ++ )
if(a [i ] > max )
max = a [ i ];
printf ( “The maximum number in the array is: %d” ,
program to find kth Smallest Element
# include <stdio.h>
int main (void)
{ int u,j,k, temp,no_elements,array [20];
printf (“Enter the number of elements: “);
scanf (“%d”,&no_elements);
printf(“Enter the list of elements:\n “);
for (i=0;I<no_elements;i++)
scanf (“%d”,&array[i]);
for( i=0; i<no_elements; i++)
for( j=0; j<no_elements; j++)
if(array[i] > array [j])
{ temp = array[i]
array [i] = array [j]
array[j] = temp; }
find kth Smallest Element contd…..
/* The nested loop to sort the array. The if loop is used to swap the
element of the array in ascending order. So the Kth smallest
element will be the element */

printf (“Enter the subscript of the element: “);

scanf(“%d”‟ &k);
printf (“\nThe %d a smallest element is %d”, k, array[k-1]);
program to perform Insertion Sort
# include <stdio.h>
int main (void)
{int a [MAX], n, i, k, temp;
printf (“Size of the array : “);
scanf (“%d”, &n);
printf (Elements of the array:\n”);
for (k = 0 ; k < n ; k++)
scanf (“%d”, &a[k]);
for(k = 1 ; k < n ; k++)
{ temp = a[k];
for(I = k-1 ; i >= 0&&temp < a[i] ; i - )
a [i+1] = a [ i ];
a[ i+1 ] = temp;}
Insertion Sort contd….

The loop performs the insertion sort

The elements are inserted at appropriate
places in the ascending order
printf (“The sorted list is :\n”)
for (k = 0 ; k< n ; k++)
printf(“ \n%d”, a[k]);
Two-dimensional arrays (1)
int arr[2][3]; /* NOT arr[2, 3] */
int i, j;
int sum = 0;
arr[0][0] = 1;
arr[0][1] = 23;
arr[0][2] = -12;
arr[1][0] = 85;
arr[1][1] = 46;
arr[1][2] = 99;
/* continued on next slide */
Two-dimensional arrays (2)

for (i = 0; i < 2; i++) {

for (j = 0; j < 3; j++) {
sum += arr[i][j];

printf("sum = %d\n", sum);

Two-dimensional arrays (3)

• Two-dimensional arrays can be split into

component one-dimensional arrays:

int arr[2][3];
/* initialize... */
/* arr[0] is array of 3 ints */
/* arr[1] is another array of 3 ints */
Two-dimensional arrays (4)

• Picture of arr:

1 23 -12 arr[0]

85 46 99 arr[1]
Two-dimensional arrays (5)

• Initializing two-dimensional arrays:

int my_array[2][3];
/* not initialized */
int my_array[2][3]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* OK */
int my_array[2][3]
= { 1, 2, 3, 4, 5, 6 };
/* warning with -Wall */
Two-dimensional arrays (6)

int arr[2][]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* invalid */
int arr[][]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* invalid */
int arr[][3]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* OK */
Two-dimensional arrays (7)
int my_array[][3]
= { 1, 2, 3, 4, 5, 6 };
/* warning with -Wall */
int my_array[][3]
= { { 1, 2, 3 }, { 4, 5 } };
/* OK; missing value = 0 */

• Rule: all but leftmost dimension must be specified

• Compiler can compute leftmost dimension
• OK to specify leftmost dimension as well
Program to add two matrices
# include <studio.h>
int main (void)
{ int sMatrix [3] [3] = {{1,2,3},
int bMatrix{[3][3] = {{4,5,6},
int cMatrix[3][3];
int, j;
for ( i= 0; I < 3; i++ )
for (j = 0; j <3; J++)
cMatrix[i] [j] =aMatrix [i] [j] + bMatrix [i] [j];
add two matrices contd….
printf (“ADDED MATRIX\n”);
for ( i = 0; i < 3; I++ )
for (j = 0; j < 3; j++ )
printf( “%d “, cMatrix [i] [j]);
printf (“/n”);
The output of the program will be
5 7 9
7 7 7
16 16 16
program to find transpose of a matrix
# include <stdio.h>
int main (void)
{ int a [ROWS] [COLS] = { {1,2,3},
int i,j, tmp;
for (i=1;i<n;i++)
{ for (j =0;j<i;j++)
tmp = a[i] [j];
a[i] [j] = a [j] [i];
a[j] [i] = tmp;
transpose of a matrix contd….
for ( i = 0; i < 3; i + + )
for ( j = 0; j < 3; j + + )
printf (“&d “, cMatrix [i] [j] );
printf (“ \n”);
The output of the program will be
1 4 7
2 5 8
3 6 8
Passing arrays to functions (1)
An array name can be passed as an argument to
a function, thus allowing the entire array to
be passed to the function. To pass an array to
a function, the array name must appear by
itself, without brackets or subscripts as an
actual argument within the function call.
void Func(char b[]);
{ char a[10];
........ }
void Func(char b[])
{ .....
Passing arrays to functions (2)
/* To sort an array of integers into ascending order */
void Sort(int a[], int n)
{ int i, j, Temp;
for (i = 0; i < n - 1; ++i)
for(j = i + 1; j < n; ++j)
if(a[i] > a[j])
{ Temp = a[i];
a[i] = a[j];
a[j] = Temp;
Passing arrays to functions
{ int i;
int n[10]={44,-10, 0,16, 7, 2,1, 57, -33,
printf("The array before sort:\n");
for(i = 0; i < 10; ++i) printf("%d",
Sort(n, 10);
printf("The array after the
for(i = 0; i < 10; ++i) printf("%d",
1.void f(int x[], int y);
int a[5], b, i;
for(i = 0; i < 5; i++) a[i] = 2 * i;
b = 15;
f(a, b);
f or(i = 0; i < 5; i++) printf("%d\n", a[i]);
printf("%d", b);
void f(int x[], int y)
int i;
for(i = 0; i < 5; i++) x[i] += 2;
y += 2;
2. Generate prime Numbers between 10-200

3. Finding Kth smallest element.


Write a program to display the reverse a string.

Write a program to concatenate a string to the

end of another string
• The most common array is the string,
which is simply an one-dimensional
array of characters terminated by a
• The End-of-String Sentinel (delimiter)
\0. #define MAXWORD 100
int main(void){

char w[MAXWORD];
w[0] = „A‟;
w[1] = „\0‟;
• When declaring a character array that
will hold a string, you need to declare it
to be one character longer than the
largest string that it will hold.
• WHY?

//to declare an array str that can hold a

//10 characters string

char str[11];
String Initialization
• General form:
char array_name[size] = “string”;

char str[9] = “I like C”;

char str[9] = {'I', ' ', 'l', 'i', 'k', 'e',' ', 'C', '\0'};

char *p = “I like C”;

• The format %s is used for a string.
scanf(“%s”, w); //if w is a string var
printf(“%s”, w);

• „a‟ and “a” are very different.

„a‟ a character constant

“a” a array of characters with
two elements.
String-Handling Functions
• Standard header <string.h>
strcpy(s1, s2) Copies s2 into s1
strcat(s1, s2) Concatenates s2 onto the end
of s1.
strlen(s1) Returns the length of s1
strcmp(s1, s2) Returns 0 if s1 and s2 are the
same; less than 0 if s1<s2;
greater than 0 if s1>s2
strchr(s1, ch) Returns a pointer to
the first occurrence of
ch in s1.
strstr(s1, s2) Returns a pointer to
the first occurrence of
s2 in s1.
#include <stdio.h>
#include <string.h> Hello
int main(void){ Hello
char s1[80], s2[80]; lengths: 5 5
gets(s1); The strings are equal

printf("lengths: %d %d\n", strlen(s1),


if(!strcmp(s1, s2))
printf("The strings are equal\n");
strcat(s1, s2); hellohello
printf (''%s\n", s1); This is a test
e is in hello
found hi
strcpy(s1, "This is a test.\n");

if(strchr("hello", 'e')) printf("e is in hello\n");

if(strstr("hi there", "hi")) printf("found hi");
return 0;
Dynamically Allocated Strings
• The type pointer to char is conceptually a
• An example follows:
/* Allocate space for a string dynamically, request user
input, and then print the string backwards. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
char *s;
int t;
s = malloc(80);
if(!s) {
printf(''Memory request failed.\n");
exit (1);
for(t=strlen(s)-2; t>=0; t--) putchar(s[t]);
free(s); return 0;
Every variable or function in C has 2 attributes:

Type Storage Class

General form:

storage-specifier type var_name

Storage Class : determines how the compiler

allocates memory to that variable.

Auto Extern Register Static

Storage Class of a C object defines its:

1) Spatial Territory- Defines where it can

be referred to in the program. Its Scope
or Visibility.

2) Temporal Authority- Defines when an

object is available. The Extent to which
it exists.
Auto Variables
The storage class auto can only be used in a block:
it cannot be used at the global level.

1) Spatial Limitation(scope): The auto

variable is limited to the block in which it is
defined and its sub-blocks. LOCAL.

2) Temporal Limitation(extent): Are alive only

when the block in which they are defined is
running. Variable does not exist before block
execution, when block terminates it
Impact of Auto
• Auto is the default SC for local vars because it
makes the most efficient use of memory.

• Good programmers use Auto when ever possible

because their lifetime is brief and their scope is
limited to one function.

• They provide an effective way to isolate the

actions of each program unit from the others.
• Most common of the four storage classes.

• Variables declared within function bodies

are auto by default.

• Thus auto is rarely explicitly specified.

auto int a,b,c;
auto float f;
Unintentional interference between
functions is minimized and, making it
much easier to debug large programs.

Constant allocation and deallocation of

auto vars does add some overhead to the
the execution time, but since is done quite
efficiently, the time wasted is minimal
and the advantages of the added modularity
are great.
When a block is entered, the system allocates
memory for the auto variables.
“LOCAL” i.e., Those declared in the

When Block is exited the variables are

released and their values lost.

IF re-enter the
Block? _________

Memory is reallocated.
Call by Reference with Auto
1) When the block is suspended, such as when it
calls another function,the variable is suspended
but can still be accessed and changed(e.g.
actual argument in a func call).

2) It can still be referenced and changed through

a pointer to it. When the block becomes active
again, the variable becomes active i.e., can
directly reference it by name.)
• Primary purpose is to make variables
visible to other compilation units.

• Must be defined in the global area of a

program, that is outside of any block.

• All global variables( i.e., those defined

outside any function) are EXTERN by
Extern Characteristics
• Spatial Limitation(global): It is visible
from its definition to the end of the
program. It can be referred to and
changed by all blocks that come after it as
well as by other programs that are aware of
its existence.

• Temporal Limitation(Immortal): The

whole life of the program. From the time
of its allocation till the end of the program.
extern (cont.)

Variables declared outside of a function have

extern storage class by default.
i.e., even if don‟t use keyword extern.

Extern Var‟s are initialized to 0

Register Storage Class

Variables so declared should be stored in

high speed memory i.e.,
Registers(cpu) provided if is possible
to do so.

Defaults to Auto if register not available

Typically, the compiler has only a few such
registers available.

Many are required for system use & can‟t be

allocated otherwise:

* Base Address of program

* Return Address after program execution ends,
* Instruction register, program counter,
It is an attempt to improve execution speed.
Most frequently accessed variable – loop control
variable or function parameters.

register int i ;
for (i = d, i <LIMIT, ++i){


If storage class is present & Type is absent - get


register i ;
Static Storage Class
A static variable can be defined inside a
block(local) or in the global area of the
program. Its characteristics differ slightly
depending on where it is defined.
Local Static Variables
Static variable is defined inside a block:

1. Spatial Limitation(scope): LOCAL,

undefined outside the block.
2. Temporal Limitation(extent):
Immortal. It lives as if it were a global

What are the consequences of the

immortal extent?
Locally defined Static variables are one of the truly
significant features of the “C” language.

1) Allow a “Local variable” to retain its previous

value when a block is re-entered.
(Not the case with Auto)
2) In other languages, these variables must be
declared globally, which reduces the benefits
of data hiding and isolation.
3) The variable will be automatically initialized to
0 when allocated.
Void f(void)
static int cnt = 0;
++ cnt;
if (cnt % 2 == 0)
. . . . . .
else . . . . .
* 1st Time Function Invoked cnt is set to 0.
* Upon EXIT cnt NOT cleared from memory
* Next invocation ,retains previous value.
Global Static Variables
Global variables-that is, variables defined
outside the scope of all blocks-can be
referred to by other compilation units.

To prevent a global variable from being

exported to the LINKER for reference
by other compilation units, it can be
declared static.
Global Static Characteristics:
1) Spatial Limitation(scope): Global.
Visible from its definition to the end of
the compile unit. Guarantees that the
scope does not extend beyond its
spatial area, i.e., the current
compilation unit.

1) Temporal Limitation(extent) Immortal.

Same as local static, it lives as global
variables live.
Static Extern Variable
Restricted in scope to the “remainder of the file” in which
they are defined. Not known to other files(compilation
void f(void)
…… /* v not available here */
static int v;
void g(void)
…… /* v can be used here */
A Function can be Static: The scope of the function
is limited to this file only(privacy concern). Is
known throughout the entire file.

void f(int a)
…….. /* g() is available here,
} but not in other files */

static int g(void)

Default Initialization
Extern & Static vars are initialized to 0
by the system.

Auto & Register are usually not initialized

by system.

Start will garbage.

Type Qualifiers
• Two type qualifiers: const volatile

• They are used in declarations and must be

coded after the storage class but precede
the type names that they qualify.
static const int k = 3;

• Control how variables may be accessed or

• Variables of type const may not be
changed by your program.

• The compiler is free to place variables of

this type into read-only memory (ROM).
const int a=10;

const int a=7; int *p=&a; //wrong

const int a=7; const int *p=&a; //correct

#include <stdio.h>
void sp_to_dash(const char *str);

int main(void)
sp_to_dash("this is a test");
return 0;

void sp_to_dash(const char *str)

while(*str) {
if(*str== ' ') printf("%c", '-'); if(*str== ' ') *str= '-'; wrong
else printf("%c", *str);
A definition causes a compiler to set aside
memory at compile time (every variable
definition is a declaration) - not always the

e.g. when you introduce a variable outside of

any function definition (global variable),
you both declare and define the variable,
because you have:
a) informed the compiler about the
variable‟s type.
b) caused the compiler to set aside memory
for the variable at compile time.
When you introduce a variable inside a function
definition(local), you only declare that
variable, because the compiler does not set aside
memory for such variable at compile time
[memory in stack frame].

Functions are both declared & defined

Because: a) must specify return type.

b) compiler sets aside memory for

functions at compile time.
Q 1: Differentiate between external and local static variables.

Q 2: Explain the utility and requirement of declaring a variable as


Q 3: What is the output of each of the following :

a) #include <stdio.h>
int i = 3;
int i = 5;
printf("%d\n", i);
printf("%d\n", i);
Functions and Structured

Lecture 10-13
Structured Programming
• Structured programming is a problem-solving
strategy and a programming methodology.
– The construction of a program should embody top-
down design of the overall problem into finite

• Each subtask can be coded directly as

a function.

• These functions can be used in main

to solve the overall problem.
• Functions are the building blocks of C
and the place where all program activity
occurs. Function topics include:

– Function types
– Function variables
– Function arguments
– Function scopes
– Return values
– Function prototypes
– Recursion
General syntax:

ret-type function-name (parameter list)

body of the function
return (expression)

• A function may return any type of data except an

• The parameters receive the values of the
arguments when the function is called.
VOID used to indicate:
A. - No Return Value.
B. - No Parameters or Arguments.

* This allows Type compatibility to be

handled by the compiler.

void Fname (void)

Not Return No Received
a Value. Values.
• A variable is a named location in
memory that is used to hold a value that
can be modified by the program.

• All variables must be declared before

they can be used.
• Where variables are declared:

– Inside functions:
local variables

– Outside of all functions:

global variables

– In the definition of function parameters:

formal parameters
Local variable
void func1(void)
• Declared inside a function. {
• Can be used only by statements int x;
x = 10;
that are inside the block in }
which the variables are declared.
• A local variable is created upon void func2(void)
entry into its block and destroyed int x;
upon exit. x = -199;
void f(void)
int t;
scanf("%d", &t);

if(t==l) {
char s[80]; /* this is created only upon
entry into this block */
/* do something . . . */

/* s not known here */

#include <stdio.h>
int main(void)
Local variables {
int x;
are stored on the x = 10;
run-time stack.
if(x == 10) {
int x; /* this masks the outer x */
x = 99;
printf("Inner x: %d\n", x); 99

printf("Outer x: %d\n", x); 10

return 0;
#include <stdio.h>
void f(void);
int main(void)
• The value will be {
int i;
assigned to the for(i=0; i<10; i++) f();
variable each time return 0;
the block of code
in which it is void f(void)
declared is entered. {
int j = 10;
printf("%d ", j);
j++; /* this line has no lasting effect */
Global Variables
• They are known throughout the program
in which they are defined.

• They will hold their value throughout the

program execution.

• They are declared outside of any function

• Storage for global variables is in a fixed

region and not the run-time stack.
#include <stdio.h> void func1(void)
int count; /* GLOBAL */ int temp;
temp = count;
void func1(void); func2();
void func2(void); printf("count is %d", count);
int main(void)
{ void func2(void)
count = 100; {
func1(); int count; /* LOCAL */
printf("count is %d", count); for(count=l; count<10; count++)
return 0; putchar('.');
} printf("count is %d", count);
• Avoid using unnecessary global

– They take up memory the entire time your

program is executing.

– Using a global variable where a local variable

will do makes a function less general.

– Using a large number of global variables can

lead to program errors.
Function Parameters
• General form:

fun-name(type varname1, type varname2,…. )

• All function parameters must be declared

individually, each including both the type and
void f(int i, int k, int j) /* correct */
void f(int i, k, float j) /* wrong */

• Parameters behave like any other local

The Scope of a Function
• Each function is a discrete block of code.

• A function's code is private to that function

and cannot be accessed by any statement in
any other function except through a call to
that function.
• Variables that are defined within a
function are local variables. Such
variables are freed from memory when
their function completes execution.

• Therefore, a local variable cannot hold its

value between function calls.

• A global variable has extern storage class.

We will see the impact of this later.
• The formal parameters to a function also
fall within the function's scope.

– A parameter is known throughout the entire


– A parameter comes into existence when the

function is called and is destroyed when the
function is exited,( I.e., the Extent of the
• A function cannot be defined within a
function(no nested-functions).
Communication with a
• Two ways that arguments can be passed to
a function.

– Call by Value.

– Call by Reference.
Call by Value
* When an Argument (variable, constant, or
expression) is passed to a matching parameter
(declared in Function Heading), A Copy of the
Argument is made and is passed to the
Arguments Parameters
in calling in called
Module. Module.
* Changes made to the parameter have no effect on
the argument. i.e., the parameter is implemented
as a local variable which is initialized to the value
passed from the Argument.
Call by Reference
• It is often convenient to have functions modify
the values of the variables referred to in the
Argument list.

• The address of an argument is copied into the

• Inside the subroutine, the address is used to
access the actual argument used in the call.

To effect call-by-reference we must use pointers in

the Argument list & pass addresses of variables
[see chap 8].
#include <stdio.h>
int sqr(int x);

int main(void)
int t=10;
printf("%d %d", sqr(t), t);
return 0;

int sqr(int t)
t = t*t;
return t;
Placement of Functions:
Before the compiler sees a call to a function
it wants to know the Number and Type of
its Parameters and the type of the Return
Value of the Function.

Two methods of doing so:

1. Place Function Before main function

2. Provide Function Prototype Before the call.
#include <stdio.h>

void f(int a, int b)

printf(''%d ", a%b); Before Main

int main (void)

return 0;
Function Prototypes
In C - A Function call can appear Before the
function is Defined (i.e., code of function):

* The called function can be defined later in

the same file.

* The called function can be in another file.

IF the Function Prototype is provided Before

the call.
Func Prototype is “Heading” of function.

FP‟s - Can be placed at the top of the File -

typically above any Function Definitions
But below :

This gives the FP‟s File Visibility. Know

throughout the file.
Parameter Passing
Call by Value
#include <stdio.h>
double average(int, int, int);

int main(void) {
int test1, test2, test3;
double avg;
scanf(“%d%d%d%d”, &test1, &test2, &test3);
avg = average(test1, test2, test3);
printf(“ The average is: %f”‟, avg);
/* This function returns the average of 3 exam
scores which are passed call-by-value. */

double average(int exam1, int exam2, int exam3)

{ double testavg;

testavg = (exam1 + exam2 + exam3)/ 3;

return testavg;
Returning from a Function
• A function terminates execution and returns
to the caller in two ways.

– Occurs when the last statement in the function

has executed.

– Occurs when meet the return statement.

• General form:
return expression;

• It causes an immediate exit from the

– Returns program control to calling
– Allows Returning of a value.

• The value of expression will become the

return value of the function.
• You can use as many return statements as
you like within a function. However, the
function will stop executing as soon as it
encounters the first return.
/* Return 1 if c is part of string s; 0 otherwise. */

int is_in(char *s, char c)

while (*s)
if(*s==c) return 1;
else s++;
return 0;
• The } that ends a function also causes the
function to return. It is the same as a
return without any specified value. If this
occurs within a non-void function, then the
return value of the function is undefined.

• A function declared as void cannot

contain a return statement that specifies
a value.
• As long as a function is not declared as
void, it can be used as an operand in an

x = power(y);

if(max(x,y) > 100) printf(''greater");

for(ch=getchar(); isdigit(ch); ) . . . ;
The exit( ) Function
• General form
void exit(int return_code);

• This function causes immediate termination of

the entire program, forcing a return to the
operating system.

• The value of return_code is returned to the

calling process, which is usually the operating
•Programmers frequently use exit when a
mandatory condition for program execution
is not satisfied.

#include <stdlib.h>

int main(void)
if(!virtual_graphics()) exit(1);
Fill in the blanks
• The region where a variable name can be used is called the
_______ of the variable.
• The variables declared inside a function or blocks have
______ scope.
• The three kinds of score are ____, _______ and ________.
• ________ and _______ variables have block scope by
• Auto variable cannot be _______ variables.
• Functions have _________ scope.
• Functions have _______ scope.
• Labels have _____ scope.
• Variable declared outside a block have _______ scope.
• Function declaration should be done ______ a function
Exercise Contd…. (true/false)
• Function scope can be told as a form of block scope.
• Allocated memory in a block is automatically released
before the block ends.
• Variables with the same name in different block use the
same memory locations.
• Block variables can be global variables also.
• File scope variables can be accessed by all functions in the
• File scope variables can be local variables also.
• It is possible to jump out of functions using labels.
• Using global variables allows sharing of data between
• Using global variables increased the structural organization
of a program.
• It is must to declare functions before they are used.
Exercise contd…..

• Functions cannot be considered as a source for

reusability of code.
• Function prototype and function definition
should match in the function name, the return
value, the number and type of parameters.
• Arguments are mandatory in any function.
• The arguments passed to a function are mapped
to the function prototype.
• A function can take no arguments also.
• Functions can take no arguments also.
• Parameters are values passed to a function and
arguments are the variable that received the
Q 1: Write a function int power(int x, int n) to return xn.

Q 2: Write a function int sum(int x, int n) which returns

the sum of the following series:
2x + 4x + 6x + _ _ _ _ _ _ _ _ _ n terms
Q 3: Write a function to return the factorial of a number.

Q 4: Write a function, int sum(int x, int n) to return the sum

of the following series :
2 3
x x
x + ____ + ______ + _ _ _ _ _ _ n terms
2! 3!
Q 5: Write a function int isPrime(int n) that returns 1 if its
argument is a prime number, else returns 0.
Q 6: Write a function int arrSum(int arr[], int num) that takes two arguments: an
integer array and the number of elements in the array. Hence the function
returns as its result, the sum of the elements in the array.

Q 7: What is the output :

void f(int x[], int y);
int a[5], b, i;
for(i = 0; i < 5; i++) a[i] = 2 * i;
b = 15;
f(a, b);
for(i = 0; i < 5; i++) printf("%d\n", a[i]);
printf("%d", b);
void f(int x[], int y)
int i;
for(i = 0; i < 5; i++) x[i] += 2;
y += 2;
Recursion is the ability of a C function to
call itself. Recursion is capable of defining
an object in terms of a simpler case of
itself.” Recursion is a function, which
keeps on calling itself. So, when will the
function stop? There should be if condition
upon which recursion stops.
• A function calls itself (circular definition).
/* non-recursive */ /* recursive */
int fact(int n) { int factr(int n) {
int t, answer; int answer;

answer = 1; if(n==l) return 1;

for(t=1; t<=n; t++) /* recursive call */
answer=answer*t; answer = factr(n-l)*n;
return answer; return answer ;
} }
Factorial of a number using recursion
#include <stdio.h>
int factorial (int n)
{if (n= = 0);
return 1;
return (n* factorial (n-1));}
int main (void)
{ int n;
printf ( <<Enter the number: <<);
scanf (<<The factorial of %d is %d>>, n,
factorial (n));
Recursion exercise
Fill in the Blanks

• _________ is the ability of a C program to call itself.

• Recursive code works _____ than iterative code.
• The point at which the program stops recursion is called
• ______ is an elegant way of solving towers of Hanoi.
• Disks of ______ dimensions are present in the towers
• Recursive code necessarily needs a _______.
• Quick sort algorithm terminates when ______.
• Quick sort was developed by ________.
• Quick sort divides the array into _____ using ______.
Q 1: What is the advantage of using a Recursive Technique ?

Q 2: What will be the output of the following :

#include <stdio.h>

Q 3: Write a recursive function, int sum(int n), that returns:

2 + 4 + 6 + _ _ _ _ + 2n

Q 4: Write a recursive function to print the binary equivalent of an

Why Pointers
• They provide the means by which
functions can modify arguments in the
calling function.

• They support dynamic memory


• They provide support for dynamic data

structures, such as binary trees and linked
What Are Pointers
• A pointer is the memory address of an

• A pointer variable is a variable that is

specifically declared to hold a pointer to an
object of its specified type.

• This address is the location of another

object (typically another variable) in
Memory Variable in
address memory
1000 1003
Pointer Declaration
• General syntax:
type *name;

int *m; //The variable m can hold a

//pointer to type int.
char *ch;

int count, *y, q;

Two Pointer Operators
Address Operator: &

Dereference Operator: *

Both & and * have a higher precedence

than all other arithmetic operators except
the unary minus, with which they share
equal precedence.
& Operator
• The & is a unary operator that returns the
memory address of its operand.
& “the address of”

m = &count;
m receives the address of count.
m count
* Operator
* is the complement of &. It is a unary
operator that returns the value located at
the address that follows.
* “at address”

q = *m;
q receives the value at address m. ?
#include <stdio.h>
int main(void)
Put the int target, source=10;
value 10 int *m;
into a m = &source;
variable target = *m;
called target. printf("%d", target);

return 0;
Pointer Assignments
• You can use a pointer variable on the
right-hand side of an assignment statement
to assign its value to another pointer.

• When both pointers are the same type, the

situation is straightforward.
#include <stdio.h>
int main(void)
int x = 99;
int *p1, *p2;
p1 = &x;
p2 = p1;
printf("%p %p", p1, p2);
printf(''%d %d\n", *p1, *p2);
return 0;
Illustrates Distinction between a pointer var value &
a Dereferenced var.

main( )
{ int i = 777, *p = &i;
printf (“value of i:%d\n”, *p);
printf (“Addr of i:%u or %p\n”, p, p);
Output Value of i: 777
Address of i: 234880259 or dfffcfc

u - (unsigned Dec integer)

p - (whatever way is Default for system) - Here is Hex.
Example 1
int i = 1, *j, *k;
Assume addresses of i, j, k are respectively Byte addresses
10, 20, 30

1 ? ?
i:10 j:20 k:30

1. j = &i;

int var Pointer var Pointer var

1 10 ?
i:10 j:20 k:30
2. *j = 2;

1 2 10 ?
i:10 j:20 k:30
Stores 2 at the memory location pointed to by j.

3. i = *j + 1;

12 3 10 ?
i:10 j:20 k:30

* has higher precedence than +. Assigns to i the

contents of the location pointed to by j,
incremented by 1.
4. k = &i;

3 10 10
i:10 j:20 k:30

5. printf (“%d”, *k);

output: 3
Example 2
int a=42, b=53, *p1, *p2;
p1 = &a;

p2 = p1;

p2 = &b;

p1? p2? *p1? *p2?

int a=42, b=53, *p1, *p2;
p1 ? 42
? 53 p2 = p1;
p1 42
p1 = &a; p2 53
p1 42
p2 ? 53 p2 = &b;
p1 42
p2 53
Example 3
int *p1, v1;
v1 = 0;
p1 = &v1;
*p1 = 42; int a=8, b=9;
int *p1, *p2;
v1? p1? *p1? p1 = &a;
p2 = &b;
p1 = p2; vs. *p1 = *p2;
p1 = p2;
before after
p1 8 p1 8

p2 9 p2 9
*p1 = *p2;
before after
p1 8 p1 9

p2 9 p2 9
Example 4
# include <stdio.h>
main( )
int j, i, *intptr;
scanf(“%d%d”, &i, &,j);
intptr = i > j ? &i:&j;
printf(“%d\n”, *intptr);
Address of the larger var is stored in ? :
then the larger number is output.
Example 5
int a=3,b=7,*p; p = &b;

3 7
a b p


printf (“b= %d\n”, b);

“The object pointed to by p (i.e., b) is assigned the

value of 2**p–a.”

1) 2 * *p 2*7
2) 14 – 3 11
3) Which is assigned? b
Pointer Initialization
int i, *p = &i; correct

int *p = &i, i; sequence wrong.

The variable must be defined before

the address can be assigned.
p = &i; p “points to” i

p = 0; “Null” is usually defined as


p = NULL; Pointer constant points


p = (int *) 1307;
cast to pointer to int.
1307 is an absolute address in
int i = 3, j = 5, *p = &i, *q = &j, *r;
double x;
3 5 ?
i:10 j
p:50 q ? x

1) p = i + 7; ILLEGAL The only integer value

that can be assigned to a
pointer variable directly
is the special value
0 (NULL).

To assign any other value requires a cast (int *) (i + 7)

2) **&p
All are unary operators. 1 &p - The
address of p (50).

*&p - “The Addr

3 10 stored at p” (10)

i:10 p:5

3 **&p – The contents of

the address (*&p)

“The contents of the variable pointed

to by p”
3) r = &x; Illegal
x is a double variable
r is pointer to int.

4) 7 * *p / *q + 7 i:10 j
3 5
Dereference Right to Left p q
1. *q 5
2. *p 3
3. 7 * 3 [21]
4. 21/5 4
5 4 + 7 11
5) *(r = &j) *= *p
4 2 1 5 3 j - int var
p - pointer to int
j i r - pointer to int
5 3
r p

1. &j - Address of j 1
2. r = 1 r points to j
3. *p contents of thing
pointed to by p i.e., 3
4. *( ) Location pointed to by r, i.e., j.

5. *= *r *= *p; *r = *r * *p;
Pointer Arithmetic
int *v=(int *)100; Byte Address.

100 v
102 v+1
104 v+2
106 v+3
108 v+4

assume int
are 2 bytes long.
Pointer Arithmetic (cont.)

char *ch=(char *)3000;

int *i=(int *)3000;
ch 3000 i
ch+1 3001
ch+2 3002 i+1
ch+3 3003
ch+4 3004 i+2
ch+5 3005
Pointer Arithmetic (cont.)
• Only two operations are allowed.
– Addition and subtraction.
e.g. p++; p--; p1=p1+12;

• Cannot multiply or divide pointers.

• Cannot add two pointers.
• Cannot add or subtract type float or
double to or from pointers.
Call by Reference
• Passing a ADDRESS of the argument to a
formal parameter which is a POINTER of
the same type as the argument.

• Code within the function can change the

value of the argument passed to the
1) Declare a function parameter to be a

2) Pass an address as an argument when the

function is called.

3) Use the dereferenced pointer in the

function body to reference the argument
in the calling function.
#include <stdio.h>
void swap(int *x, int *y);

int main (void)

int i=10, j=20;

printf("i and j before swapping: %d %d\n", i, j);

swap(&i, &j); /* pass the addresses of i and j */

printf("i and j after swapping: %d %d\n", i, j);

return 0;
void swap(int *x, int *y)

int temp;

temp=*x; /* save the value at address x */

*x =*y; /* put y into x */
*y=temp; /* put x into y */
Fill in the blanks
• _________gives C the power to deal with machine
• _______ gets the value stored by location pointed by a
• If int *ptr = &temp;, then ptr = ____________.
• NULL is defined in _________.
• Address of different data types assigned to pointers of
different data types give rise to ________ errors.
• If int a = 0, b = 1;
int *pl = &a, *ps = &b;
*p1 = p1+p2;
*p = ________(taking &a = 1000 and &b =20).
7. float a =1.5, *ptr = &a;
ptr = (int) (ptr + a);
thus p = _______ (taking &p = 100).
Exercise Contd……
True / False
1. Pointers hold address of memory locations.
2. „&‟ is called the indirection operator.
3. p = * (&p)
4. p = &(*p)
5. Addition of pointers is illegal.
6. We can apply bit operations on pointers.
7. NULL points to nothing.
8. (ptr1-ptr2) = (ptr1+ptr2)/size of object pointed by
ptr1. (given ptr1 and ptr2 point to elements of the
same array.
9. Pointers of the same type can be compared.
10. Pointers cannot be compared for equality at any time.
Exercise Contd……
Q: Write a function, Fact(int i, int *j), to find the
factorial of an integer, i, and store it in *j.

Q : Write a function int LetterCnt(char *p) which

returns count of all alphabets in a character string.

Q: Write a function using pointers to copy a string to

another string.

Q : Write a function using pointers that appends one

string to another.
Derived Data Type
• C gives you several ways to create a
custom data type.

– The structure, which is a grouping of

variables under one name and is called an
aggregate data type.

– The “typedef” keyword, allow us to define a

new user-defined type.
• A structure is a collection of variables
referenced under one name, providing a
convenient means of keeping related
information together.

• It allows us to organize related data of

different types in one structure.
Structure Declaration
• A structure declaration forms a template that
can be used to create structure objects (instances
of a structure).

• The variables that make up the structure are called


• Usually, the members of a structure are

logically related.
General Form
struct tag {
type member-name;
type member-name;
type member-name;
} structure-variable(s);
keyword structure tag name
struct addr
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
}; Terminated by a semicolon
No variable has actually been created.
Structure Variable Declaration
struct addr addr_info;

declares a variable of type struct addr called


The compiler automatically allocates

sufficient memory to accommodate all of
its members.
Memory allocated for addr_info

Name 30 bytes
Street 40 bytes
City 20 bytes
State 3 bytes
Zip 4 bytes
Assume 4-byte long integers
You can declare one or more
objects when declare a struct type

struct addr {
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
} addr_info, binfo, cinfo;
Initialization of Structures

All, Extern and Static Variables including

structure variables that are not explicitly

initialized, are automatically initialized to

Accessing Structure Members
• Individual members of a structure are
accessed through the use of the Dot
Operator (“.”).

• General form:

e.g., = 12345;


for(t=0;[t]; ++t)

putchar([t] );
Structure Assignments
#include <stdio.h>
int main(void)
struct {
int a;
int b; Do not need to assign
} x, y; the value of each
member separately
x.a = 10;
y = x; /* assign one structure to another */

printf("%d", y.a);

return 0;
Array of Structures

What does an array of structures allow us to do

that is not possible with any other single
Arrays of Structures
• To declare an array of structures, you must
first define a structure and then declare
an array variable of that type.

struct addr addr_list[100];

printf("%lu", addr_list[2].zip);

addr_list[2].name[0] = 'X';
Passing Structures to Functions

• Passing Structure Members to Functions.

• Passing Entire Structures to Functions

Passing Structure Members to Functions
• When you pass a member of a structure to
a function, you are passing the value of
that member to the function. It is
irrelevant that the value is obtained from a
member of a structure.
struct friend
{ char x;
int y;
float z;
char s[10];
} mike;
func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */

func(&mike.x); /* passes address of character x */

func2(&mike.y); /* passes address of integer y */
func3(&mike.z); /* passes address of float z */
func4(mike.s); /* passes address of string s */
func(&mike.s[2]);/* passes address of character s[2]
Passing Entire Structures to
• Call-by-value:

#include <stdio.h>

struct Example_type {
int a, b;
char ch;
void f1(struct Example_type parm);

int main(void)
struct Example_type arg;

arg.a = 1000;
return 0; struct_type
} must match
void f1(struct Example_type parm)
printf(''%d", parm.a);
In Header File: cl_info.h

#define CLASS_SIZE 100

struct student {
char *last_name;
int student_id;
char grade;
e.g.: To count the
In Program File : number of failing
#include “cl_info.h” students in a given
MAIN( ) Class.
struct student temp, class [CLASS_SIZE];
Structure Pointers
• When a pointer to a structure is passed to a
function, only the address of the
structure is pushed on the stack. This
makes for very fast function calls.

• Passing a pointer makes it possible for the

function to modify the contents of the
structure used as the argument via call-by-
Declaring a Structure Pointer
• Like other pointers, structure pointers are
declared by placing * in front of a
structure variable's name.

struct addr *addr_pointer;

Using Structure Pointers
• To pass a structure to a function using call
by reference.

• To create linked lists and other dynamic

data structures that rely on dynamic
struct bal {
float balance;
char name[80];
} person;

struct bal *p; /* declare a structure pointer */

p = &person;
The Structure Pointer Operator
Used to access the members of a structure via a

(*pointer-To-Struct). member
pointer-To-Struct member
struct student temp, *p = &temp;

temp.grade = „A‟;
temp.last_name = “Bushker”;
temp.student_id = 590017;

struct student {
char *last_name;
int student_id;
char grade;
Expression Equivalent Value

temp.grade p –> grade A

temp.last_name p –> last_name Bushker
temp.student_id p –> student_id 590017

(*p).student_id 590017
Parenthesis are necessary
(dot) has higher priority than *
Arrays and Structures Within

• A member of a structure can be either a

single variable or an aggregate type. In C

aggregate types are arrays and structures.

Arrays Within Structures
struct x {
int a[10] [10]; /* 10 x 10 array of ints */
float b;
} y;

To reference element [ 3,7] in member a of

Structure y.

Structures within Structures
struct emp {
struct addr address; /* nested structure */
float wage;
} worker; = 93456;
Using sizeof to Ensure Portability
Type Size in Bytes struct s {
char 1 char ch;
int 4 int i;
double 8 double f;
} s_var;
sizeof(s_var) is 13 (8+4+1).

struct s *p;
p = malloc(sizeof(struct s));
• You can define new data type names by using
the keyword typedef

– You are not actually creating a new data type.

– You define a new name for an existing type.

• The primary advantage of the type definition is

that it allows you to replace a complex name,
such as a pointer declaration, with a mnemonic
that makes the program easier to read and follow.
• General Form:

typedef type newname;

typedef float BALANCE;

BALANCE over_due;
E.g., The declaration for an array of
pointers to strings.

Char * stringPtrAry[20];

Typedef char * STRING;

STRING StrPtrAry[20];
Typedef with Structures
typedef struct
{ char id[10];
char name[26];
int gradepts;
} STUDENT; A typename not
a variable.

STUDENT pupil;

void printstudent (STUDENT Stu);

Q 1: How does an array differ from structure ?

Q 2: What is a structure tag and what is its purpose ?

Q 3: Define a structure which stores the name of a

student, his roll number, and marks in three subjects.
There are 10 students. Write a program to print roll
number and name of student who gets the maximum
and the one who gets the minimum marks. Also
display the Average marks of each student.

Q 4: Write a function to swap two dates using a

structure. Use this function to swap an array of dates.
File handling

File accessing Function

Classes of Files
There are two broad classes of files:
Text Files: All the data are stored as
characters which must be converted to
internal formats when entered into
memory. Text files are organized around
lines which end with a new line(“|n”).

Binary Files: Store data in internal

computer formats, such as integer and
floating-pt numbers. Take less time to I/O
because no format conversion is necessary.
• Files are stored on auxiliary or secondary
storage devices. Two most common are
disk and tape.
• A buffer is a temporary storage area which
holds data while they are being transferred
to or from memory. Its primary purpose
is to synchronize the physical devices to
your program needs(e.g., more data can
be input at one time then your program can
use. The buffer holds extra data until you
are ready for it).
• These buffering activities are taken care of
by software know as device drivers or
access methods, which are provided by the
supplier of the Operating System you are
Files and Streams
• The computer looks at input and output data,
whether from a physical device such as a
keyboard, or from secondary files, as a stream of
characters or bytes.

• Since files exist separately from our program and

computer, we must have some way to connect
them: we must create a linkage between the
external file and its usage in our program. In
C, this linkage is know as a file table.
• The term file table implies that several things are
stored. It contains ALL the info needed to
locate your file wherever it is stored outside of
the computer. It also contains info such as the
file name, the location of its file buffer, and the
current state of the file.

• We define a file table with the standard FILE

type. There will be a file table for each file that
our program will access.
File System Basics
• The header <stdio.h> contains:

– Three file pointers(stdin, stdout, stderr).

– Several interrelated functions.

– Each stream that is associated with a file has a

file control structure of type FILE.
The file pointers(stdin, stdout, stderr-
i.e., Tables) are automatically opened
when the program starts.

File tables are created that POINT to these

file streams.
Three File Pointers
stdin Standard input Connected
file to the
Stdout Standard output Connected
file to the
stderr Standard error file Connected
to the
fopen( ) Opens a file Commonly
fclose( ) Closes a file
putc( ) Writes a char. to a file used C file-
fputc( ) Same as putc( ) system
getc( ) Reads a character from a file
fgetc( ) Same as getc( ) functions
fgets( ) Reads a string from a file
fputs( ) Writes a string to a file
fseek( ) Seeks to a specified byte in a file
ftell( ) Returns the current file position
fprintf( ) Is to a file what printf( ) is to the console
fscanf( ) Is to a file what scanf( ) is to the console
feof( ) Returns true if end-of-file is reached
rewind( ) Resets the file position indicator to the begin of the file
remove( ) Erases a file
Fflush() Flushes a file
The File Pointer
• In order to read or write files, your program
needs to use file pointers.
• A file pointer is a pointer to a structure of
type FILE.
• It points to information that defines various
things about the file, including its name,
status, and the current position of the file.
FILE *fp;
Opening a File
• The fopen( ) function opens a stream for
use and links a file with that stream.
Then it returns the file pointer associated
with that file.

• General form:

FILE *fopen(const char *filename,

const char *mode);
• filename is a pointer to a string of
characters that make up a valid filename
and may include a path specification.

• mode determines how the file will be


• fopen( ) function returns a file pointer

which should not be altered by your code.

• If an error occurs when it is trying to open

the file, fopen( ) returns a null pointer.
Mode Meaning Legal
r Open a text file for reading values for
w Create a text file for writing Mode
a Append to a text filer
b Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary filer
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or create a text file for read/write
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append or create a binary file for read/write
FILE *fp;
if ((fp = fopen("test","w"))==NULL) {
printf(''Cannot open file.\n");
• The number of files that may be open at any one
time is specified by FOPEN_MAX. This value
will be at least 8.

• If, when opening a file for read-only operations,
the file does not exist ,fopen ( ) will fail.

• When opening a file using append mode, if the
file does not exist, it will be created.
When a file is opened for append:
- All new data written to the file will be
added to the end of the file.
- The original contents will remain
When a file is opened for writing:
- If the file does not exist, it will be
- If it does exist, the contents of the
original file will be destroyed, and a
new file will be created.
• The difference between r+ and w+ is :

- r+ will not create a file if it does not exist;

however, w+ will.

- If the file already exists, opening it with w+

destroys its contents; opening it with r+ does
Closing a File
• General form:

int fclose(FILE *fp);

Returns zero for a successful close.

Returns EOF if an error occurs.

Generally, fclose( ) will fail only when a disk has

been prematurely removed from the drive or
the designated file pointer is incorrect.
• fclose( ) closes a stream that was opened
by a call to fopen( ).

• It writes any data still remaining in the

disk buffer to the file and does a formal
operating-system-level close on the file.
• Failure to close a stream invites all kinds
of trouble, including :lost data, destroyed
files, and possible intermittent errors in
your program.

• It also frees the file control block

associated with the stream, making it
available for reuse.
Writing a Character
To a File
• putc( ) and fputc( )

• General form:

int putc(int ch, FILE *fp);

Returns the character written if successful.

Otherwise, returns EOF.
Reading a Character
• getc( ) and fgetc( )
• General form:
int getc(FILE *fp);
Returns EOF when the end of the file has
been reached.

do {
ch = getc(fp);

} while(ch!=EOF);
/* KTOD: A key to disk program. */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
FILE *fp; Reads characters from the
char ch; keyboard and writes them to a
disk file until the user types a
if(argc!=2) { dollar sign.
printf(''You forgot to enter the filename.\n");
if((fp=fopen(argv[1], "w"))==NULL) {
printf(''Cannot open file.\n");
exit (1);

do {
ch = getchar();
putc(ch, fp);
} while (ch != '$');

return 0;
feof( )
• General form:
int feof(FILE *fp);

Returns true if the end of the file has been

reached; otherwise, returns zero.

while(!feof(fp)) ch = getc(fp);
Working with Strings
• fputs( )

• General form:

int fputs(const char *str, FILE *fp);

Returns EOF if an error occurs.

• fgets( )

• General form:

char *fgets(char *str, int length, FILE *fp);

It reads a string from the specified stream

until either a newline character is read or
length–1 characters have been read.
If a newline is read, it will be part of the
string (unlike the gets( ) function).

It returns str if successful and a null

pointer if an error occurs.
rewind( )
General Format:
void rewind(FILE *fp);

Although it is most commonly used with tape

files, it can be used with disk as well. It
simply sets the file position indicator to the
beginning of the file.
• A common use of REWIND is to change a
work file from a write state to a read state.

• Often it is necessary to place data in a file

temporarily for later processing.

• When all the data have been written and

you are ready to begin reading, you rewind
the file and simply start reading.

• You must open the file in read/write

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
char str[80];
FILE *fp;

if((fp = fopen("TEST", "w+"))==NULL) {

printf("Cannot open file.\n");
do {
printf("Enter a string (CR to quit):\n");
strcat(str, "\n"); /* add a newline */
fputs(str, fp);
} while(*str!='\n');

/* now, read and display the file */

rewind(fp); /* reset to start of file */
while(!feof(fp)) {
fgets(str, 79, fp);
} return 0;
Erasing Files

• General form:

int remove(const char *filename);

It returns zero if successful. Otherwise, it

returns a nonzero value.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> Double check
before erasing
int main(int argc, char *argv[]){
char str[80]; .
if(argc!=2) {
printf(''usage: erase <filename>\n");
printf("Erase %s? (Y/N): ", argv[1]);


if(toupper(*str)= ='Y')
if(remove(argv[1])) {
printf("Cannot erase file.\n");

return 0;

}/* END MAIN */

fprintf( ) and fscanf( )
• General form:

int fprintf(FILE *fp, const char *control_string, . .);

int fscanf(FILE *fp, const char *control_string, . ..);

fprintf(stdout, …); printf(…);

fscanf(stdin, …); scanf(…);
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
FILE *fp;
char s[80];
int t;

if((fp=fopen("test", "w")) == NULL)

printf(''Cannot open file.\n");
printf("Enter a string and a number: ");
fscanf(stdin, "%s%d", s, &t); /* read from keyboard */
fprintf(fp, "%s %d", s, t); /* write to file */

if((fp=fopen("test","r")) == NULL) {
printf("Cannot open file.\n");

fscanf(fp, "%s%d", s, &t); /* read from file */

fprintf(stdout, "%s %d", s, t); /* print on screen */

return 0;
Suppose that the file data.dat is
What is printed ?
#include <stidio.h>
char 1;
FILE *fp;
fp = fopen (“data.dat”, “rb”);
1 = getc (fp);
printf(“%c\n”, 1)
fseek (fp, OL, 2);
if (( 1 = getc(f[)) = = EOF)
printf(„ EOF \n);
pintf(“%c\n”, 1);
fseek(fp, -5L, 2);
1 = getc (fp);
printf(“%c”, 1);
• A Linked List is an ordered collection of data in
which each element contains 2 parts: data and

• The data part holds info fields and the link is

used to chain the data together. It contains a
pointer that identifies the in next node the list.

• A Pointer variable points to the first node

(HEAD) in the list.

• Memory for each node is allocated

Head Data Data Data Data

The Head ptr gives acess to the LINKED LIST which is

a sequence of linked nodes.
Self-Referential Structures
• The node in a linked list are called self-
referential structures: Each instance of the
structure contains a pointer member to
another instance of the same type.

• This gives us the ability to create our

linked list structure in which one instance
of a node structure points to another
instance of the node structure.
Type Definition for a Linked List
typedef int KEY_TYPE;

typedef struct
{ KEY_TYPE key;
… /* other data fields */

typedef struct nodetag

{ DATA data;
struct nodetag *link;
Pointers to Linked Lists
• One of the attributes of a linked list is that its data
are NOT stored with physical adjaceny- like
array data is.

• We need to identify the first logical node in the

list which we do with a pointer variable
designated as the HEAD POINTER.

• A linked list MUST always have a head ptr and

will likely have other pointers which will be
used for implementing LL activities (e.g.,
insertions, deletions, searches …).
Primitive List Functions
• To work with a linked list we need some
basic operations that manipulate the nodes.
INSERT a Node: At the beginning.
At the end.
Anywhere in the list.
DELETE a Node: At the beginning.
At the end.
Anywhere it is.
SEARCH for a Find the location for
node. above activities.
Inserting a New Node
• Steps to insert a new node:

1. Allocate memory for the new node.

2. Determine the insertion point. Implies

a search function. We need to know
the new nodes logical predecessor.

3. Point the new node to its successor.

4. Point the predecessor to the new node.