Вы находитесь на странице: 1из 390

Programming in C– An Overview

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

1
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
programming.
– Very concise language.

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

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

4
A Hello World Program
/*The first program.*/
Result is :
#include <stdio.h> Hello,world!
int main(void) //main function
{
printf(“Hello, world!\n”);
return 0;
}

5
Terms
• 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.
6
Terms (cont.)
• Library
– The file containing the standard functions that
a program can use.
• Complier time
– The time during which a program is being
compiled.
• Run time
– The time during which a program is executing.

7
Language Types
• Three types of programming languages
1. Machine languages
• Strings of numbers giving machine specific instructions
• Example:
+1300042774
+1400593419
+1200274027
2. Assembly languages
• English-like abbreviations representing elementary
computer operations (translated via assemblers)
• Example:
Load BASEPAY
Add overpay
Store GROSSPAY

8
Language Types, Cont.
3. High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via compilers)
• Example:
grossPay = basePay + overTimePay

9
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
languages
• Java, Python, Perl, VB are examples of high-level
high-level languages
• Application specific languages (Matlab, Javascript,
VBScript) are even higher-level.

10
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

11
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
variables
• The data type of every variable must be declared before that
particular variable can appear in a statement

12
Data types Contd….
• Four basic types
– char – a single byte capable of holding just one
character
– 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

13
Fundamental Data Types
char signed char unsigned char

short int long

unsigned short unsigned unsigned long

float double long double

14
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

15
int
• 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

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

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

18
Example
main()
{ 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

19
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

20
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

21
Floating points contd….
• The type float denotes normal precision real
numbers
• Single precision floating point numbers are
declared
float variable_name;

22
Floating points contd….
• The type double denotes double precision real
numbers
• Double precision floating point numbers are
declared
double variable_name;

23
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

24
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.
25
Keywords
• Reserved words.
• Cannot be redefined or used in other
contexts.
• Case sensitive.
• Have a special predefined meaning.

26
Reserved Words (Keywords) in C

int long
• auto break register return
• case char short signed
• const continue
sizeof static
• default do
• double else struct switch
• enum extern typedef union
• float for unsigned void
• goto if volatile while

27
Constants
• 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


28
Floating Point: Need a decimal pt or Scientific
notation.

23.7
.16
1.604
2e3

Character: Any single printable character in single


quotes. ‘?’, ‘A’, ‘9’…..

29
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
‘\0’.

30
String Constants (cont.)

“a string of text”

“” // the null string

“” // a string of a blank character

“ a = b + c; ” // nothing is executed

31
Punctuators
• 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);

}
32
Comments
• 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 33
• 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
returns.

34
Variables in C
Topics
• Naming Variables
• Declaring Variables
• Using Variables
• The Assignment Statement

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

x=a+b
z + 2 = 3(y - 5)
• Remember that variables in algebra are
represented by a single alphabetic character.

36
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)

37
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
surface_area

38
Case Sensitivity
• C is case sensitive
– It matters whether an identifier, such as a variable
name, is uppercase or lowercase.
– Example:
area
Area
AREA
ArEa
are all seen as different variables by the compiler.

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

40
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

garbage

41
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

42
Using Variables: Initialization
• Variables may be be given initial values, or
initialized, when declared. Examples:
length

int length = 7 ; 7

diameter

float diameter = 5.9 ; 5.9

initial
char initial = ‘A’ ; ‘A’

43
Using Variables: Initialization (con’t)
• 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 */

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

45
Example: Declarations and
Assignments
inches
garbage
#include <stdio.h> feet
garbage
int main( ) fathoms
garbage
{
int inches, feet, fathoms ; fathoms
7
feet
fathoms = 7 ; 42
feet = 6 * fathoms ; inches

inches = 12 * feet ; 504




46
Example: Declarations and Assignments
(cont’d)



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

return 0 ;
}

47
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);

48
Escape characters
Escape Description
Sequenc
e
\n Newline, position cursor at the start of a new
line
\t Horizontal tab, move cursor to the next tab
stop
\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
49
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
int
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
50
A simple C Program that reads in two
numbers,stores them and prints out the sum

main()
{
int x,y; /* places to store numbers */
printf("Enter x ");
scanf("%d",&x);
printf("Enter y ");
scanf("%d",&y);
printf("The sum of x and y was %d\n",x+y);
}

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

52
How to read characters
• You can read char values with the scanf
function
• C provides a function called getchar() which
allows you to read characters one at a time
from a line of input.

53
getchar()
• Function contained in stdio.h
• getchar() returns an int code for a character
typed on the standard input (the keyboard)
char c;
c = getchar() ;

54
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 putchar()
• For example,
putchar( c ) ;

55
putchar()
• Prints a character to the standard output
(screen)
• Is a function also referenced in stdio.h

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

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


58
Field Width Specification (cont.)
Character Data:

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

x_ _ _ _ y
_ _ _z

59
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'
program
• another name for the function print
2. An escape character can be included in a 'C'
string by including the following characters in the
string
• \e
• ESC
• \033
• \0x1B 60
Contd……..
3.Conventionally 'C' source files have names ending in
•.c
•.cpp
•.bas
•.html
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 video
•The program will not link correctly

61
Contd………..
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

62
Contd…..
True/False
• ___, ___, ____, _____, _______ 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 ______

63
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 them.

64
Operators
And
Expressions
Lecture 3

65
Operators
• Arithmetic Operators

• Relational and Logical Operators

• Special Operators

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

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

-a*b–c ((- a) * b) – c

68
• Expressions inside parentheses are evaluated
first.

1 * (2 - 3)

• Operators on the same level of precedence are


evaluated from left to right.
(Associativity).

1 + 2 + 3 + 4 –5

(((1 + 2) + 3) + 4) –5
69
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
70
• 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).
71
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”
72
Examples
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

73
l = 4;
n = 3;
m = 2;

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

After the assignment to x. 3


m

74
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*=k=m+5
j=(j*(k=(m+5))) ?
75
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);
76
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


zero.

77
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
! NOT
78
Precedence and Associativity

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

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

79
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.
80
Examples
!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 ?
81
int i, j = 1;

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

1) (i=2) i 2

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

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

1) (i = = 3) false 0

2) && j 1 && 0 0

3) = j 0

83
j 0 i 2

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

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

2) || 0 j || 1 true
1
1
3) = j
84
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
85
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
86
 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)

87
• 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.
88
e.g. int i;
i = 0;
for ( ; i < 10; putchar (‘a’ + i), i++);

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

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

Most commas in a program DO NOT represent


comma operators.
89
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;
} 90
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
91
Examples

x = 10;
x = 10;
y = x>9 ? 100 : 200; if(x>9)
y = 100;
else
y = 200;

92
int i, h, j = 2; ( ) not needed

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

k = (i>j) ? i:j; k get max of I


or j
93
This statement does what?

c = (c > =‘a’ && c < = ‘z’) ? c - (‘z’ - ‘Z’):c;

IF True - have a Lower case letter in the variable


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


94
Expressions
• 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 */ 95
Null Statement: ; [A semi-colon
alone by itself].

Can be useful in loops & conditional


statements.
The body of a loop could be empty
.
Scanf(“%d”, &x);
While(printf(“%d”,x) ,scanf(“%d”,&x))
;
96
Expressions (cont.)
• Spacing and Parentheses

x=10/y-(127/x);
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;
97
Exercises
• 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.

98
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
operators.
• ++p and p++ means the same in an assignment
expression 99
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? 100
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
x+=x++

101
Control constructs
Conditional Execution
Lecture 4

102
Selection
• if
• switch

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

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

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


compound_1
} No Semi-colon
else{
compound_2
};

• Conditional execution allows you write


code that reacts to tested conditions.
105
Example
#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
not”);

106
Example contd……

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

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


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

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


}
107
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
exclusive.
108
#include <stdio.h> Nested IF statements
main()
{ int score;
printf(“Please type in your score:”);
scanf(“%d”, &score);
printf(“Your grade is a “);
if (score >= 90) printf{“A”);
else
if (score >= 80) printf(“B”);
else
if (score >=70) printf(“C”);
else
if (score >=50) printf(“D”);
else
if (score >= 40) printf(“D”);
else
109
printf(“F”);}
The if-else-if ladder

• General form:
if (expression) statement;
else
if (expression) statement;
else
if (expression) statement;
.
.
.
else statement;
110
• The conditions are evaluated from the top
downward.
• 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.
111
Example

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

112
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;
else
bonus = 30000;
113
Conditional Expression
• The expressions must simply evaluate to
either a true or false (zero or nonzero) value.

• The expressions are not restricted to involving


the relational and logical operators.

114
The ?: Alternative
Exp1 ? Exp2: Exp3

x = 10;
x = 10;
y = x>9 ? 100 : 200; if(x>9)
y = 100;
else
y = 200;
115
#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.");
printf("\n");
return 0;
}
116
/* 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;
}
117
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
allowed).

• When a match is found, the statements


associated with that constant are
executed.
118
General Form
switch (expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
.
.
default
statement sequence
} //ANSI C allowed at least 257 case statements.
119
Execution
• 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. 120
• 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
rules). 121
• 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 */


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

case '2':
correct_errors ();
break;

case '3':
display_errors ();
break;

default :
printf("No option selected");
}
} 123
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:
process(k);
} 124
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;
default:
printf (“Invalid grade”); break; }}
125
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.

126
switch(x) {
case 1:
switch(y) {
case 0:
printf(''Divide by zero error.\n");
break;
case 1:
process(x, y);
break;
}
break;
case 2:
…. 127
Exercise
• control constructs in C are ___________
and ___________.
• If- else statement is used for
____________.
• The case statement values are
necessarily_____________.
• If values do not match any of the cases in
switch-case then the control is transferred
to ___________, if present.
128
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
also.
• break passes the control to the first statement in the
iterative block.
• 129
Exercise contd….

130
Loops
For,do-while ,while
Lecture 5-6

131
Iteration
• 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).

132
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.
133
Execution
• 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.

134
#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);
}
135
The Elements of the For-loop
• The initialization, testing and
incrementation can be any valid C
expression.

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

• Common use as a counting loop.

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

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

• The incrementation of the loop control


variable can occur outside the for
statement.
for( x=1 ; x < 10; )
{
printf("%d", x);
++x;
} 137
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");
138
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 loops.
• Does what?

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

139
Declaring Variables within a For Loop

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


140
While Loop
• General form:
while(condition)
statement;

• 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
loop.

141
Example
char wait_for_char(void)
{
char ch;
ch = '\0'; /* initialize ch */
while(ch != 'A') ch = getchar();
return ch;
}

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

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

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

A;
for (A; T; I)
While (T)
{
{
Body;
} Body;
I;
}
144
NESTED LOOPS
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
YOU MUST REPEAT
i.e., a repetition of an
already repetitive task. 145
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.
146
/* Find triples of integers that add up to n. */
#include <stdio.h>

main()
{ int cnt = 0, j , k , m,n;
n=7;
for(j = 0; j <= N; ++j)
for( k = 0; k <= N; ++k)
for( m = 0: m <= N; ++m)
if ( j + k + m == N) {
++cnt;
printf(“%d%d%d”, j , k , m); }
printf(“\n Count: %d\n”, cnt);
}

147
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

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

do {
scanf(''%d", &num);
} while(num > 100);
149
•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: ");

150
do {
ch = getchar(); /* read the selection from
the keyboard */
switch(ch) {
case '1':
check_spelling();
break;
case '2':
correct_errors();
break;
case '3':
display_errors();
break;
}

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


} 151
Jump
• break
• continue
• return (will be introduced in Ch. 4,
Functions).

152
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
153
•A break causes an exit from only the
innermost loop.
for(t=0; t < 100; ++t) {
count = 1;
for(;;) {
printf(''%d ", count);
count++;
if(count == 10) break;
}
}
123456789123456789…
100 times 154
Breaking out of loops
• Sometimes loops need to be cut short:
– You can break out of any loop with break ;
statement.
– A break will cause the loop to be aborted
immediately.
– The next statement executed is the statement
following the loop.
• Compare this with return:
– A return will cause a function to be aborted
immediately.
– Control returns to the calling function. 155
continue Statement
• General form
continue;

• break forces termination of the loop.

• continue forces the next iteration of the loop


to take place, skipping any code in between.

156
• 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.

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

putchar(ch+1);
}}
158
Exercise
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;
while(a)
{
printf("Hello");
a--;
}

159
• 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.

160
About Arrays
one-dimensional
multidimensional
Lecture 7-9

161
Arrays

• 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)
162
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];
163
One-dimensional arrays (1)

• Arrays can be
– initialized
– partially initialized
– not initialized
• Uninitialized space contains?
– "garbage"

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

166
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
167
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!
168
Program to generate the first 20 Fibonacci numbers
#include <stdio.h>
main()
{
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]);
}

169
PROGRAM TO MAXIMUM OF 25 GIVEN
ELEMENTS IN AN ARRAY
# 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” , max);
}
170
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; } 171
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 */
array[k-1]

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


scanf(“%d”’ &k);
printf (“\nThe %d a smallest element is %d”, k, array[k-1]);
}

172
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;} 173
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]);
}

174
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 */
175
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);

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

177
Two-dimensional arrays (4)

• Picture of arr:

1 23 -12 arr[0]

85 46 99 arr[1]

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

180
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
181
Program to add two matrices
# include <studio.h>
int main (void)
{ int sMatrix [3] [3] = {{1,2,3},
{4,5,6},
(7,8,8}};
int bMatrix{[3][3] = {{4,5,6},
{3,2,1}
(9,8,7}};
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];
182
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
ADDED MATRIX
5 7 9
7 7 7
16 16 16
183
program to find transpose of a matrix
# include <stdio.h>
int main (void)
{ int a [ROWS] [COLS] = { {1,2,3},
{4,5,6},
(7,8,8}};
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;
}
} 184
transpose of a matrix contd….
printf (“TRANSPOSE OF THE 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
TRANSPOSE OF THE MATRIX
1 4 7
2 5 8
3 6 8
185
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[]);
main()
{ char a[10];
Func(a);
........ }
void Func(char b[])
{ .....
.....
}
186
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;
}}
187
Passing arrays to functions
(contd..)
main()
{ int i;
int n[10]={44,-10, 0,16, 7, 2,1, 57, -33,
101};
printf("The array before sort:\n");
for(i = 0; i < 10; ++i) printf("%d",
n[i]);
Sort(n, 10);
printf("The array after the
sort:\n");
for(i = 0; i < 10; ++i) printf("%d",
n[i]);
printf("\n");
} 188
Exercises
1.void f(int x[], int y);
main()
{
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.

189
Strings

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

char w[MAXWORD];
w[0] = ‘A’;
w[1] = ‘\0’;
/*….*/ 191
• 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];

192
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”;

193
• 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.

194
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
195
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.

196
#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
gets(s2);

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


strlen(s2));

if(!strcmp(s1, s2))
printf("The strings are equal\n");

197
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");
printf(s1);

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


if(strstr("hi there", "hi")) printf("found hi");
return 0;
}
198
Dynamically Allocated Strings
• The type pointer to char is conceptually a
string.
• An example follows:

199
/* 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);
}
gets(s);
for(t=strlen(s)-2; t>=0; t--) putchar(s[t]);
free(s); return 0;
200
}
STORAGE CLASSES

201
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


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

203
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
dies(mortal).

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

205
auto
• 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;

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

207
When a block is entered, the system allocates
memory for the auto variables.
“LOCAL” i.e., Those declared in the
block.

When Block is exited the variables are


released and their values lost.

IF re-enter the
Block? _________

Memory is reallocated.
208
Call by Reference with Auto
Parameters
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.)

209
Extern
• 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
default.

210
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.
211
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 automatically.

212
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


213
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,
etc……..

214
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


int.

register i ;
215
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.

216
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 variable.

What are the consequences of the


immortal extent?

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

218
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.
219
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.

220
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.
221
Static Extern Variable
Restricted in scope to the “remainder of the file” in which
they are defined. Not known to other files(compilation
units).
void f(void)
{
…… /* v not available here */
}
static int v;
void g(void)
}
…… /* v can be used here */
}
222
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)


{
……..
}
223
Default Initialization

Extern & Static vars are initialized to 0 by


the system.

Auto & Register are usually not initialized


by system.

Start will garbage.

224
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


modified.
225
const
• 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


226
#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);
str++;
}
}
227
A definition causes a compiler to set aside
memory at compile time (every variable
definition is a declaration) - not always the
reverse.

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.
228
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.
229
Exercise

230
Functions and Structured
Programming

Lecture 10-13

231
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
subtasks.

• Each subtask can be coded directly as


a function.

• These functions can be used in main


to solve the overall problem. 232
Functions
• 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
233
General syntax:

ret-type function-name (parameter list)


{
body of the function
return (expression)
}

• A function may return any type of data except an


array.
• The parameters receive the values of the
arguments when the function is called.
234
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.
235
Variables

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

236
• Where variables are declared:

– Inside functions:
local variables

– Outside of all functions:


global variables

– In the definition of function parameters:


formal parameters

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

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


}
239
#include <stdio.h>
Local variables int main(void)
{
are stored on the int x;
run-time stack. x = 10;

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;
} 240
#include <stdio.h>
void f(void);
• The value will be int main(void)
{
assigned to the int i;
variable each time for(i=0; i<10; i++) f();
the block of code return 0;
}
in which it is
declared is entered. void f(void)
{
int j = 10;
printf("%d ", j);
j++; /* this line has no lasting effect */
}
241
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.
242
#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);
}
243
• Avoid using unnecessary global variables.

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

244
Function Parameters
• General form:

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

• All function parameters must be declared


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

• Parameters behave like any other local variable.

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

246
• 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.
247
• The formal parameters to a function also
fall within the function's scope.

– A parameter is known throughout the entire


function.

– A parameter comes into existence when the


function is called and is destroyed when the
function is exited,( I.e., the Extent of the
variable).
• A function cannot be defined within a
function(no nested-functions).
248
Communication with a Function

• Two ways that arguments can be passed to


a function.

– Call by Value.

– Call by Reference.

249
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
parameter.
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 250
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


parameter.
• 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]. 251
#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;
} 252
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.

253
#include <stdio.h>

void f(int a, int b)


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

int main (void)


{
f(10,3);
return 0;
}
254
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.
255
Func Prototype is “Heading” of function.

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


typically above any Function Definitions
But below :
#includes
#defines

This gives the FP’s File Visibility. Know


throughout the file.
256
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);
}

257
/* 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;
}

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

259
• General form:
return expression;

• It causes an immediate exit from the


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

• The value of expression will become the


return value of the function.
260
Rules
• 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;
{ 261
• 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.

262
• As long as a function is not declared as
void, it can be used as an operand in an
expression.

x = power(y);

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

for(ch=getchar(); isdigit(ch); ) . . . ;

263
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
system.
264
•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);
play();
...
}
265
Exercise
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
default.
• 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
call.

266
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.
• 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
functions.
• Using global variables increased the structural
organization of a program.
• It is must to declare functions before they are used.

267
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
values.
268
RECURSION

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.

269
Recursion
• 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 ;
} }
270
Factorial of a number using recursion
#include <stdio.h>
int factorial (int n)
{if (n= = 0);
return 1;
else
return (n* factorial (n-1));}
int main (void)
{ int n;
printf ( <<Enter the number: <<);
scanf (<<The factorial of %d is %d>>, n,
factorial (n));
}
271
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
Hanoi.
• Recursive code necessarily needs a _______.
• Quick sort algorithm terminates when ______.
• Quick sort was developed by ________.
• Quick sort divides the array into _____ using ______.

272
Pointers

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

• They support dynamic memory allocation.

• They provide support for dynamic data


structures, such as binary trees and linked
lists.

274
What Are Pointers
• A pointer is the memory address of an
object.

• 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. 275
Memory Variable in
address memory
1000 1003
1001
1002
1003
1004
1005
.
.
. 276
Pointer Declaration

• General syntax:
type *name;

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


//pointer to type int.
char *ch;

int count, *y, q;


277
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.
278
& 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

100
279
* 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. ?

280
#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;
}
281
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.

282
#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;
}
283
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.

284
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
285
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. 286
4. k = &i;

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

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

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

p2 = p1;

p2 = &b;

p1? p2? *p1? *p2? 288


int a=42, b=53, *p1, *p2;
p1 ? 42
p2
? 53 p2 = p1;
p1 42
p1 = &a; p2 53
p1 42
p2 ? 53 p2 = &b;
p1 42
p2 53
289
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;
290
p1 = p2;
before after
p1 8 p1 8

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

p2 9 p2 9 291
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.
292
Example 5
int a=3,b=7,*p; p = &b;

3 7
a b p

*p=2**p–a;

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 11 293
Pointer Initialization

int i, *p = &i; correct

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

The variable must be defined


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

p = 0; “Null” is usually defined as


0.

p = NULL; Pointer constant points


“nowhere”.

p = (int *) 1307;
cast to pointer to int.
1307 is an absolute address in
memory.
295
int i = 3, j = 5, *p = &i, *q = &j, *r;
double x;
r
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)


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

*&p - “The Addr


2
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” 297
3) r = &x; Illegal
Why?
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
298
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;
299
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.
300
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

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

302
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 function.

303
Steps
1) Declare a function parameter to be a
pointer.

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.

304
#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;
} 305
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 */
}

306
Exercise
Fill in the blanks
• _________gives C the power to deal with machine
architecture.
• _______ gets the value stored by location pointed by a
pointer.
• 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). 307
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.

308
Structures

309
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.
310
Structures
• 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.

311
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


members.

• Usually, the members of a structure are logically


related.

312
General Form
struct tag {
type member-name;
type member-name;
type member-name;
.
.
.
} structure-variable(s);

313
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.
314
Structure Variable Declaration
struct addr addr_info;

declares a variable of type struct addr called


addr_info.

The compiler automatically allocates sufficient


memory to accommodate all of its members.

315
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 316
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;
317
Initialization of Structures

All, Extern and Static Variables including

structure variables that are not explicitly

initialized, are automatically initialized to


0.

318
Accessing Structure Members

• Individual members of a structure are


accessed through the use of the Dot
Operator (“.”).

• General form:

object-name.member-name

319
e.g., addr_info.zip = 12345;
printf("%lu", addr_info.zip);

gets(addr_info.name);

for(t=0; addr_info.name[t]; ++t)


putchar( addr_info.name[t] );

320
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;
} 321
Array of Structures

WHY?

What does an array of structures allow us to do


that is not possible with any other single
structure?

322
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';
323
Passing Structures to Functions

• Passing Structure Members to Functions.

• Passing Entire Structures to Functions

324
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;
325
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]
*/
326
Passing Entire Structures to Functions
• Call-by-value:

#include <stdio.h>

struct Example_type {
int a, b;
char ch;
};

327
void f1(struct Example_type parm);

int main(void)
{
struct Example_type arg;

arg.a = 1000;
f1(arg);
return 0; struct_type
} must match
void f1(struct Example_type parm)
{
printf(''%d", parm.a);
} 328
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];
…..
} 329
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-
reference.

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

331
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 allocation.

332
struct bal {
float balance;
char name[80];
} person;

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

p = &person;

333
The Structure Pointer Operator
–>
Used to access the members of a structure via a
pointer.
p–>balance

Forms:
(*pointer-To-Struct). member
or
pointer-To-Struct member
334
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;
};

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

336
Arrays and Structures Within
Structures

• A member of a structure can be either a

single variable or an aggregate type. In C

aggregate types are arrays and structures.

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

y.a[3][7] 338
Structures within Structures

struct emp {
struct addr address; /* nested structure */
float wage;
} worker;

worker.address.zip = 93456;

339
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));
340
typedef
• 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.
341
• General Form:

typedef type newname;

typedef float BALANCE;

BALANCE over_due;

342
E.g., The declaration for an array of
pointers to strings.

Char * stringPtrAry[20];

Typedef char * STRING;

STRING StrPtrAry[20];

343
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);

344
File handling

File accessing Function

345
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. 346
• 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).
347
• 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 using.

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

349
• 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.

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

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

352
Three File Pointers
stdin Standard input Connected
file to the
keyboard
Stdout Standard output Connected
file to the
screen
stderr Standard error file Connected
to the
screen
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
354
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;
355
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);

356
• 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


opened.

• 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.
357
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
358
FILE *fp;
if ((fp = fopen("test","w"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}
• 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. 359
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
unchanged.
When a file is opened for writing:
- If the file does not exist, it will be
created.
- If it does exist, the contents of the
original file will be destroyed, and a
new file will be created.
360
• 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
not.

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

362
• 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.

363
• 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.

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

365
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); 366
/* KTOD: A key to disk program. */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{ KTOD TEST
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");
exit(1);
}
367
if((fp=fopen(argv[1], "w"))==NULL) {
printf(''Cannot open file.\n");
exit (1);
}

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

fclose(fp);
return 0;
} 368
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);
369
Working with Strings
• fputs( )

• General form:

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

Returns EOF if an error occurs.

370
• 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.

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

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

373
• 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


mode.
374
#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");
exit(1);
}
375
do {
printf("Enter a string (CR to quit):\n");
gets(str);
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);
printf(str);
} return 0;
}
376
Erasing Files
• General form:

int remove(const char *filename);

It returns zero if successful. Otherwise, it


returns a nonzero value.

377
#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");
exit(1);
}

378
printf("Erase %s? (Y/N): ", argv[1]);

gets(str);

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

return 0;

}/* END MAIN */

379
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(…);

380
#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");
exit(1);
}
381
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 */
fclose(fp);

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

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


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

return 0;
382
}
LINKED LIST

383
LINKED LIST
DATA STRUCTURE

• A Linked List is an ordered collection of data in


which each element contains 2 parts: data and
link.

• 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 dynamically.


384
Head Data Data Data Data

The Head ptr gives acess to the LINKED LIST which is a


sequence of linked nodes.

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

386
Type Definition for a Linked List
typedef int KEY_TYPE;

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

typedef struct nodetag


{ DATA data;
struct nodetag *link;
} NODE; A TYPE for EACH NODE
387
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 …).
388
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.
389
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.


390

Вам также может понравиться