Professional Documents
Culture Documents
C Programming
Unit I - Introduction
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
1
Learning Objectives
• History of C
• Characteristics of C
• C Program Structure
• Variables, Defining Global Variables
• Printing Out and Inputting Variables
• Constants
• Operators
• Conditionals
• Looping and Iteration
• Arrays and Strings
• Functions
• Storage classes
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
2
Objectives
• History of C
• Characteristics of C
• C Program Structure
• Variables, Defining Global Variables
• Printing Out and Inputting Variables
• Constants & Literals
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
3
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 1
MCA-103, Programming in C
History of C
• Developed by Brian Kernighan and Dennis Ritchie of
AT&T Bell Labs in 1972
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
4
Features of C
• C can be thought of as a “high level assembler”
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
5
Writing C Programs
• A programmer uses a text editor to create or modify files
containing C code.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
6
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 2
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
7
1. Preprocessing
2. Compilation
3. Linking
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
8
Stage 1: Preprocessing
Performed by a program called the preprocessor
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
9
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 3
MCA-103, Programming in C
Stage 2: Compilation
Performed by a program called the compiler.
If any compiler errors are received, no object code file will be generated.
An object code file will be generated if only warnings, not errors, are
received.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
10
Stage 3: Linking
• Combines the program object code with other object code to
produce the executable file.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
11
Developing a C Program
Editor
Preprocessor
Modified Source Code in RAM
Compiler
Program Object Code File pgm.obj
Linker
Executable File
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
12
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 4
MCA-103, Programming in C
Keys Operation
F9 Compile Only
Ctrl F9 Compile & run
Alt F5 To see Output Screen
F2 Save the File
Alt X Exit Turbo C
F3 Load File
F6 Switch Window
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
13
A Simple C Program
/* Filename: hello.c
Author: --------
Date written: --/--/----
Description: This program prints the greeting
“Hello, World!”
*/
#include <stdio.h>
int main ( void )
{
printf ( “Hello, World!\n” ) ;
return 0 ;
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
14
Structure of a C Program
program header comment
int main ( )
{
statement(s)
return 0 ;
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
15
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 5
MCA-103, Programming in C
Explanation
tells compiler about standard input and output functions (i.e. printf + others)
#include
#include <stdio.h>
<stdio.h> /*
/* comment
comment */
*/
main function
int
int main(void)
main(void)
{{
printf("Hello\n");
printf("Hello\n");
“begin” printf("Welcome
printf("Welcome to
to the
the Course!\n");
Course!\n");
return
return 0;
0;
}}
flag success Hello
Hello
to operating “end”
Welcome
Welcome to
to the
the Course!
Course!
system
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
16
Tokens
• The smallest element in the C language is the
token.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
17
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
18
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 6
MCA-103, Programming in C
Numeric Literals
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
19
Character Literals
• Singular!
• One character defined character set.
• Surrounded on the single quotation mark.
• Examples:
‘A’
‘a’
‘$’
‘4’
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
20
String Literals
• A sequence characters surrounded by double quotation
marks.
• Considered a single item.
• Examples:
“UMBC”
“I like ice cream.”
“123”
“CAR”
“car”
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
21
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 7
MCA-103, Programming in C
Keywords
• Sometimes called reserved words.
• Are defined as a part of the C language.
• Can not be used for anything else!
• Examples:
int
while
for
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
22
Names / Identifiers
• Variables must be declared before use and
immediately after “{”
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 8
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
25
Punctuation
• Semicolons, colons, commas, apostrophes, quotation marks, brackets,
and parentheses.
• ; : , ‘ “{ } ( )
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
26
Operators
There are operators for:
assignments
mathematical operations
relational operations
Boolean operations
bitwise operations
shifting values
subscripting
obtaining the size of an object
obtaining the address of an object
referencing an object through its address
choosing between alternate sub-expressions
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
27
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 9
MCA-103, Programming in C
Things to remember
• Statements are terminated with semicolons
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
28
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
29
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
30
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 10
MCA-103, Programming in C
Topics
• Variables
Naming
Declaring
Using
• The Assignment Statement
• Constants
• Data Input & Output
• Type Conversion
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
31
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
32
Naming Conventions
• Begin variable names with lowercase letters
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
33
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 11
MCA-103, Programming in C
Declaring Variables
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
34
Declaring Variables
When we declare a variable
Space is set aside in memory to hold a value of the specified
data type
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
35
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
36
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 12
MCA-103, Programming in C
Integer Types in C
C supports different kinds of integers
maxima and minima defined in “limits.h”
Limits depend upon size in bytes which in turn depends upon
environment
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
37
Integer Example
#include
#include <stdio.h>
<stdio.h>
#include
#include <limits.h>
<limits.h>
int
int main(void)
main(void)
{{
unsigned
unsigned long
long big
big == ULONG_MAX;
ULONG_MAX;
printf("minimum
printf("minimum int
int == %i,
%i, ",
", INT_MIN);
INT_MIN);
printf("maximum
printf("maximum int
int == %i\n",
%i\n", INT_MAX);
INT_MAX);
printf("maximum
printf("maximum unsigned = %u\n", UINT_MAX);
unsigned = %u\n", UINT_MAX);
printf("maximum
printf("maximum long
long int
int == %li\n",
%li\n", LONG_MAX);
LONG_MAX);
printf("maximum
printf("maximum unsigned
unsigned long
long == %lu\n",
%lu\n", big);
big);
return
return 0;
0; minimum int = -32768, maximum int = 32767
}} minimum int = -32768, maximum int = 32767
maximum
maximum unsigned
unsigned == 65535
65535
maximum
maximum long
long int
int == 2147483647
2147483647
maximum
maximum unsigned long == 4294967295
unsigned long 4294967295
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
38
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
39
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 13
MCA-103, Programming in C
• Example assignments:
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
40
Use
scanf (“%c”, &ch) ;
to read a single character into the variable ch.
Use
printf(“%c”, ch) ;
to display the value of a character variable.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
41
Character Example
Note: print integer
value of character
#include
#include <stdio.h>
<stdio.h>
#include
#include <limits.h>
<limits.h>
int
int main(void)
main(void)
{{
char
char lower_a
lower_a == 'a';
'a';
char
char lower_m
lower_m == 'm';
'm';
printf("minimum
printf("minimum char
char == %i,
%i, ",
", CHAR_MIN);
CHAR_MIN);
printf("maximum
printf("maximum char
char == %i\n",
%i\n", CHAR_MAX);
CHAR_MAX);
printf("after
printf("after '%c'
'%c' comes
comes '%c'\n",
'%c'\n", lower_a,
lower_a, lower_a
lower_a ++ 1);
1);
printf("uppercase
printf("uppercase is
is '%c'\n",
'%c'\n", lower_m
lower_m -- 'a'
'a' ++ 'A');
'A');
return
return 0;
0;
}} minimum
minimum char
char == 0,
0, maximum
maximum char
char == 255
255
after
after 'a'
'a' comes
comes 'b'
'b'
uppercase is 'M'
uppercase is 'M'
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
42
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 14
MCA-103, Programming in C
char I/O
#include
#include <stdio.h>
<stdio.h>
int
int main
main (( ))
{{
char
char ch
ch ;;
printf
printf (“Enter character: “)
(“Enter aa character: “) ;;
scanf
scanf (“%c”,
(“%c”, &ch)
&ch) ;;
printf
printf (“The
(“The value
value of
of %c\n.”,
%c\n.”, ch)
ch) ;;
return
return 00 ;;
}}
Input: A
Output : The value of A is 65.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
43
Garbage in stdin
While reading integers using scanf( ),
The problem with the newline character didn’t seem to
be there.
As scanf( ) looks for the next integer ignoring
whitespaces.
After reading the integer, the newline is still present in
the input stream.
If the next item read is a character we will get the
newline.
We have to take this into account and remove it.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
45
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 15
MCA-103, Programming in C
Real Types In C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
46
Real Example
#include
#include <stdio.h>
<stdio.h>
#include
#include <float.h>
<float.h>
int
int main(void)
main(void)
{{
double
double ff == 3.1416,
3.1416, gg == 1.2e-5,
1.2e-5, hh == 5000000000.0;
5000000000.0;
printf("f=%lf\tg=%lf\th=%lf\n",
printf("f=%lf\tg=%lf\th=%lf\n", f,
f, g,
g, h);
h);
printf("f=%le\tg=%le\th=%le\n",
printf("f=%le\tg=%le\th=%le\n", f,
f, g,
g, h);
h);
printf("f=%lg\tg=%lg\th=%lg\n",
printf("f=%lg\tg=%lg\th=%lg\n", f, g, h);
f, g, h);
printf("f=%7.2lf\tg=%.2le\th=%.4lg\n",
printf("f=%7.2lf\tg=%.2le\th=%.4lg\n", f,
f, g,
g, h);
h);
return
return 0;
0;
}} f=3.141600 g=0.000012 h=5000000000.000000
f=3.141600 g=0.000012 h=5000000000.000000
f=3.141600e+00
f=3.141600e+00 g=1.200000e-05
g=1.200000e-05 h=5.000000e+09
h=5.000000e+09
f=3.1416
f=3.1416 g=1.2e-05
g=1.2e-05 h=5e+09
h=5e+09
f=
f= 3.14
3.14 g=1.20e-05
g=1.20e-05 h=5e+09
h=5e+09
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
47
Constants
• Constants have types in C
• Numbers without “.”, “e” or “F” are int, e.g. 10000, -35
(some compilers switch to long int if the constant would
overflow int)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 16
MCA-103, Programming in C
Warning!
return
return 0;
0;
}}
f=5000000000.000000
f=5000000000.000000
g=705032704.000000 OVERFLOW
g=705032704.000000
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
49
Named Constants
Named constants may be created using const
#include
#include <stdio.h>
<stdio.h>
creates an
integer int
int main(void)
main(void)
constant {{
const
const long
long double
double pi
pi == 3.141592653590L;
3.141592653590L;
const
const int
int days_in_week
days_in_week == 7;7;
const
const sunday
sunday == 0;
0;
days_in_week
days_in_week == 5;
5;
error!
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
50
Preprocessor Constants
Named constants may also be created using the
Preprocessor
Needs to be in “search and replace” mode
Historically these constants consist of capital letters
int
int day
day == SUNDAY;
SUNDAY;
long
long flag
flag == USE_API;
USE_API;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 17
MCA-103, Programming in C
• You can not assume that the variable will have a value
before you give it one.
Some compilers do, others do not! This is the
source of many errors that are difficult to find.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
52
int length = 7 ;
length
float diameter = 5.9 ; 7
diameter
char initial = ‘A’ ;
5.9
initial
‘A’
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
53
Example:
int height ; /* rectangle height */
int width = 6 ; /* rectangle width */
int area ; /* rectangle area */
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
54
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 18
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
55
Examples:
diameter = 5.9 ;
area = length * width ;
Note that only single variables may appear on the left-hand
side of the assignment operator,
The statement
length= width= 10.9;
is accepted and assigns a value 10.9 to both the variables
named length and width. Can you justify why.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
56
Functions
• We saw that it was necessary for us to use some functions
to write our first programs.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
57
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 19
MCA-103, Programming in C
I/O Example
printf("%i
printf("%i -- %i
%i == %i\n",
%i\n", a,
a, b,
b, aa -- b);
b);
write “a”, “b” and “a-b” return
return 0;
0;
in the format specified }}
Enter
Enter two
two numbers:
numbers: 21
21 17
17
21
21 -- 17
17 == 44
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
58
Displaying Variables
• A Function that allows us to display formatted data :
printf( ).
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
59
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
60
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 20
MCA-103, Programming in C
• (We can input more than one item at a time if we wish, as long as we
specify it correctly.)
• Notice the “&” in front of the variable name. Can you explain its
significance!
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
61
Format Specifiers
• Format specifiers are normal strings with embedded
“conversion specifications” which are placeholders for
arguments
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
62
Conversion Specifications
Conversion specifications tell how to translate
a data value into a string
Conversion Specifications: Options:
%d, %i -- signed integer l -- long
%u -- unsigned integer .n -- precision of n digits
%f -- floating point number 0 -- fill unused field with 0s
%c -- character
%s -- string
%x -- hexadecimal value
%p -- pointer
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
63
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 21
MCA-103, Programming in C
Escape Sequences
Seq Meaning Example Output
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
64
printf quiz!
Answers:
2.325 rounded to 2 decimals is 2.33
24 in hex is 0018
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
65
scanf Examples
int items_read;
Read an integer:
int num;
items_read = scanf(“%d”, &num);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 22
MCA-103, Programming in C
sscanf examples
#include <stdio.h>
main()
{
char Host[64];
char User[64];
char Buff[200] = "Hostname=Server1 User=test
Time=11:15";
------- ---------
| /
| /
sscanf (Buff, "Hostname=%s %s", Host, User);
printf("Host is %s\n", Host);
printf("User is %s\n", User);
exit(0);
}
Host is Server1
User is User=test
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
67
Type Conversion
#include <stdio.h>
void main(void)
{
int i,j = 12; /* i not initialized, only j */
float f1,f2 = 1.2;
f1 = f2 + (float) j; /* explicit:
f1 <- 1.2 + 12.0 */
f1 = f2 + j; /* implicit: f1 <- 1.2 + 12.0 */
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
68
Type Conversion
• char < short int < int < long int < float < double < long double
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
69
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 23
MCA-103, Programming in C
• Place a blank line between the last variable declaration and the first
executable statement of the program.
• Comments should explain why you are doing something, not what you
are doing it.
• a = a + 1;
• /* add one to a */ /* WRONG */
• /* count new student */ /* RIGHT*/
• /*variable name should have been more descriptive*/
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
71
Remaining
Scope and lifetime of variables
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
72
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 24
MCA-103, Programming in C
Operators in C
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
73
Objectives
• Arithmetic operators
• Cast operator
• Increment and Decrement
• Bitwise operators
• Comparison operators
• Assignment operators
• sizeof operator
• Conditional expression operator
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
74
Arithmetic Operators in C
Name Operator Example
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
75
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 25
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
76
Division
• If both operands of a division expression are integers, you
will get an integer answer. The fractional portion is
discarded.
int
intmain(void)
main(void)
if either operand is a
{{
double, the other is
int
int ii == 5,
5, jj == 4;
4;
automatically
doublef;
doublef;
promoted
ff == (double)i
(double)i // j;
j;
ff == ii // (double)j;
(double)j;
ff == (double)i
(double)i // (double)j;
(double)j;
integer division is done ff == (double)(i
(double)(i // j);
j);
here, the result, 1, is
changed to a double, return
return 0;
0;
1.00000 }}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
78
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 26
MCA-103, Programming in C
Modulus
• The expression m % n yields the integer remainder
after m is divided by n.
• Modulus is an integer operation- - both operands
MUST be integers.
• Examples : 17 % 5 = 2
6%3 = 0
9%2 = 1
5%8 = 5
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
79
Precedence
Operator(s) Precedence & Associativity
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
80
int
int ii == 5,
5, jj == 4;
4;
“i” becomes 6
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
81
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 27
MCA-103, Programming in C
ii == ++j;
++j; equivalent to:
printf("i=%d,
printf("i=%d, j=%d\n",
j=%d\n", i,
i, j);
j); 1. i = j;
2. j++;
jj == 5;
5;
ii == j++;
j++;
printf("i=%d,
printf("i=%d, j=%d\n",
j=%d\n", i,
i, j);
j);
i=6,
i=6, j=6
j=6
i=5,
i=5, j=6
j=6
return
return 0;0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
82
Prefix Vs Postfix
int amount, count ;
count = 3 ;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
83
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
84
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 28
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
85
Practice
Given
int a = 1, b = 2, c = 3 ;
++a * b- c--
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
86
More Practice
Given
int a = 1, b = 2, c = 3, d = 4 ;
++b / c + a * d++
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
87
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 29
MCA-103, Programming in C
Using Parentheses
One can use parentheses to change the order in which an
expression is evaluated.
a+b*c
1. Would multiply b * c first,
2. then add a to the result.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
88
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
89
Truth in C
• To understand C’s comparison operators (less than, greater
than, etc.) and the logical operators (and, or, not) it is
important to understand how C regards truth
• There is no boolean data type in C, integers are used
instead
• The value of 0 (or 0.0) is false
• Any other value, 1, -1, 0.3, -20.8, is true
if(32)
if(32)
printf("this
printf("this will
will always
always be
be printed\n");
printed\n");
if(0)
if(0)
printf("this
printf("this will
will never
never be
be printed\n");
printed\n");
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
90
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 30
MCA-103, Programming in C
Relational Operators
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== is equal to
!= is not equal to
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
91
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
92
Logical Operators
• At times we need to test multiple conditions in order to
make a decision.
• Logical operators combine simple conditions to make
complex conditions.
• Result into a 0 (false) or 1 (true)
|| OR if ( z == 0 || x > 10 )
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
93
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 31
MCA-103, Programming in C
if
if (( age
age << 11 &&
&& gender == ‘m’)
gender == ‘m’)
{{
printf
printf (“Infant
(“Infant boy\n”)
boy\n”) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
94
0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
Exp1 && Exp2 && … && Expn will evaluate to 1 (true) only if
ALL sub-conditions are true.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
95
Example Use of ||
if
if (grade == ‘D’
(grade == ‘D’ ||
|| grade == ‘F’)
grade == ‘F’)
{{
printf
printf (“Must
(“Must reappear
reappear in
in the
the next
next
semester!\n”)
semester!\n”) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
96
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 32
MCA-103, Programming in C
Exp1 && Exp2 && … && Expn will evaluate to 1 (true) if only
ONE sub-condition is true.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
97
Example Use of !
if
if (( !! (x
(x ==
== 2)
2) )) /*/* same
same as
as (x
(x !=
!= 2)
2) */*/
{{
printf(“x
printf(“x is
is not
not equal
equal to
to 2.\n”)
2.\n”) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
98
Expression ! Expression
0 1
nonzero 0
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
99
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 33
MCA-103, Programming in C
Practice
Given
int a = 5, b = 7, c = 17 ;
1. c / b == 2
2. c % b <= a % b
3. b + c / a != c - a
4. (b < c) && (c == 7)
5. (c + 1- b == 0) || (b = 5)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
100
Warning!
Remember to use parentheses with conditions, otherwise your
program may not mean what you think
int
int ii == 10;
10;
if(!i
if(!i ==
== 5)
5)
printf("i
printf("i is
is not
not equal
equal to
to five\n");
five\n");
else
else
printf("i is equal to five\n");
printf("i is equal to five\n");
ii is
is equal
equal to
to five
five
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
101
Bitwise Operators
C has the following bit operators which may only be
applied to integer types:
& bitwise and
| bitwise inclusive or
^ bitwise exclusive or
~ one’s compliment
>> right shift
<< left shift
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
102
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 34
MCA-103, Programming in C
Bitwise Example
#include
#include <stdio.h>
<stdio.h> 0x6eb9
0x6eb9 0110
0110 1110
1110 1011
1011 1001
1001
0x5d27
0x5d27 0101
0101 1101
1101 0010
0010 0111
0111
int
int main(void)
main(void) 0x4c21
0x4c21 0100
0100 1100
1100 0010
0010 0001
0001
{{
short
short aa == 0x6eb9;
0x6eb9; 0x6eb9
short 0x6eb9 0110
0110 1110
1110 1011
1011 1001
1001
short bb == 0x5d27;
0x5d27; 0x5d27
0x5d27 0101
0101 1101
1101 0010
0010 0111
0111
unsigned
unsigned short
short cc == 7097;
7097; 0x7fbf
0x7fbf 0111 1111 1011 1111
0111 1111 1011 1111
printf("0x%x,
printf("0x%x, ",
", aa && b);
b);
printf("0x%x, 0x6eb9
0x6eb9 0110
0110 1110
1110 1011
1011 1001
printf("0x%x, ",
", aa || b);
b); 1001
printf("0x%x\n", 0x5d27
0x5d27 0101
0101 1101
1101 0010
0010 0111
printf("0x%x\n", aa ^^ b);
b); 0111
0x339e
0x339e 0011
0011 0011
0011 1001
1001 1110
1110
printf("%u,
printf("%u, ",
", cc <<
<< 2);
2);
printf("%u\n",
printf("%u\n", cc >>>> 1);
1);
7097
7097 0001
0001 1011
1011 1011
1011 1001
1001
return
return 0;
0; 28388
28388 0110
0110 1110
1110 1110
1110 0100
0100
}}
0x4c21,
0x4c21, 0x7fbf,
0x7fbf, 0x339e
0x339e 7097
7097 0001
0001 1011
1011 1011
1011 1001
1001
28388,
28388, 3548
3548 3548
3548 0000
0000 1101
1101 1101
1101 1100
1100
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
103
Shift Operations
If the left operand is an unsigned integer logical shifts
are carried out.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
104
Assignment
• Assignment is more flexible than might first appear
• An assigned value is always made available for subsequent
use
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
105
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 35
MCA-103, Programming in C
Warning!
One of the most frequent mistakes is to confuse test for
equality, “==”, with assignment, “=”
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void)
{{
int
int ii == 0;
0;
if(i
if(i == 0)
0)
printf("i
printf("i is
is equal
equal to
to zero\n");
zero\n");
else
else
printf("somehow
printf("somehow i is not zero\n");
i is not zero\n");
return
return 0;
0;
}}
somehow
somehow ii is
is not
not zero
zero
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
106
In each of these:
expression1 op= expression2
is equivalent to:
(expression1) = (expression1) op (expression2)
aa +=
+= 27;
27; ff /=
/= 9.2;
9.2; ii *=
*= jj ++ 2;
2;
aa == aa ++ 27;
27; ff == ff // 9.2;
9.2; ii == ii ** (j
(j ++ 2);
2);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
107
sizeof Operator
C has a mechanism for determining how many bytes a variable
occupies
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void)
{{
long
long big;
big;
printf("\"big\"
printf("\"big\" isis %u
%u bytes\n",
bytes\n", sizeof(big));
sizeof(big));
printf("a
printf("a short
short is
is %u
%u bytes\n",
bytes\n", sizeof(short));
sizeof(short));
printf("a
printf("a double
double is
is %u
%u bytes\n",
bytes\n", sizeof
sizeof double);
double);
return
return 0;
0; "big"
"big" is
is 44 bytes
bytes
}}
aa short
short is
is 22 bytes
bytes
aa double
double is 88 bytes
is bytes
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
108
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 36
MCA-103, Programming in C
int
int i,
i, jj == 100,
100, kk == -1;
-1; int
int i,
i, jj == 100,
100, kk == -1;
-1;
ii == (j
(j >> k)
k) ?? jj :: k;
k; ii == (j
(j << k)
k) ?? jj :: k;
k;
if(j
if(j >> k)
k) if(j
if(j << k)
k)
ii == j;
j; ii == j;
j;
else
else else
else
ii == k;
k; ii == k;
k;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
109
Precedence of Operators
• C treats operators with different importance, known as
precedence
• There are 15 levels
• In general, the unary operators have higher precedence than
binary operators
• Parentheses can always be used to improve clarity
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void)
{{
int
int jj == 33 ** 44 ++ 48
48 // 7;
7;
printf("j
printf("j == %i\n",
%i\n", j);
j);
return
return 0;
0; jj == 18
}} 18
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
110
Associativity of Operators
• For two operators of equal precedence (i.e. same
importance) a second rule, “associativity”, is used
• Associativity is either “left to right” (left operator first) or “right
to left” (right operator first)
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void)
{{
int
int ii == 66 ** 44 // 7;
7;
printf("i
printf("i == %d\n",
%d\n", i);
i);
return
return 0;
0;
}} ii == 33
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
111
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 37
MCA-103, Programming in C
Precedence/Associativity Table
Operator Associativity
() [] -> . left to right
! ~ ++ -- - + (cast) * & sizeof right to left
* / % left to right + - : unary
+ - left to right
<< >> left to right
< <= >= > left to right
== != left to right
& left to right
| left to right
^ left to right
&& left to right
|| left to right
?: right to left
= += -= *= /= %= etc right to left
, left to right
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
112
Review
#include
#include <stdio.h>
<stdio.h>
int
int main(void){
main(void){
int
int ii == 0,
0, j,
j, kk == 7,
7, mm == 5,
5, n;
n;
jj == mm +=
+= 2;
2;
printf("j
printf("j == %d\n",
%d\n", j);
j);
jj == k++
k++ >> 7;
7;
printf("j
printf("j == %d\n",
%d\n", j);
j);
jj == ii ==
== 00 && k;
k;
printf("j
printf("j == %d\n",
%d\n", j);
j);
nn == !i
!i >> kk >>
>> 2;
2;
printf("n
printf("n == %d\n",
%d\n", n);
n);
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
113
Expression Value
i += j + k
j *= k = m + 5
k -= m /= j * 2
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
114
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 38
MCA-103, Programming in C
#include
#include <stdio.h>
<stdio.h>
int
int main
main (( ))
{{
int
int num,
num, temp,
temp, digits
digits == 00 ;;
temp
temp == num
num == 4327
4327 ;;
while
while (( temp
temp >> 00 ))
{{
printf
printf (“%d\n”, temp)
(“%d\n”, temp) ;;
temp
temp /=/= 10
10 ;;
digits++
digits++ ;;
}}
printf
printf (“%d
(“%d digits
digits inin %d.\n”,
%d.\n”, digits,
digits, num);
num);
return
return 00 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
115
Debugging Tips
Trace your code by hand (a hand trace), keeping track of the
value of each variable.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
116
Structured Programming
All programs can be written in terms of only three control
structures
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
117
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 39
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
118
The braces are not required if the body contains only a single
statement.
However, they are a good idea and are required by the C Coding
Standards.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
119
Examples
if
if (( age
age >=
>= 18
18 ))
{{
printf(“Vote!\n”)
printf(“Vote!\n”) ;;
}}
if
if (( value
value ==
== 00 ))
{{
printf
printf (“The
(“The value
value you
you entered
entered was
was zero.\n”);
zero.\n”);
printf
printf (“Please
(“Please try
try again.\n”)
again.\n”) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
120
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 40
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
121
Warning!!!!!!
A semicolon after the condition forms a “do nothing”
statement
printf("input
printf("input an
an integer:
integer: ");
");
scanf("%i",
scanf("%i", &j);
&j);
if(j
if(j >> 0);
0);
printf("a
printf("a positive
positive number
number was
was entered\n");
entered\n");
input
input an
an integer:
integer: -6
-6
aa positive
positive number
number was
was entered
entered
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
122
if ( condition )
{
statement(s) /* the if clause */
}
else
{
statement(s) /* the else clause */
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
123
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 41
MCA-103, Programming in C
Example
if
if (( age
age >=
>= 18
18 ))
{{
printf(“Vote!\n”)
printf(“Vote!\n”) ;;
}}
else
else
{{
printf(“Maybe
printf(“Maybe next
next time!\n”)
time!\n”) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
124
Nesting ifs
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
125
Nesting ifs
else associates with the nearest if
Use curly brackets { } to override
int
int ii == 100;
100;
if(i
if(i >> 0)
0)
if(i
if(i >> 1000)
1000)
printf("i
printf("i is
is big\n");
big\n");
else
else ii is
is reasonable
reasonable
printf("i
printf("i is
is reasonable\n");
reasonable\n");
int
int ii == -20;
-20;
if(i
if(i >> 0)
0) {{
if(i
if(i >> 1000)
1000)
printf("i
printf("i is
is big\n");
big\n");
}} else
else ii is
is negative
negative
printf("i is negative\n");
printf("i is negative\n");
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
126
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 42
MCA-103, Programming in C
else if ( condition2 )
{
statement(s)
}
... /* more else clauses may be here */
else
{
statement(s) /* the default case */
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
127
Example
if
if (( value
value ==
== 00 ))
{{
printf
printf (“You
(“You entered
entered zero.\n”)
zero.\n”) ;;
}}
else
else if
if (( value
value << 00 ))
{{
printf
printf (“%d
(“%d is
is negative.\n”,
negative.\n”, value)
value) ;;
}}
else
else
{{
printf
printf (“%d
(“%d is
is positive.\n”,
positive.\n”, value)
value) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
128
= versus ==
int
int aa == 22 ;;
if
if (( aa == 11 )) /*
/* semantic
semantic (logic)
(logic) error!
error! */
*/
{{
printf
printf (“a (“a isis one\n”)
one\n”) ;;
}}
else
else ifif (( aa ==== 22 ))
{{
printf
printf (“a (“a isis two\n”)
two\n”) ;;
}}
else
else
{{
printf
printf (“a (“a isis %d\n”,
%d\n”, a)
a) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
129
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 43
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
130
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
131
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
132
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 44
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
133
float ii == 3;
float f;
f; 3;
switch(f) switch(i)
switch(i) {{
switch(f) {{ case
case
case 2:
2: case 3:
3: printf("i
printf("i == 3\n");
3\n");
.... case
case 2:
2: printf("i
printf("i == 2\n");
2\n");
.... case
case 1:
1: printf("i
printf("i == 1\n");
1\n");
switch(i) }}
switch(i) {{ ii == 33
case
case 22 ** j:
j: ii == 22
....
.... ii == 11
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
134
• Without the break, the code flows into the next case.
• The last statement of each case in the switch should almost always
be a break. Exceptional case!!!
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
135
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 45
MCA-103, Programming in C
switch
Limitations Advantages
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
136
• Inform the user of the type of error that has occurred (e.g.,
“Error - invalid day.”).
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
137
switch Example
switch
switch (( day
day ))
{{
case
case 0:
0: printf
printf (“Sunday\n”)
(“Sunday\n”) ;;
break
break ;;
case
case 1:
1: printf
printf (“Monday\n”)
(“Monday\n”) ;;
break
break ;;
..
..
..
case
case 6:
6: printf
printf (“Saturday\n”)
(“Saturday\n”) ;;
break
break ;;
default:
default: printf
printf (“Error
(“Error --
-- invalid
invalid day.\n”)
day.\n”) ;;
break
break ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
138
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 46
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
139
Iterative Constructs
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
140
Topics
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
141
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 47
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
142
while ( condition )
{
statement(s)
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
143
while Loop
• The simplest C loop is the while
• Parentheses must surround the condition
• One statement forms the body of the loop
• Braces must be added if more statements are to be executed
int
int jj == 5;
5;
while(j
while(j >> 0)0) jj == 55
printf("j
printf("j == %i\n",
%i\n", j--);
j--); jj == 44
jj == 33
int
int j=5;
j=5; jj == 22
while(j
while(j >> 0)
0) {{ jj == 11
printf("j
printf("j == %i\n",
%i\n", j);
j);
j--;
j--;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
144
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 48
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
145
int
int jj == 5;
5;
user probably
intends “until j is printf("start\n");
printf("start\n");
equal to zero”, while(j
while(j ==== 0)
0)
however this is NOT printf("j
printf("j == %i\n",
%i\n", j--);
j--);
the way to write it printf("end\n");
printf("end\n");
start
start
end
end
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
146
Exercise
• Problem: Write a program that calculates the
average exam grade for a class of 10 students.
• What are the program inputs?
the exam grades
• What are the program outputs?
the average exam grade
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
147
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 49
MCA-103, Programming in C
The Algorithm
<total> = 0
<grade_counter> = 1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
148
The C Code
#include
#include <stdio.h>
<stdio.h>
int
int main
main (( ))
{{
int
int counter,
counter, grade,
grade, total,
total, average
average ;;
total
total == 00 ;;
counter
counter == 11 ;;
while
while (( counter
counter <=<= 10
10 ))
{{
printf
printf (“Enter grade :: “)
(“Enter aa grade “) ;;
scanf
scanf (“%d”,
(“%d”, &grade)
&grade) ;;
total
total == total
total ++ grade
grade ;;
counter
counter == counter
counter ++ 11 ;;
}}
average
average == total
total // 10
10 ;;
printf
printf (“Class
(“Class average
average is:
is: %d\n”,
%d\n”, average)
average) ;;
return
return 00 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
149
Versatile?
• How versatile is this program?
• It only works with class sizes of 10.
• We would like it to work with any class size.
• A better way :
Ask the user how many students are in the class.
Use that number in the condition of the while loop
and when computing the average.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
150
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 50
MCA-103, Programming in C
New Algorithm
<total> = 0
<grade_counter> = 1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
151
New C Code
#include
#include <stdio.h>
<stdio.h>
int
int main
main (( ))
{{
int
int numStudents,
numStudents, counter,
counter, grade,
grade, total,
total, average
average ;;
total
total == 00 ;;
counter
counter == 11 ;;
printf
printf (“Enter
(“Enter the
the number
number of students: “)
of students: “) ;;
scanf
scanf (“%d”,
(“%d”, &numStudents)
&numStudents) ;;
while
while (( counter
counter <=<= numStudents)
numStudents) {{
printf
printf (“Enter grade :: “)
(“Enter aa grade “) ;;
scanf
scanf (“%d”,
(“%d”, &grade)
&grade) ;;
total
total == total
total ++ grade
grade ;;
counter
counter == counter
counter ++ 11 ;;
}}
average
average == total
total // numStudents
numStudents ;;
printf
printf (“Class
(“Class average
average is:
is: %d\n”,
%d\n”, average)
average) ;;
return 0
return 0 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
152
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
153
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 51
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
154
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
155
New Algorithm
<total> = 0
<grade_counter> = 1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
156
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 52
MCA-103, Programming in C
New C Code
#include
#include <stdio.h>
<stdio.h>
int
int main
main (( ))
{{
int
int counter,
counter, grade,
grade, total,
total, average
average ;;
total
total == 00 ;;
counter
counter == 11 ;;
printf(“Enter grade: “)
printf(“Enter aa grade: “) ;; Can use a do-while loop
scanf(“%d”,
scanf(“%d”, &grade)
&grade) ;; instead
while
while (grade
(grade != != -1)
-1) {{ Covered later
total = total + grade
total = total + grade ; ;
counter
counter == counter
counter ++ 11 ;;
printf(“Enter
printf(“Enter another grade: “)
another grade: “) ;;
scanf(“%d”,
scanf(“%d”, &grade)
&grade) ;;
}}
average
average == total
total // counter
counter ;;
printf
printf (“Class
(“Class average
average is:
is: %d\n”,
%d\n”, average)
average) ;;
return
return 00 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
157
/*
/* Initializations
Initializations */
*/
total
total == 00 ;;
counter
counter == 11 ;;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
158
/*
/* Compute
Compute and
and display
display the
the average
average grade
grade */
*/
average
average == total
total // counter
counter ;;
printf
printf (“Class average is: %d\n”, average) ;;
(“Class average is: %d\n”, average)
return
return 00 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
159
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 53
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
160
Counter-Controlled Repetition
(Definite Repetition)
int
int ii == 11 ;;
while
while (( ii <=
<= 10
10 ))
{{
printf(“i
printf(“i == %d\n”,
%d\n”, i)
i) ;;
ii == ii ++ 11 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
161
while
while (( xx !=
!= yy ))
{{
printf(“x
printf(“x == %d”,
%d”, x)
x) ;;
xx == xx ++ 22 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
162
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 54
MCA-103, Programming in C
Event-Controlled Repetition
(Indefinite Repetition)
If it is NOT known in advance exactly how many times a loop
will execute, it is known as an event-controlled loop.
sum
sum == 00 ;;
printf(“Enter
printf(“Enter an
an integer
integer value:
value: “)
“) ;;
scanf(“%d”,
scanf(“%d”, &value)
&value) ;;
while
while (( value
value !=
!= -1)
-1) {{
sum
sum == sum
sum ++ value
value ;;
printf(“Enter
printf(“Enter another
another value:
value: “)
“) ;;
scanf(“%d”, &value)
scanf(“%d”, &value) ; ;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
163
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
164
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
165
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 55
MCA-103, Programming in C
}
initialization test modification
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
166
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
167
for
for (( ii == 0;
0; ii << 10;
10; ii == ii ++ 11 ))
{{
printf
printf (“%d\n”,
(“%d\n”, i)
i) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
168
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 56
MCA-103, Programming in C
for
for (( ii == 9;
9; ii >=
>= 0;
0; ii == ii -- 11 ))
{{
printf
printf (“%d\n”,
(“%d\n”, i)
i) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
169
for
for (( ii == 0;
0; ii << 10;
10; ii == ii ++ 22 ))
{{
printf
printf (“%d\n”,
(“%d\n”, i)i) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
170
int
int j;
j;
user probably
intends “until j is printf("start\n");
printf("start\n");
equal to zero”, for
for (j
(j == 5;
5; jj ==
== 0;
0; j--)
j--)
however this is NOT printf("j
printf("j == %i\n",
%i\n", j);
j);
the way to write it printf("end\n");
printf("end\n");
either! start
start
end
end
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
171
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 57
MCA-103, Programming in C
#include
#include <math.h>
<math.h>
int
int main(void)
main(void)
{{
double
double angle;
angle;
for(angle
for(angle == 0.0;
0.0; angle
angle << 3.14159;
3.14159; angle
angle +=
+= 0.2)
0.2)
printf("sine
printf("sine of
of %.1lf
%.1lf is
is %.2lf\n",
%.2lf\n", angle,
angle, sin(angle));
sin(angle));
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
172
int
int i,
i, j,
j, k;
k;
for(i
for(i == 0,
0, jj == 5,
5, kk == -1;
-1; ii << 10;
10; i++,
i++, j++,
j++, k--)
k--)
for(;
for(; ii << 10;
10; i++,
i++, j++,
j++, k--)
k--)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
173
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
174
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 58
MCA-103, Programming in C
Example
do
do
{{
printf
printf (“Enter
(“Enter aa positive number: “);
positive number: “);
scanf
scanf (“%d”,
(“%d”, &num)
&num) ;;
if
if (( num
num <=
<= 00 ))
{{
printf
printf (“\n
(“\n Try
Try again\n”)
again\n”) ;;
}}
}} while
while (( num
num <=
<= 00 )) ;;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
175
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
177
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 59
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
178
Nested Loops
• Loops may be nested (embedded) inside of each other.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
179
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
180
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 60
MCA-103, Programming in C
USE IN MODERATION.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
181
• USE IN MODERATION.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
183
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 61
MCA-103, Programming in C
Arrays
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
185
• e.g.
Sales data of multiple products
Grades of students in a class
Salaries of all employees
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
186
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 62
MCA-103, Programming in C
What is an array
• An array is a set of variables that have the same data type
and share one name.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
187
1 3 5 … 9 11 13
0 1 2 … n-3 n-2 n-1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
188
int
int m1,
m1, m2,
m2, m3….
m3….
scanf
scanf (“%d”,
(“%d”, &m1);
&m1);
scanf
scanf (“%d”,
(“%d”, &m2);
&m2);
……
scanf
scanf (“%d”,
(“%d”, &m3);
&m3);
Without
Withoutarray
array
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 63
MCA-103, Programming in C
Declaring an Array
Examples:
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
190
• The actual offset address depends on the data type of the array.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
191
Visual Representation
int
int x[4];
x[4];
Address x[2]=23;
x[2]=23; Offset / Array index
x 342901 ? 0
342903 ? 1
342905 23 2
Identifier
3
Array elements
342907 ?
Value
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
192
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 64
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
193
Array example
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void)
{{
int
int x[5];
x[5];
x[0]=23;
x[0]=23; /*
/* valid
valid */
*/
x[2.3]=5;
x[2.3]=5; /*
/* invalid:
invalid: index
index isn’t
isn’t int
int */
*/
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
194
Initializing arrays
An array is initialized
using a code block
containing comma-delimited values
The values match in position with the elements in the
array.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
195
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 65
MCA-103, Programming in C
Initializing Arrays - II
C will count the values and size the array for you
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
196
Examples
int x [ 5 ] = { 1,2,3,4,5 }; size 10 bytes
creates array with indices 0-4; element values 1-5
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
197
read into:
printf(“Sales for employee 3: “);
scanf(“%f”,&(Sales[3]));
printed:
printf(“Sales for employee 3
$%7.2f\n”,Sales[3]);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 66
MCA-103, Programming in C
Notes
Initialize I to 0
Terminate when I reaches ArraySize
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
199
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
200
printf (( “The
printf “The average
average is
is %d”
%d” ,, total
total // 55 );
);
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
201
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 67
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
202
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
203
Related Arrays - I
Consider two arrays that store
Roll numbers of students
Marks of students
Respectively.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
204
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 68
MCA-103, Programming in C
Related Arrays – II
• Suppose now we have 3 arrays for storing marks in three
different subjects.
• Write a program to store sum of marks obtained by a student in
all subjects in another array.
English 20 30 32 40 28
Mathematics 45 35 36 47 38
Science 37 38 33 40 42
Total
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
205
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
206
Strings
• Another application of Arrays is to store multiple related
characters.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
207
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 69
MCA-103, Programming in C
Processing Strings
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
208
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
209
Selection Sorting
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
210
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 70
MCA-103, Programming in C
Original Array 6 4 8 10 1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
211
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
212
Smallest
Smallest==A[J];
A[J];
for
for(K(K==1;
1;KK<<N;
N;K++)
K++)
ifif(A[K]
(A[K]<<Smallest)
Smallest) But we need location of
Smallest
Smallest==A[K];
A[K]; smallest, not its value to
swap, Change???
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
213
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 71
MCA-103, Programming in C
Binary Search
Example: when looking up name in phone book, don’t
search start to end
Approach:
Open book in middle
Determine if name in left or right half
Open that half to its middle
Determine if name in left or right of that half
Continue process until name is found (or not)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
214
Dimensionality
• Etc.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
215
Single v. Multi-dimensional
• So far, we have only looked at single dimensional arrays
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
216
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 72
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
217
Declaring 2D arrays
To declare a 1-D Array, we specify 1 size
data_type array_name [size];
Examples
int a[2][3]; /* Creates a 2x3 array of ints */
double b[5][2] /* Creates a 5x2 array of doubles */
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
218
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
219
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 73
MCA-103, Programming in C
Logical Interpretation
Syntax: BaseType Name[IntLit1][IntLit2];
Second
Dimension
0 1 2 3
0
First
1
Dimension
2
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
220
Storage Scheme
• C follows a “Row-Major” storage order
• All the data elements of an array are stored at contiguous
locations
• The elements of 0th row are followed by those of 1th and so on…
• Thus, the actual storage order (in memory) for the array depicted
in the previous slide would be
Initialising a 2D array
Columns Note:
Note: In In this
this case,
case, wewe
0 1 provide
provide one one data
data element
element
for
for the
the first
first row.
row. After
After this,
this,
Rows all
0 1 0 all remaining
remaining elements
elements in in
the
therow
rowareareinitialized
initializedto
to00
1 3 4
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
222
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 74
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
223
Examples
0 1
0 1 0
1 3 4
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
224
Processing 2D Arrays
Processing Order:
Row Major
Column Major
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
225
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 75
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
226
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
227
Syntax:
BaseType Name[IntLit1][IntLit2][IntLit3]...;
Examples:
int ThreeDPoints [100][256][256]; /* 3D array */
float TimeVolume [100][256][256][256]; /* 4D array */
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
228
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 76
MCA-103, Programming in C
• syntax:
Name[Expr1][Expr2][Expr3] /* 3D */
Name[Expr1][Expr2][Expr3][Expr4] /* 4D */
etc.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
229
Functions
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
230
Topics
• Using Predefined Functions
• Programmer-Defined Functions
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
231
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 77
MCA-103, Programming in C
Review-Structured Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
232
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
233
Functions
• A C program is made up of one or more functions, one of
which is main( ).
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
234
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 78
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
235
Functions (Contd.)
• We have used three predefined functions so far:
printf
scanf
getchar
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
236
int
int main
main (( ))
{{
printMessage
printMessage (( )) ;;
return
return 00 ;;
}}
void
void printMessage
printMessage (( void
void ))
{{
printf
printf (“Have
(“Have aa nice
nice day!\n”)
day!\n”) ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
237
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 79
MCA-103, Programming in C
Examining printMessage
#include <stdio.h>
int main ( )
{
printMessage ( ) ; function call
return 0 ;
}
void printMessage ( void ) function header
{
printf (“A message for you:\n\n”) ; function
printf (“Have a nice day!\n”) ; body
}
function definition
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
238
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
239
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
240
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 80
MCA-103, Programming in C
Prototyping
• When calling a Standard Library function, #include the file
specified in the help page(s) - this file will contain the
prototype.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
241
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
242
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
243
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 81
MCA-103, Programming in C
return_type
return_type functionName(parameter
functionName(parameter11,, .. .. .. ,,
parameter
parameternn ))
{{
variable
variable declaration(s)
declaration(s)
statement(s)
statement(s)
return
return statement
statement
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
244
Parameter Passing
• Consider a function averageTwo that calculates and returns
the average of two integers passed to it as parameters.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
246
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 82
MCA-103, Programming in C
Parameter Passing - II
Corresponding actual and formal parameters
do not have to have the same name, but they may.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
247
Local Variables
• Functions only “see” (have access to) their own local
variables. This includes main( ) .
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
248
The Rules
• A function may accept zero or as many parameters as it
needs.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
249
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 83
MCA-103, Programming in C
int
int print_table(double
print_table(double start,
start, double
double end,
end, double
double step)
step)
{{
double d;
double d;
int
int lines
lines == 1;
1;
printf("Celsius\tFarenheit\n");
printf("Celsius\tFarenheit\n");
for(d
for(d == start;
start; dd <=
<= end;
end; dd +=
+= step,
step, lines++)
lines++)
printf("%.1lf\t%.1lf\n",
printf("%.1lf\t%.1lf\n", d, d, dd ** 1.8
1.8 ++ 32);
32);
return
return lines;
lines;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
250
Writing Prototypes
Function header:
int
int print_table(double
print_table(double start,
start, double
double end,
end, double
double step)
step)
{{
int
int print_table(double
print_table(double start,
start, double
double end,
end, double
double step);
step);
int
int print_table(double
print_table(double x,
x, double
double y,
y, double
double z);
z);
int
int print_table(double,
print_table(double, double,
double, double);
double);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
251
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
252
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 84
MCA-103, Programming in C
Example Prototypes
/*
/* no
no parameters,
parameters, int
int return
return value
value */
*/
int
int get_integer(void);
get_integer(void);
/*
/* no
no parameters,
parameters, double
double return
return value
value */
*/
double
double get_double(void);
get_double(void);
/*
/* no
no parameters,
parameters, no
no return
return value
value */
*/
void
void clear_screen(void);
clear_screen(void);
/*
/* three
three int
int parameters,
parameters, int
int return
return value
value */
*/
int
int day_of_year(int
day_of_year(int day,
day, int
int month,
month, int
int year);
year);
/*
/* parameter
parameter checking
checking DISABLED,
DISABLED, double
double return
return value
value */
*/
double
double test_function();
test_function();
/*
/* short
short int
int parameter,
parameter, (default)
(default) int
int return
return value
value */
*/
transfer(short
transfer(short intint s);
s);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
253
Example Calls
int
int i;
i;
double
double d;
d;
long
long l;
l;
short
short int
intss == 5;
5;
ii == get_integer();
get_integer(); no mention of “void”
dd == get_double();
get_double(); when calling these
clear_screen();
clear_screen(); functions
ii == day_of_year(16,
day_of_year(16, 7,
7, 1969);
1969);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
254
Attributes of a variable
Data type
Name
Memory Address
Scope (code blocks where the variable is visible /
accessible)
Lifetime (duration for which the variable is retained in
memory)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
255
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 85
MCA-103, Programming in C
Rules of Visibility
int
int main(void)
main(void)
{{
int
int ii == 5,
5, j,
j, kk == 2;
2;
float compiler does not
float ff == 2.8F,
2.8F, g;
g; know about “d”
dd == 3.7;
3.7;
}}
void
void func(int
func(int v)
v)
{{
double
double d,
d, ee == 0.0,
0.0, f;
f; “i” and “g” not
available here
i++;
i++; g--;
g--;
ff == 0.0;
0.0; func’s “f” is used, not
}} main’s
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
256
Stack Example
#include
#include <stdio.h>
<stdio.h>
double
double power(int,
power(int, int);
int);
Variables
Variablesononthe
theStack
Stack
int
int main(void)
main(void) {{
int xx == 2;
(partial
(partialcontents)
contents)
int 2;
double
double d;
d;
dd == power(x,
power(x, 5);
5);
printf("%lf\n",
printf("%lf\n", d); d); 32.0 power: result
return
return 0;
0; 2 power: n
}}
5 power: p
double
double power(int
power(int n,
n, int
int p)
p) {{
double
double result
result == n;
n; ? main: d
while(--p
while(--p >> 0)
0) 2 main: x
result
result *=*= n;
n;
return
return result;
result;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
258
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 86
MCA-103, Programming in C
Storage
• C stores local variables on the stack
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
259
Memory Map
Stack
Heap
Code
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
260
Auto
• Local variables are automatically allocated on entry into, and
automatically de-allocated on exit from, a function
• Initialization: recommended
int
int table(void)
table(void)
{{
int lines auto keyword
int lines == 13;
13; redundant
auto
auto int
int columns;
columns;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
261
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 87
MCA-103, Programming in C
static
• The static keyword instructs the compiler to place a
variable into the data segment
• The data segment is permanent (static)
• A value left in a static in one call to a function will still
be there at the next call
• Initial value: 0
• Initialization: unnecessary if zero is acceptable
int
int running_total(void)
running_total(void)
{{ permanently
permanentlyallocated,
allocated,
static but
butlocal
localto
tothis
this
static int
int rows;
rows; function
function
rows++;
rows++;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
262
register
• The register keyword tells the compiler to place a
variable into a CPU register (you cannot specify which)
• If a register is unavailable the request will be ignored
• Largely redundant with optimizing compilers
• Initial value: random
• Initialization: recommended
void
voidspeedy_function(void)
speedy_function(void)
{{
register
register int
int i;i;
for(i
for(i == 0;
0; ii << 10000;
10000; i++)
i++)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
263
Global Variables
• Global variables are created by placing the
declaration outside all functions
• They are placed in the global/static data area
• Initial value: 0
• Initialization: unnecessary if zero is acceptable
• Avoid using this category of variables. Why!!!
#include
#include <stdio.h>
<stdio.h>
double
double d;
d; variable “d” is global
intmain(void) and available to all
intmain(void) functions defined
{{
below it
int
int i;
i;
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
264
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 88
MCA-103, Programming in C
extern
Example:
extern int mode;
extern void GlobalFunction (int);
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
265
By value
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
266
Call by Value
• When a function is called the parameters are copied - “call
by value”
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
267
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 89
MCA-103, Programming in C
void
void change(int
change(int v);
v);
int
int main(void){
main(void){
int
int var
var == 5;
5; the function
was not able
change(var);
change(var); to alter “var”
printf("main:
printf("main: var
var == %i\n",
%i\n", var);
var);
return
return 0;
0;
}} the function is
able to alter “v”
void
void change(int
change(int v)
v) {{
vv *=
*= 100;
100;
printf("change: change:
change: vv == 500
printf("change: vv == %i\n",
%i\n", v);
v); 500
}} main:
main: var
var == 55
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
268
Formatted Example
/*************************************************************
/*************************************************************
**
** averageTwo
averageTwo -- calculates
calculates andand returns
returns the
the average
average ofof two
two
numbers
numbers
** Inputs:
** Inputs: num1 - an integer value
num1 - an integer value
num2
num2 -- an
an integer
integer value
value
** Outputs:
** Outputs: the
the floating
floating point
point average
average ofof num1
num1 and
and num2
num2
*************************************************************/
*************************************************************/
float
float averageTwo
averageTwo (int
(int num1,
num1, int
int num2)
num2)
{{
float average
float average ;; /*
/* average of the
average of the two
two numbers
numbers */
*/
average
average == (num1
(num1 ++ num2)
num2) // 2.0
2.0 ;;
return average
return average ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
269
Using averageTwo
#include
#include <stdio.h>
<stdio.h>
float
float averageTwo
averageTwo (int
(int num1,
num1, int
int num2)
num2) ;;
int
int main
main (( ))
{{
float
float ave
ave ;;
int
int value1
value1 == 5,
5, value2
value2 == 88 ;;
ave
ave == averageTwo
averageTwo (value1,
(value1, value2)
value2) ;;
printf
printf (“%d
(“%d ++ %d
%d // 22 == %f\n”,
%f\n”, value1,
value1, value2,
value2, ave)
ave) ;;
return
return 00 ;;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
270
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 90
MCA-103, Programming in C
5 8 5 8 6.5
int int float int int float
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
271
5 8 5 8
int int float int int float
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
272
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
273
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 91
MCA-103, Programming in C
Solution…
Use Pointers.
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
274
Pointers
• Declaring pointers
• The “&” operator
• The “*” operator
• Initializing pointers
• Type mismatches
• Call by reference
• Pointers to pointers
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
275
Pointers - Why?
Using pointers allows us to:
Achieve call by reference (i.e. write functions
which change their parameters)
Handle arrays efficiently
Handle structures (records) efficiently
Create linked lists, trees, graphs etc.
Put data onto the heap
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
276
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 92
MCA-103, Programming in C
Declaring Pointers
Pointers are declared by using “*”
Declare an integer:
int
int i;
i;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
277
long
long int
int *p;
*p; /*
/* pp is
is aa pointer
pointer to
to aa long
long int
int */
*/
float*
float* pf;
pf; /*
/* pf
pf is
is aa pointer
pointer to
to aa float
float */
*/
char
char c,
c, d,
d, *pc;
*pc; /*
/* cc and
and dd are
are aa char
char
pc
pc is
is aa pointer
pointer to
to char
char */
*/
double*
double* pd,
pd, e,
e, f;
f; /*
/* pd
pd is
is pointer
pointer toto aa double
double
ee and
and ff are
are double
double */
*/
char*
char* start;
start; /*
/* start
start is
is aa pointer
pointer to
to aa char
char */
*/
char*
char* end;
end; /*
/* end
end is
is aa pointer
pointer to
to aa char
char */
*/
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
278
char
char gg == 'z';
'z';
int
int main(void)
main(void)
{{
char
char cc == 'a';
'a'; p c
char
char *p;
*p; 0x1132 'a'
0x1132
pp == &c;
&c; p g
pp == &g;
&g; 0x91A2 'z'
0x91A2
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
279
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 93
MCA-103, Programming in C
Rules
• Pointers may only point to variables of the same type as the pointer has
been declared to point to
• A pointer to an int may only point to an int
not to char, short int or long int, certainly not to float,
double or long double
• A pointer to a double may only point to a double
not to float or long double, certainly not to char or any of the
integers
• Etc......
int
int *p;
*p; /*
/* pp is
is aa pointer
pointer toto an
an int
int */
*/
long
long large
large == 27L;
27L; /*/* large
large is
is aa long
long int,
int,
initialized with 27
initialized with 27 */ */
pp == &large;
&large; /*
/* ERROR
ERROR */
*/
#include
#include <stdio.h>
<stdio.h> p c
char
char gg == 'z';
'z'; 0x1132 'a'
int 0x1132
int main(void)
main(void)
{{
char p g
char cc == 'a';
'a';
char
char *p;
*p; 0x91A2 'z'
0x91A2
pp == &c;
&c;
printf("%c\n",
printf("%c\n", *p);
*p);
pp == &g;
&g; print “what p points to”
printf("%c\n",
printf("%c\n", *p);
*p);
aa
return
return 0;
0; zz
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
281
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
282
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 94
MCA-103, Programming in C
Initialization Warning!
The following code contains a horrible error: why
#include
#include <stdio.h>
<stdio.h>
p i
int
int main(void)
main(void) ? 13
{{ 0x1212
short
short ii == 13;
13;
short
short *p;
*p;
*p
*p == 23;
23;
printf("%hi\n",
printf("%hi\n", *p);
*p);
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
283
Initialize Pointers!
Pointers are best initialized!
A pointer may be declared and initialized in a single step
short
short ii == 13;
13;
short
short *p
*p == &i;
&i;
short
short *p
*p == &i;
&i;
short
short *p
*p == &i;
&i;
short
short *p
*p == &i;
&i;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
284
NULL
• A special invalid pointer value exists #defined in various header
files, called NULL
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void)
{{
short
short ii == 13;
13;
short
short *p*p == NULL;
NULL;
if(p
if(p ==
== NULL)
NULL)
……
else
else
……
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
285
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 95
MCA-103, Programming in C
A World of Difference!
There is a great deal of difference between:
p i
int
int ii == 10,
10, jj == 14;
14;
int 0x15A0 10 14
int *p
*p == &i;
&i; 0x15A0
int
int *q
*q == &j;
&j;
q j
*p
*p == *q;
*q; 0x15A4 14
0x15A4
and:
p i
int
int ii == 10,
10, jj == 14;
14;
0x15A0 10
int
int *p
*p == &i;
&i; 0x15A4 0x15A0
int
int *q = &j;
*q = &j; q j
0x15A4 14
pp == q;
q; 0x15A4
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
286
*p 0x1210
*p == *q;
*q;
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
287
Type Mismatch *
p i
int
int ii == 10,
10, jj == 14;
14;
0x15A0 10
int
int *p
*p == &i;
&i; 0x15A0
int
int *q
*q == &j;
&j; q j
0x15A4 14
pp == *q;
*q; 0x15A4
*p
*p == q;
q;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
288
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 96
MCA-103, Programming in C
change(var);
change(var);
printf("main:
printf("main: var
var == %i\n",
%i\n", var);
var);
return the function is
return 0;
0; able to alter “v”
}}
void
voidchange(int
change(int v)
v)
{{ change:
change: vv == 500
500
vv *= main:
main: var
var == 55
*= 100;
100;
printf("change:
printf("change: vv == %i\n",
%i\n", v);
v);
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
289
Call by Reference
prototype “forces” us to pass a pointer
#include
#include <stdio.h>
<stdio.h>
void
void change(int*
change(int* p);
p);
int
int main(void)
main(void) main: var
{{
5
int
int var
var == 5;
5; 0x1120
change(&var);
change(&var);
printf("main:
printf("main: var
var == %i\n",
%i\n", var);
var); change: p
return
return 0;
0;
}} 0x1120
0x1124
void
void change(int*
change(int* p)
p)
{{
*p
*p *=
*= 100;
100;
printf("change:
printf("change: *p
*p == %i\n",
%i\n", *p);
*p);
}} change:
change: *p
*p == 500
500
main:
main: var
var == 500
500
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
290
Pointers to Pointers *
#include
#include <stdio.h>
<stdio.h> pp is a “pointer to” a
int “pointer to an int”
int main(void)
main(void)
{{
int
int ii == 16;
16; i
int
int *p
*p == &i;
&i; 16
int 0x2320
int **pp;
**pp;
p
0x2320
pp
pp == &p;
&p; 0x2324
printf("%i\n",
printf("%i\n", **pp);
**pp); pp
0x2324
return
return 0;0; 0x2328
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
291
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 97
MCA-103, Programming in C
Review
int
int main(void)
main(void)
{{ i j k
int
int ii == 10,
10, jj == 7,
7, k;
k;
int
int *p
*p == &i;
&i;
int *q = &j;
int *q = &j; p q
int
int *pp
*pp == &p;
&p;
**pp
**pp +=
+= 1;
1;
pp
*pp
*pp == &k;
&k;
**pp
**pp == *q;
*q;
ii == *q***pp;
*q***pp;
ii == *q/**pp;
*q/**pp; /*
/* headache?
headache? */;
*/;
return
return 0;
0;
}}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
292
• Each function that you define should address a well defined task.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
293
Recursion…
U1.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
294
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 98
MCA-103, Programming in C
Recursive Functions
• recursive functions: represent an activity that
can be defined in terms of itself
• Common examples
X raised to power Y is X *(X raised to power Y-1)
Factorial N is N * (Factorial N-1)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
295
Algorithm Structures
Iterative execute action in loop
Recursive reapply action to sub-problem(s)
Recursive solution:
Might lead to a simpler algorithm
The algorithm might not be as efficient, though.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
296
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
297
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 99
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
298
• Recursive solution:
1. Power (X, Y) = X * Power (X, Y-1)
2. Problem diminishing? yes.
3. Base case: Power (X, 0) = 1; base case does not have a
recursive call.
4. Can reach base case as problem diminishes? yes
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
299
Iterative definition:
Factorial(N) = N * (N-1) * (N-2) *…1 for any N > 0.
Factorial(0) = 1
Recursive solution:
1. Factorial (N) = N * Factorial(N-1)
2. Problem diminishing? yes.
3. Base case: Factorial(0) = 1; base case does not have a
recursive call.
4. Can reach base case as problem diminishes? Yes
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
300
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 100
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
301
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
303
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 101
MCA-103, Programming in C
Discuss
Sum of first n positive integers
Fibonacci Series
Recurrence Relations
Binary Search
Is Palindrome
Reversing a string
Towers of Hanoi
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
304
Function Calls
• We know that function call activity follows the LIFO
rule.
Recursive
RecursiveFunction
FunctionCalls
Calls
B X
B B B X X X C
A A A A A X X X X X A A A
M M M M M M M M M M M M M M M M M
Time
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
306
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 102
MCA-103, Programming in C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
307
M
Arrows pointing down:
=>Function call
A X A
B X C
B X
Arrows pointing up:
=>return from function
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
308
Recursion Tree
A part of function-call tree
Shows only recursive calls
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
309
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 103
MCA-103, Programming in C
Factorial (4)
Factorial (3)
Factorial (2)
Factorial (1)
Factorial (0)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
310
Fib(4)
Fib(3) Fib(2)
Fib(2) Fib(1)
Fib(1) Fib(0)
Fib(1) Fib(0)
Can
Canyou
youspot
spotthe
theproblem!!!
problem!!!
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
311
Important
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
312
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 104
MCA-103, Programming in C
• The priests were to move one disk per day, following a set of rules.
• When they had successfully completed their task, the world would
come to an end.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
313
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
314
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
315
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 105
MCA-103, Programming in C
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
316
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
317
Move 1
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
318
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 106
MCA-103, Programming in C
Move 2
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
319
Move 3
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
320
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
321
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 107
MCA-103, Programming in C
Move 1
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
322
Move 2
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
323
Move 3
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
324
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 108
MCA-103, Programming in C
Move 4
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
325
Move 5
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
326
Move 6
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
327
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 109
MCA-103, Programming in C
Move 7
A B C
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
328
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
329
General solution
The key to the solution is to notice that to move any disk, we must first
move the smaller disks off of it, thus a recursive definition
To move 1 disk
Move 1 disk from start tower to destination tower
To move 2 disks
Move smaller disk from start tower to intermediate tower
Move larger disk from start tower to final tower
Move smaller disk from intermediate tower to final tower
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
330
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 110
MCA-103, Programming in C
General solution - II
To move n disks
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
331
Algorithm
Hanoi (N, Start, Final, Intermediate)
Begin
if N IS NOT 0
Hanoi (N-1, Start, Intermediate, Final)
Move N from Start to Final
Hanoi (N-1, Intermediate, Final, Start)
End;
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
332
Recursive solution:
1. Decide a pivot element in the array P with index Pindex.
2. Partition the array into three parts: elements < P(call it S1),
P , and elements >P (call it S2).
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
333
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 111
MCA-103, Programming in C
5. If there are fewer than k-1 elements in S1, then kth element
is S2 = A[Pindex+1 -L]. Since we have eliminates Pindex-
First elements, now we are looking for (k-(Pindex-
First+1))th element in S2.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1.
334
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal U1 112