SlideShare a Scribd company logo
2
Program
A set of directions telling a computer exactly what
to do.
Programming languages
Languages for specifying sequences of directions
to a computer.
Algorithm
A sequence of language independent steps
which may be followed to solve a problem.
Flowchart
Diagrammatic representation of step for solving
the given problem.
 Programming is controlling: computer does exactly what
you tell it to.
 Programming is teaching: computer can only “learn” to do
new things if you tell it how.
 Programming is problem solving: always trying to make
computer do something useful — i.e., finding an optimal
travel route.
 Programming is creative: must find a good solution out of
many possibilities.
 Programming is modelling: describe salient (relevant)
properties and behaviours of a system of components.
 Programming is abstraction: identify important features
without getting lost in detail.
 Programming is concrete: must provide detailed
instructions to complete task
3
Many Aspects of Programming
• Machine language:
It is computer’s native language having a sequence of zeroes
and ones (binary). Different computers understand different
sequences. Thus, hard for humans to understand: e.g. 0101001...
• Assembly language:
It uses mnemonics for machine language. In this each instruction
is minimal but still hard for humans to understand:
e.g. ADD AH, BL
• High-level languages:
FORTRAN, Pascal, BASIC, C, C++, Java, etc.
Each instruction composed of many low-level instructions,
closer to English. It is easier to read and understand:
e.g. hypot = sqrt(opp*opp + adj * adj);
10
Programming Languages
Errors
13
 Debugging is the process of detecting and fixing
errors found in a program.
 Syntactic errors are caused by giving the compiler
a program it cannot recognize.
 Logical errors come from programs that compile
correctly but fail to execute as expected.
 Programs must be designed carefully and tested
thoroughly to ensure that neither error will occur.
‘C’
• Implements basic programming languages
concepts.
• Structured programming language.
• Developments of other PL requires core C
elements.
• Unix, Linux and Windows in C.
• Cellular phones and palmtop softwares.
• Gaming frameworks.
• Hardware devices interaction with max
performance.
Alphabets,
Digits,
Special
Symbols.
Constants,
Variables,
And
Keywords
Instructions
Program.
C Constants.
• Primary Constants.
Integer Constants.
Real Constants.
Character Constants.
• Secondary Constants.
Array.
Pointer.
Structures and Unions.
Enum.
• Integer Constants.
e.g. 426
+756
-588 etc.
• Character Constants.
e.g. ‘E’
‘h’
‘=‘
‘8’
• Real Constants.
+3.211e-4
5.6e4
e.g. 488.22
+85.23
-11.20
Data types declaration.
int a; /* General declaration */
int a = 10; /* Valued Declaration */
float b = 12.6;
float b;
char c;
char c = ‘y’;
Maximum values of Data Types.
• int requires 2 bytes to store in memory.
-32768 to 32767.
• float requires 4 bytes to store.
-3.4e38 to 3.4e38.
• char requires 1 byte to store.
A….Z and a….z also special symbols.
• long int requires 4 bytes to store.
-2147483648 to 2147483647.
• double requires 8 bytes to store.
-1.7e308 to 1.7e308.
• long double requires 10 bytes to store.
-1.7e4932 to 1.7e4932.
Giving variable names (identifiers).
• ‘C’ is a case-sensitive language.
means ‘a’ R ‘A’.
• All the alphabets are allowed.
• All numbers are allowed but not at the
start.
e.g char a9, thyy; /* Valid */
char 5abc; /* Invalid */
• Only special symbol _ (under score) is
allowed. e.g. int min_max;
Keywords.
auto break case char const
continue default do double else
enum extern float for goto
if long register return short
signed sizeof static struct switch
typedef union unsigned void while
volatile near far asm
Operators.
• Numerial operators.
• Logical operators.
• Relational operators.
• Conditional operators.
• Bitwise operators.
Numerical operators.
+ - * / % =
---------------------------------------------
e.g. int a, y = 10, x = 12;
float b;
a = y + 10;
b = x / 2;
a = a – b;
Relational operators.
<= == !=
> < >=
Logical operators.
&& ||
Conditional operators.
? :
Boolean operators.
& | ~ ^
Expression and Statements.
int a = 10, j = 26;
float r = 5.22, t = 2.66 + 45.2 * 2;
float b = 1.02 , c = b / 2 + 5.2;
int d, e, f, g;
d = e = f= g = 50;
float alpha = 23.001, beta = 892.00;
float delta = alpha * beta / 3.2 – alpha;
char h, i ;
h = ‘D’;
I = h;
Hierarchy of operations.
int i;
i = 5 * 6 – 8 + 9 – (43 + 2) /5 – 5;
i = 30 – 8 + 9 – 45/5 – 5;
i = 30 – 8 + 9 – 9 – 5;
i = 22 + 0 – 5;
i = 17;
First ‘C’ Program.
#include<stdio.h>
main()
{
int i = 10, j = 12;
float k, m = 12.6;
k = (i + j) / m;
printf(“Input : %d %d %f”, i, j, m);
printf(“nOutput : %f ”, k);
}
Input : 10 12 12.600000
Output : 1.746032
Basic I/O statements.
• printf.
printf(“<formal string>”,<list of variables>);
e.g. printf(“Hello world”);
int i = 15;
printf(“Value of i is : %d”, i );
 %d – integer value.
 %f – float value.
 %c – character value
printf(“%d %d %d”, 3, 3+5, a+b*c);
Basic I/O statements.
• scanf.
It accepts values from user in the form of
int / float / char / long / double.
e.g. int j,
char m;
float k;
scanf(“%d%f%c”, &j, &k, &m);
Compilation and Execution
• Integrated Development Environment
(IDE).
editor + compiler.
• Compiling ‘C’ program
F9 / Alt F9 – Compiling.
Ctrl F9 – Executing.
Alt F5 – Watching output.
Control Statements in
‘C'
Control Statements
• Selection Statements
–Using if and if...else
–Nested if Statements
–Using switch Statements
–Conditional Operator
• Repetition Statements
–Looping: while, do-while, and for
–Nested loops
–Using break and continue
Selection Statements
• if Statements
• switch Statements
• Conditional Operators
if Statements
if (Condition)
{
statement(s);
}
Example:
if (i S 0)
{
printf("i = %d “, i );
}
Condition ?
statement1
statement2
statement3
true
false
Caution
Adding a semicolon at the end of an if clause is a
common mistake.
if (radius S= 0);
{
area = radius*radius*PI;
printf ("The area for the circle
of radius %d is =%d“, radius,area);
}
This mistake is hard to find, because it is neither
a compilation error nor a runtime error, it is a logic error.
This error often occurs when you use the next-line block
style.
Wrong
The if...else Statement
if (condition)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}
if...else Example
if (radius S= 0)
{
area = radius*radius*PI;
printf("The area for the circle of radius
%d is =%d" , radius, area);
}
else
{
printf(“Radius can not be Negative ");
}
Multiple Alternative if Statements
if (score S= 90)
grade = ‘A';
else
if (score S= 80)
grade = ‘B';
else
if (score S= 70)
grade = ‘C';
else
if (score S= 60)
grade = ‘D';
else
grade = ‘F';
if (score S= 90)
grade = ‘A';
else if (score S= 80)
grade = ‘B';
else if (score S= 70)
grade = ‘C';
else if (score S= 60)
grade = ‘D';
else
grade = ‘F';
Note
The else clause matches the most recent if clause in the same block.
For example, the following statement
int i = 1; int j = 2; int k = 3;
if (i S j)
if (i S k)
printf("A");
else
printf("B");
Other combination is :
int i = 1; int j = 2; int k = 3;
if (i < j)
{
if (i S k)
printf("A");
}
else
printf("B");
switch Statements
switch (variable-name)
{
case value1:
Execute this;
break;
case value2:
Execute this;
break;
case valueN:
Execute this;
break;
default:
Execute this;
}
switch Statement Flow Chart
Variable
value1
default
Next
Statement
Execute this; Execute this; Execute this; Execute this;
value2
valueN
switch Statement Rules
The switch-expression must yield a value of char or
int type and must always be enclosed in parentheses.
The value1, ..., and valueN must have the same data type
as the value of the switch-expression. The resulting
statements in the case statement are executed when the
value in the case statement matches the value of the
switch-expression. (The case statements are executed in
sequential order.)
The keyword break is optional, but it should be used at
the end of each case in order to terminate the remainder
of the switch statement.
If the break statement is not present, the next case
statement will be executed.
switch Statement Rules,
cont…..
The default case, which is optional, can be
used to perform actions when none of the specified
cases is true.
The order of the cases (including the default
case) does not matter. However, it is a good
programming style to follow the logical sequence of
the cases and place the default case at the end.
Caution
Do not forget to use a break statement when one is
needed. For example, the following code always
displays Wrong number of years regardless of what
num is. Suppose the num is 15. The statement
rate = 8.50 is executed, then the statement
rate = 9.0, and finally the statement,
printf("Wrong number of years").
switch (num) {
case 7: rate = 7.25;
case 15: rate = 8.50;
case 30: rate = 9.0;
default: printlf("Wrong number of years");
}
Example: switch-case
int w = 20;
switch(w)
{
case 10: printf(“First”);
break;
case 20: printf(“Second”);
case 30:
break;
printf(“Third”);
break;
default: printf(“Wrong value…”);
}
Conditional Operator
(condition) ? exp1 : exp2
if (x S 0) y = 1
else y = -1;
is equivalent to
y = (x S 0) ? 1 : -1;
Ternary operator
Conditional Operator
if (num % 2 == 0)
printf(“%d is even”,num);
else
printf(“%d is odd”,num);
(num%2==0)?printf(“even”):printf(“odd”);
Repetitions
while Loops
do-while Loops
for Loops
break and continue
while Loop Flow Chart
false
true
Statement(s)
Next
Statement
Continuation
condition?
while (continuation-condition)
{
// loop-body;
}
while Loop Flow Chart, cont.
int i = 0;
while (i < 100)
{
printf("Welcome to C!");
i++;
}
false
true
printf("Welcome to C!");
i++;
Next
Statement
(i < 100)
i = 0;
do-while Loop
false
true
Statement(s)
Next
Statement
Continue
condition?
do
{
// Loop body;
} while (continue-condition);
for Loop
Initialization
false
true
Increment
Decrement
Statement(s)
(loop-body)
Next
Statement
Continuation
condition?
for (initialization; condition; increment/decrement)
{
//loop body;
}
for Loop Example
i<100?
faIse
i++
i = 0
Next
Statem ent
true
printf(“W elcom e to C”);
int i;
for (i=0;i<100;i++)
{
printf("Welcome to C");
}
Caution
Adding a semicolon at the end of the for
clause before the loop body is a common
mistake, as shown below:
for (int i=0; i<10; i++);
{
printf("i is %d“,i);
}
Wrong
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i<10);
{
printf("i is %d“,i);
i++;
}
In the case of the do loop, the following
semicolon is needed to end the loop.
int i=0;
do
{
printf("i is %d“,i);
i++;
} while (i<10);
Wrong
Correct
Which Loop to Use?
The three forms of loop statements, while, do, and
for, are expressively equivalent; that is, you can write a
loop in any of these three forms.
It is recommend that you use the one that is most
intuitive and comfortable for you. In general, a for loop
may be used if the number of repetitions is known, as, for
example, when you need to print a message 100 times. A
while loop may be used if the number of repetitions is not
known, as in the case of reading the numbers until the
input is 0. A do-while loop can be used to replace a while
loop if the loop body has to be executed before testing the
continuation condition.
The break Keyword
false
Statement(s)
Next
Statement
Continuation
condition?
true
Statement(s)
break
Example: break statement
int a = 10;
while( a S= 0 )
{
printf(“nValue of a = %d”,a);
a--;
if(a==5)
break;
}
Output:
Value of a = 10
Value of a = 9
Value of a = 8
Value of a = 7
Value of a = 6
The continue Keyword
false
Statement(s)
Next
Statement
Continue
condition?
true
Statement(s)
continue
Example: continue statement
int a = 6;
while( a S= 0 )
{
a--;
if(a==3)
continue;
printf(“nValue of a = %d”,a);
}
Output:
Value of a = 5
Value of a = 4
Value of a = 2
Value of a = 1
Value of a = 0
Arrays
22-Jul-2008 2
 Introducing Arrays
 Declaring Array Variables, Creating Arrays,
and Initializing Arrays
 Passing Arrays to Methods
 Copying Arrays
 Multidimensional Arrays
 Search and Sorting Methods
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
num [0]
num [1]
num [2]
num [3]
num [4]
num [5]
num [6]
num [7]
num [8]
num [9]
int num[10];
num reference
An Array of 10
Elements
of type int
22-Jul-2008 3
Declaring Array Variables
22-Jul-2008 4
datatype arrayname[index];
Example:
int list[10];
char num[15];
float hat[20];
Creating Arrays
22-Jul-2008 5
datatype array-name[size];
Example:
int num[10];
num[0] references the first element in the
array.
num[9] references the last element in the
array.
Declaring and Creating
in One Step
22-Jul-2008 6
 datatype arrayname[arraySize]=
{values seperated by comma};
Example :
char c[5] = {‘a’,’F’,’4’,’’=‘,’n’};
int i[4] = {12,15,0,2};
The Length of Arrays
22-Jul-2008 7
Once an array is created, its size is fixed. It
cannot be changed.
For example,
int arr[10];
You can not insert any number to arr[11]
location because it is not initialized.
Initializing Arrays
22-Jul-2008 8
Declaring, creating, initializing in one step:
float hat[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one
statement.
Declaring, creating, initializing
Using the Shorthand Notation
22-Jul-2008 9
float list[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to
the following statements:
float list[4];
list[0] = 1.9;
list[1] = 2.9;
list[2] = 3.4;
list[3] = 3.5;
CAUTION
22-Jul-2008 10
Using the shorthand notation, you have to
declare, create, and initialize the array all
in one statement. Splitting it would cause
a syntax error. For example, the following
is wrong:
float list;
list = {1.9, 2.9, 3.4, 3.5};
Example: Copying Arrays
22-Jul-2008 11
The program simply creates two
arrays and attempts to copy one to the
other, using an assignment statement.
Copying Arrays
Contents
of list1
Contents
of list2
list1
list2
Before the assignment
list2 = list1;
Contents
of list1
Contents
of list2
After the assignment
list2 = list1;
list1
list2
Garbage
22-Jul-2008 12
Copying Arrays
22-Jul-2008 13
With direct assignment:
int array1[5] = {2, 3, 1, 5, 10};
int array2[5];
array2 = array1;
Multidimensional Arrays
22-Jul-2008 14
Declaring Variables of Multidimensional Arrays and
Creating Multidimensional Arrays
int matrix[10][10];
for (i=0; i<10; i++)
for (j=0; j<10; j++)
{
matrix[i][j] = i * j;
}
float mat[5][5];
Multidimensional Array Illustration
0 1 2 3 4
0
7
0 1 2 3 4
1
2
3
4
0
1
2
3
4
matrix[2][1] = 7
int matrix[5][5];
3
0 1 2
0
1
2
int[][] array ={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
1 2 3
4 5 6
7 8 9
10 11 12
22-Jul-2008 15
Shorthand Notations
22-Jul-2008 16
You can also use a shorthand notation to declare, create and
initialize a two-dimensional array. For example,
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
This is equivalent to the following statements:
array[0][0]
array[1][0]
array[2][0]
array[3][0]
= 1; array[0][1]
= 4; array[1][1]
= 7; array[2][1]
= 10; array[3][1] = 11; array[3][2]
= 2; array[0][2] = 3;
= 5; array[1][2] = 6;
= 8; array[2][2] = 9;
= 12;
17
Ragged Arrays
Each row in a two-dimensional array is
itself an array. So, the rows can have
different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
22-Jul-2008
22-Jul-2008 18
Exercise : Bubble Sort
int i[] = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
Pass 1: 2, 5, 4, 8, 1, 6, 9
Pass 2: 2, 4, 5, 1, 6, 8, 9
Pass 3: 2, 4, 1, 5, 6, 8, 9
Pass 4: 2, 1, 4, 5, 6, 8, 9
Pass 5: 1, 2, 4, 5, 6, 8, 9
Pass 6: 1, 2, 4, 5, 6, 8, 9
What is a Function ?
• Function is a self contained block of statements
that perform a coherent task of some kind.
• Every C program can be a thought of the
collection of functions.
• main( ) is also a function.
Types of Functions.
• Library functions.
These are the in-built functions of ‘C’ library.
These are already defined in header files.
e.g. printf( ); is a function which is used to print
at output. It is defined in ‘stdio.h’ file .
• User defined functions.
Programmer can create their own function in C
to perform specific task.
User defined functions.
• e.g.
#include<stdio.h>
main( )
{
message( );
}
message( )
{
printf(“Hello”);
}
Declaration of many functions.
#include<stdio.h>
main( )
{
printf(“I am in main”);
poly( );
engg( );
agri( );
}
poly( )
{
printf(“I am in polytechnic”);
}
engg( )
{
printf(“I am in engineering”);
}
agri( )
{
printf(“I am in agri”);
}
Some conclusions.
• Any C Program must contain at least one function.
• If program contains only one function it must be
main( ).
• There is no limit on the number of functions
present in a C program.
• Each function in a program is called in the
sequence specified by functions call in main( ).
• After each function has done its thing, control
returns to main( ). When main( ) run out of
function calls program ends.
Summarization.
• C Program is a collection of one or more functions.
• A function gets called when its name is followed by a
semicolon.
e.g. main( )
{
fun( );
}
fun( )
{
statement1;
statement2;
statement3;
}
Summarization Contd……….
• Any function can be called by any other function.
e.g. main( )
{
printf(“I am in main.”);
fun( );
}
fun( )
{
printf(“I am in fun.”);
main( );
}
This will run in infinity.
Summarization Contd……….
• A function can be called by number of times.
e.g. main( )
{
printf(“I am in main.”);
fun( );
fun( );
fun( );
}
fun( )
{
printf(“I am in fun.”);
}
Summarization Contd……….
• A function can call itself, it is called as a
‘recursion’.
e.g. main ( )
{
printf(“I am in main”);
main( );
}
• A function can be called from another function but
can not be defined in another function. It should
be defined outside of the main.
Why use functions ?
• Writing functions avoids rewriting of the same
code again and again in the program.
• Using a function it becomes easier to write
program to keep track of what they are doing.
Passing values to functions.
The values that we pass to the function called as
function arguments.
e.g. main( )
{
int i=10, j=12, k=20;
calsum(i,j,k);
}
calsum(int x, int y, int z)
{
printf(“Sum is : %d”,(x+y+z));
} i, j, k are actual arguments
x, y, z are formal arguments.
Returning a value.
• The keyword ‘return’ to used to return value from function which
is present in the parenthesis of return.
• On executing return statement it immediately transfers control
back to the main program.
e.g. main( )
{
int a = 30, j = 14;
int k;
k = addin(a, j);
printf(“%d”, k);
}
int addin(int x, int y)
{
int z;
z = (x + y) +1;
return(z);
}
return
• There is no restriction of return statements in a function.
• Whenever the control returns from the function some value is
definitely returned. It should be accepted in the calling program.
e.g. int sum;
sum = calsum(a,b,c);
here the value returned by calsum must be of type int.
• Some valid return statements.
/*a is a variable name */
return a;
return (23);
return (15.32);
return (‘v’);
return;
• If you are not returning any value from a function they it should
be declared as void. (void is a keyword).
e.g. void display( )
display is not returning any value.
Function declaration and Prototype.
Any C function by default returns and integer value. More specifically,
whenever a call is made to a function, the compiler assumes that this
function would return value of type int.
Function prototype :
#include<stdio.h>
int addin(int, int);
void main( )
{
statements;
statements;
}
int addin(int a, int b)
{
statements;
}
Function
prototype.
Structures
 In general, we can call a structure is
a collection of different types of data.
 A Structure contains number of data
types grouped together. These data
types may be or may not be of same
data type.
‘C’ implementation of Structure.
• The keyword ‘struct’ is used for creating a
structure.
Syntax:
struct structure-name
{
datatype1 varname1;
datatype1 varname2;
datatype1 varname3;
};
creating the object of structure:
struct structure-name var1, var2, var3;
Accessing structure elements.
. (dot operator) is used to access individual structure element.
e.g. struct list
{
int roll;
char name[10];
float marks;
};
struct list a , b , c;
a.roll – is the integer element of structure a.
a.name – is char array element of structure a
b.marks – is a float element of structure b.
a.marks – is a float element of structure b.
scanf(“%d”, &b.roll); this statement can accept an integer
roll of structure b from user. This is applied to all the
elements of a structure.
How structure elements are stored.
e.g. struct book
{
char name;
int pages;
float price;
};
struct book z = {‘s’, 125, 90.0};
Here value of :
z.name is ‘s’.
z.pages is 125 and z.price is 90.0
Memory map:
‘s’ 125 90.0
z.name z.pages z.price
Valid declaration.
struct list {
int roll;
char name[10];
float marks;
};
struct list a , b , c;
It is equivalent to :
struct list {
int roll;
char name[10];
float marks;
}a, b, c;
Remember:
 The closing bracket of structure type
declaration must be followed by a
semicolon.
 Usually structure declaration appears at
the top of the source code file before any
variables and structures are defined.
 Accessing single variable in a structures
must be followed by a . (dot operator).
Example: Creating a student database of 3 students.
#include<stdio.h>
void main( )
{
struct student {
int roll;
char name[10];
float marks;
} a, b, c;
printf(“Enter all information of students:” );
scanf(“%d %s %f”, &a.roll, a.name, &a.marks);
scanf(“%d %s %f”, &b.roll, b.name, &b.marks);
scanf(“%d %s %f”, &c.roll, c.name, &c.marks);
printf(“You entered this information:”);
printf(“n%d %s %f”, a.roll, a.name, a.marks);
printf(“n%d %s %f”, b.roll, b.name, b.marks);
printf(“n%d %s %f”, c.roll, c.name, c.marks);
}
Array of structures.
 We can create the array of structures. Thus, we can use the same
structure for more than one variables which adds more flexibility
in your program. Let’s view the previous example.
#include<stdio.h>
void main( )
{
struct student {
int roll;
char name[10];
float marks;
} a[10];
int j;
printf(“Enter all information of students:” );
for(j = 0 ; j < 10 ; j++)
scanf(“%d %s %f”, &a.roll[i], a.name[i], &a.marks[i]);
for(j = 0 ; j < 10 ; j++)
printf(“n%d %s %f”, a.roll[i], a.name[i], a.marks[i]);
}
Memory map for arrays.
a[i].roll a[i].nam e a[i].marks
8
9
i
0
1
2
a[5].roll
3
4
5
6
7
a[9].name
Pointers in C
Pointer Variables
• Pointers are often referred to as references
• The value in a pointer variable is interpreted
as a memory address
• Usually, pointer variables hold references to
specific kinds of data (e.g.: address of an int,
address of a char, etc)
int * p;
char * chptr;
/* variable p can hold the address of a
memory location that contains an int */
/* chptr can hold the address of a
memory location that contains a char */
Dereferencing Operator
• The expression *p denotes the memory cell
to which p points
• Here, * is called the dereferencing operator
• Be careful not to dereference a pointer that
has not yet been initialized:
int *p; p ?
*p = 7;
Address in p could be
any memory location
Attempt to put a value into an unknown
memory location will result in a run-time
error, or worse, a logic error
• To help keep things straight, it’s useful to
pretend there are parentheses in the pointer
declarations:
• (int *) p; means that p is of type int* (i.e.:
that is, p is a pointer to an int location)
• int (*p); means that location *p has the
potential to hold an int value
• Don’t actually write declarations this way
The Address Operator
• The expression &x denotes the address of a
variable x
• Here, & is called the address operator or the
reference operator
int x, *p;
p ?
x ?
p = &x;
*p = 4;
p
x ?
p
x 4 Value of x has
been changed
Value of p has
been changed
The Null Pointer
• The null pointer is a special constant which
is used to explicitly indicate that a pointer
does not point anywhere
• NULL is defined in the standard library
<stdlib.h>
• In diagrams, indicated as one of:
NULL .
Pointer Example
int *p, x, y, *q = NULL;
p = &x;
*p = 4;
p x
(or *p)
y
4 ?
p = &y;
p x y
4 ?
*p is now another name for y
q
q
.
.
*p = 8;
p x y
4 8
q = p;
p x y
4 8
q
*p or *q
q
*p
.
p = &x;
p x y
4 8
*q
*p = *q;
p x y
8
8
q
*p
q
*p
*q
8
Arrays of Pointers
• It’s possible to have arrays of pointers
• The array name is a pointer to an array of
pointers:
int j = 6; k = 4;
int * arrayOfPtr[4];
j k
6 4
arrayOfPtr
? ? ? ?
0 1 2 3
Pointers in array are
not initialized yet
arrayOfPtr[0] = &k;
arrayOfPtr[2]=&j;
j k
6 4
arrayOfPtr
?
0 1 2 3
?
Array Names as Pointers
• Array name is really a pointer to the first
element in the array
• Consider the declaration int arr[5];
• arr has the same meaning as &arr[0]
• *arr has the same meaning as arr[0]
• Indexing into an array is really a pointer
dereferencing operation
Generic Pointers
• Sometimes we need to use pointer variables
that aren’t associated with a specific data
type
• In C, these generic pointers simply hold
memory addresses, and are referred to as
pointers to void:
void* ptr;
• Any kind of pointer can be stored in a variable
whose type is void*
• If we know that a value in a pointer p of type
void* is really of a specific pointer type x, and
we want to treat the value p points to as a
value of type x, we have to cast the pointer to
type x
Generic Pointer Example
void * arr[6];
int j = 7;
double k = 5.9;
int * n;
double x;
j
arr
x
n
k
? ? ? ? ? ?
?
? 7
5.9
0 1 2 3 4 5
arr[2] = (void*)&j; /*cast is okay, but not
needed here */
j
arr
x
n
k
?
? 7
5.9
? ? ? ? ?
0 1 2 3 4 5
arr[5] = &k; /* cast not needed, but
could be used */
j
arr
x
n
k
? ? ? ?
?
? 7
5.9
0 1 2 3 4 5
n = (int*)arr[2]; /* cast is required here */
j
arr
x
n
k
0 1 2 3 4 5
? ? ? ?
?
7
5.9
x = *((double*)arr[5]); /* cast is required here */
j
arr
x
n
k
0 1 2 3 4 5
? ? ? ?
5.9
7
5.9
File Handling in ‘C’
File.
 A file is used for permanent storage.
Opening a file.
FILE *fp;
fp is a file pointer variable which contains address of structure FILE
which is defined in stdio.h
fopen(“file-name”,”opening mode”);
file-name – name of the file to open.
opening-mode – mode in which is file is to be opened. This may be:
r – reading mode.
w – writing mode.
a – appending mode.
e.g. fopen(“abc.txt”,”r”);
it will open file in reading mode. Means we can only read
its data.
Creating new file.
fopen(“abc.txt”, “w”);
it will open file in writing mode means you can only write
to this file. If name of the file file is not existing then it
creates new blank file.
caution: if you create an existing file in writing mode,
then its previous contents gets destroyed.
fopen(“abc.txt”, “a”);
it will open the existing file in appending mode. In this
case the previous contents doesn’t get destroyed you
can only append new data to this file.
Reading from a file.
fscanf is used to read the contents from the file.
Syntax:
fscanf(file-pointer,”access-specifier”,variables);
e.g. FILE *fp;
char name[10];
fp = fopen(“abc.txt”, “r”);
fscanf(fp,”%s”, name);
printf(“%s”, name);
File
name
name
fscanf
Print to output
Writing to a file
fprintf is used to write the contents to the file.
Syntax:
fscanf(file-pointer,”access-specifier”,variables);
e.g. FILE *fp;
char name[10];
fp = fopen(“abc.txt”, “w”);
fprintf(fp,”Your name : KKWP”);
This will print ‘Your name : KKWP’
in the file name ‘abc.txt’.
Some file operations.
fclose(file-pointer);
when you open a file using fopen() is must be closed
using this statement after use.
e.g. fclose(fp);
Checking exiting file:
if(fp==NULL)
then file is not existing.
feof(file-pointer)
it checks that end of file is reached or not. If yes returns
1 else false.
e.g. while(feof(fp))
fscanf(fp,”%s”, name);

More Related Content

Similar to Dr Mrs A A Miraje C Programming PPT.pptx

C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xiiSyed Zaid Irshad
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topicsveningstonk
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computerShankar Gangaju
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariTHE NORTHCAP UNIVERSITY
 
java or oops class not in kerala polytechnic 4rth semester nots j
java or oops class not in kerala polytechnic  4rth semester nots jjava or oops class not in kerala polytechnic  4rth semester nots j
java or oops class not in kerala polytechnic 4rth semester nots jishorishore
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.comGreen Ecosystem
 

Similar to Dr Mrs A A Miraje C Programming PPT.pptx (20)

C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
Learn C
Learn CLearn C
Learn C
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
java or oops class not in kerala polytechnic 4rth semester nots j
java or oops class not in kerala polytechnic  4rth semester nots jjava or oops class not in kerala polytechnic  4rth semester nots j
java or oops class not in kerala polytechnic 4rth semester nots j
 
C operators
C operatorsC operators
C operators
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 

Recently uploaded

Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringC Sai Kiran
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageRCC Institute of Information Technology
 
Pharmacy management system project report..pdf
Pharmacy management system project report..pdfPharmacy management system project report..pdf
Pharmacy management system project report..pdfKamal Acharya
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsAtif Razi
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-IVigneshvaranMech
 
retail automation billing system ppt.pptx
retail automation billing system ppt.pptxretail automation billing system ppt.pptx
retail automation billing system ppt.pptxfaamieahmd
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
 
Top 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering ScientistTop 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering Scientistgettygaming1
 
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringKIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringDr. Radhey Shyam
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxVishalDeshpande27
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectRased Khan
 
AI for workflow automation Use cases applications benefits and development.pdf
AI for workflow automation Use cases applications benefits and development.pdfAI for workflow automation Use cases applications benefits and development.pdf
AI for workflow automation Use cases applications benefits and development.pdfmahaffeycheryld
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfKamal Acharya
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdfKamal Acharya
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdfKamal Acharya
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdfKamal Acharya
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdfKamal Acharya
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturingssuser0811ec
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdfKamal Acharya
 

Recently uploaded (20)

Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
Pharmacy management system project report..pdf
Pharmacy management system project report..pdfPharmacy management system project report..pdf
Pharmacy management system project report..pdf
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
 
retail automation billing system ppt.pptx
retail automation billing system ppt.pptxretail automation billing system ppt.pptx
retail automation billing system ppt.pptx
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Top 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering ScientistTop 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering Scientist
 
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringKIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker project
 
AI for workflow automation Use cases applications benefits and development.pdf
AI for workflow automation Use cases applications benefits and development.pdfAI for workflow automation Use cases applications benefits and development.pdf
AI for workflow automation Use cases applications benefits and development.pdf
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdf
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturing
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 

Dr Mrs A A Miraje C Programming PPT.pptx

  • 1. 2 Program A set of directions telling a computer exactly what to do. Programming languages Languages for specifying sequences of directions to a computer. Algorithm A sequence of language independent steps which may be followed to solve a problem. Flowchart Diagrammatic representation of step for solving the given problem.
  • 2.  Programming is controlling: computer does exactly what you tell it to.  Programming is teaching: computer can only “learn” to do new things if you tell it how.  Programming is problem solving: always trying to make computer do something useful — i.e., finding an optimal travel route.  Programming is creative: must find a good solution out of many possibilities.  Programming is modelling: describe salient (relevant) properties and behaviours of a system of components.  Programming is abstraction: identify important features without getting lost in detail.  Programming is concrete: must provide detailed instructions to complete task 3 Many Aspects of Programming
  • 3. • Machine language: It is computer’s native language having a sequence of zeroes and ones (binary). Different computers understand different sequences. Thus, hard for humans to understand: e.g. 0101001... • Assembly language: It uses mnemonics for machine language. In this each instruction is minimal but still hard for humans to understand: e.g. ADD AH, BL • High-level languages: FORTRAN, Pascal, BASIC, C, C++, Java, etc. Each instruction composed of many low-level instructions, closer to English. It is easier to read and understand: e.g. hypot = sqrt(opp*opp + adj * adj); 10 Programming Languages
  • 4. Errors 13  Debugging is the process of detecting and fixing errors found in a program.  Syntactic errors are caused by giving the compiler a program it cannot recognize.  Logical errors come from programs that compile correctly but fail to execute as expected.  Programs must be designed carefully and tested thoroughly to ensure that neither error will occur.
  • 5. ‘C’ • Implements basic programming languages concepts. • Structured programming language. • Developments of other PL requires core C elements. • Unix, Linux and Windows in C. • Cellular phones and palmtop softwares. • Gaming frameworks. • Hardware devices interaction with max performance.
  • 7. C Constants. • Primary Constants. Integer Constants. Real Constants. Character Constants. • Secondary Constants. Array. Pointer. Structures and Unions. Enum.
  • 8. • Integer Constants. e.g. 426 +756 -588 etc. • Character Constants. e.g. ‘E’ ‘h’ ‘=‘ ‘8’ • Real Constants. +3.211e-4 5.6e4 e.g. 488.22 +85.23 -11.20
  • 9. Data types declaration. int a; /* General declaration */ int a = 10; /* Valued Declaration */ float b = 12.6; float b; char c; char c = ‘y’;
  • 10. Maximum values of Data Types. • int requires 2 bytes to store in memory. -32768 to 32767. • float requires 4 bytes to store. -3.4e38 to 3.4e38. • char requires 1 byte to store. A….Z and a….z also special symbols. • long int requires 4 bytes to store. -2147483648 to 2147483647. • double requires 8 bytes to store. -1.7e308 to 1.7e308. • long double requires 10 bytes to store. -1.7e4932 to 1.7e4932.
  • 11. Giving variable names (identifiers). • ‘C’ is a case-sensitive language. means ‘a’ R ‘A’. • All the alphabets are allowed. • All numbers are allowed but not at the start. e.g char a9, thyy; /* Valid */ char 5abc; /* Invalid */ • Only special symbol _ (under score) is allowed. e.g. int min_max;
  • 12. Keywords. auto break case char const continue default do double else enum extern float for goto if long register return short signed sizeof static struct switch typedef union unsigned void while volatile near far asm
  • 13. Operators. • Numerial operators. • Logical operators. • Relational operators. • Conditional operators. • Bitwise operators.
  • 14. Numerical operators. + - * / % = --------------------------------------------- e.g. int a, y = 10, x = 12; float b; a = y + 10; b = x / 2; a = a – b;
  • 15. Relational operators. <= == != > < >= Logical operators. && || Conditional operators. ? : Boolean operators. & | ~ ^
  • 16. Expression and Statements. int a = 10, j = 26; float r = 5.22, t = 2.66 + 45.2 * 2; float b = 1.02 , c = b / 2 + 5.2; int d, e, f, g; d = e = f= g = 50; float alpha = 23.001, beta = 892.00; float delta = alpha * beta / 3.2 – alpha; char h, i ; h = ‘D’; I = h;
  • 17. Hierarchy of operations. int i; i = 5 * 6 – 8 + 9 – (43 + 2) /5 – 5; i = 30 – 8 + 9 – 45/5 – 5; i = 30 – 8 + 9 – 9 – 5; i = 22 + 0 – 5; i = 17;
  • 18. First ‘C’ Program. #include<stdio.h> main() { int i = 10, j = 12; float k, m = 12.6; k = (i + j) / m; printf(“Input : %d %d %f”, i, j, m); printf(“nOutput : %f ”, k); } Input : 10 12 12.600000 Output : 1.746032
  • 19. Basic I/O statements. • printf. printf(“<formal string>”,<list of variables>); e.g. printf(“Hello world”); int i = 15; printf(“Value of i is : %d”, i );  %d – integer value.  %f – float value.  %c – character value printf(“%d %d %d”, 3, 3+5, a+b*c);
  • 20. Basic I/O statements. • scanf. It accepts values from user in the form of int / float / char / long / double. e.g. int j, char m; float k; scanf(“%d%f%c”, &j, &k, &m);
  • 21. Compilation and Execution • Integrated Development Environment (IDE). editor + compiler. • Compiling ‘C’ program F9 / Alt F9 – Compiling. Ctrl F9 – Executing. Alt F5 – Watching output.
  • 23. Control Statements • Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator • Repetition Statements –Looping: while, do-while, and for –Nested loops –Using break and continue
  • 24. Selection Statements • if Statements • switch Statements • Conditional Operators
  • 25. if Statements if (Condition) { statement(s); } Example: if (i S 0) { printf("i = %d “, i ); } Condition ? statement1 statement2 statement3 true false
  • 26. Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius S= 0); { area = radius*radius*PI; printf ("The area for the circle of radius %d is =%d“, radius,area); } This mistake is hard to find, because it is neither a compilation error nor a runtime error, it is a logic error. This error often occurs when you use the next-line block style. Wrong
  • 27. The if...else Statement if (condition) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; }
  • 28. if...else Example if (radius S= 0) { area = radius*radius*PI; printf("The area for the circle of radius %d is =%d" , radius, area); } else { printf(“Radius can not be Negative "); }
  • 29. Multiple Alternative if Statements if (score S= 90) grade = ‘A'; else if (score S= 80) grade = ‘B'; else if (score S= 70) grade = ‘C'; else if (score S= 60) grade = ‘D'; else grade = ‘F'; if (score S= 90) grade = ‘A'; else if (score S= 80) grade = ‘B'; else if (score S= 70) grade = ‘C'; else if (score S= 60) grade = ‘D'; else grade = ‘F';
  • 30. Note The else clause matches the most recent if clause in the same block. For example, the following statement int i = 1; int j = 2; int k = 3; if (i S j) if (i S k) printf("A"); else printf("B"); Other combination is : int i = 1; int j = 2; int k = 3; if (i < j) { if (i S k) printf("A"); } else printf("B");
  • 31. switch Statements switch (variable-name) { case value1: Execute this; break; case value2: Execute this; break; case valueN: Execute this; break; default: Execute this; }
  • 32. switch Statement Flow Chart Variable value1 default Next Statement Execute this; Execute this; Execute this; Execute this; value2 valueN
  • 33. switch Statement Rules The switch-expression must yield a value of char or int type and must always be enclosed in parentheses. The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. (The case statements are executed in sequential order.) The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
  • 34. switch Statement Rules, cont….. The default case, which is optional, can be used to perform actions when none of the specified cases is true. The order of the cases (including the default case) does not matter. However, it is a good programming style to follow the logical sequence of the cases and place the default case at the end.
  • 35. Caution Do not forget to use a break statement when one is needed. For example, the following code always displays Wrong number of years regardless of what num is. Suppose the num is 15. The statement rate = 8.50 is executed, then the statement rate = 9.0, and finally the statement, printf("Wrong number of years"). switch (num) { case 7: rate = 7.25; case 15: rate = 8.50; case 30: rate = 9.0; default: printlf("Wrong number of years"); }
  • 36. Example: switch-case int w = 20; switch(w) { case 10: printf(“First”); break; case 20: printf(“Second”); case 30: break; printf(“Third”); break; default: printf(“Wrong value…”); }
  • 37. Conditional Operator (condition) ? exp1 : exp2 if (x S 0) y = 1 else y = -1; is equivalent to y = (x S 0) ? 1 : -1; Ternary operator
  • 38. Conditional Operator if (num % 2 == 0) printf(“%d is even”,num); else printf(“%d is odd”,num); (num%2==0)?printf(“even”):printf(“odd”);
  • 40. while Loop Flow Chart false true Statement(s) Next Statement Continuation condition? while (continuation-condition) { // loop-body; }
  • 41. while Loop Flow Chart, cont. int i = 0; while (i < 100) { printf("Welcome to C!"); i++; } false true printf("Welcome to C!"); i++; Next Statement (i < 100) i = 0;
  • 44. for Loop Example i<100? faIse i++ i = 0 Next Statem ent true printf(“W elcom e to C”); int i; for (i=0;i<100;i++) { printf("Welcome to C"); }
  • 45. Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++); { printf("i is %d“,i); } Wrong
  • 46. Caution, cont. Similarly, the following loop is also wrong: int i=0; while (i<10); { printf("i is %d“,i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { printf("i is %d“,i); i++; } while (i<10); Wrong Correct
  • 47. Which Loop to Use? The three forms of loop statements, while, do, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. It is recommend that you use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
  • 49. Example: break statement int a = 10; while( a S= 0 ) { printf(“nValue of a = %d”,a); a--; if(a==5) break; } Output: Value of a = 10 Value of a = 9 Value of a = 8 Value of a = 7 Value of a = 6
  • 51. Example: continue statement int a = 6; while( a S= 0 ) { a--; if(a==3) continue; printf(“nValue of a = %d”,a); } Output: Value of a = 5 Value of a = 4 Value of a = 2 Value of a = 1 Value of a = 0
  • 52. Arrays 22-Jul-2008 2  Introducing Arrays  Declaring Array Variables, Creating Arrays, and Initializing Arrays  Passing Arrays to Methods  Copying Arrays  Multidimensional Arrays  Search and Sorting Methods
  • 53. Introducing Arrays Array is a data structure that represents a collection of the same types of data. num [0] num [1] num [2] num [3] num [4] num [5] num [6] num [7] num [8] num [9] int num[10]; num reference An Array of 10 Elements of type int 22-Jul-2008 3
  • 54. Declaring Array Variables 22-Jul-2008 4 datatype arrayname[index]; Example: int list[10]; char num[15]; float hat[20];
  • 55. Creating Arrays 22-Jul-2008 5 datatype array-name[size]; Example: int num[10]; num[0] references the first element in the array. num[9] references the last element in the array.
  • 56. Declaring and Creating in One Step 22-Jul-2008 6  datatype arrayname[arraySize]= {values seperated by comma}; Example : char c[5] = {‘a’,’F’,’4’,’’=‘,’n’}; int i[4] = {12,15,0,2};
  • 57. The Length of Arrays 22-Jul-2008 7 Once an array is created, its size is fixed. It cannot be changed. For example, int arr[10]; You can not insert any number to arr[11] location because it is not initialized.
  • 58. Initializing Arrays 22-Jul-2008 8 Declaring, creating, initializing in one step: float hat[4] = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
  • 59. Declaring, creating, initializing Using the Shorthand Notation 22-Jul-2008 9 float list[4] = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: float list[4]; list[0] = 1.9; list[1] = 2.9; list[2] = 3.4; list[3] = 3.5;
  • 60. CAUTION 22-Jul-2008 10 Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: float list; list = {1.9, 2.9, 3.4, 3.5};
  • 61. Example: Copying Arrays 22-Jul-2008 11 The program simply creates two arrays and attempts to copy one to the other, using an assignment statement.
  • 62. Copying Arrays Contents of list1 Contents of list2 list1 list2 Before the assignment list2 = list1; Contents of list1 Contents of list2 After the assignment list2 = list1; list1 list2 Garbage 22-Jul-2008 12
  • 63. Copying Arrays 22-Jul-2008 13 With direct assignment: int array1[5] = {2, 3, 1, 5, 10}; int array2[5]; array2 = array1;
  • 64. Multidimensional Arrays 22-Jul-2008 14 Declaring Variables of Multidimensional Arrays and Creating Multidimensional Arrays int matrix[10][10]; for (i=0; i<10; i++) for (j=0; j<10; j++) { matrix[i][j] = i * j; } float mat[5][5];
  • 65. Multidimensional Array Illustration 0 1 2 3 4 0 7 0 1 2 3 4 1 2 3 4 0 1 2 3 4 matrix[2][1] = 7 int matrix[5][5]; 3 0 1 2 0 1 2 int[][] array ={ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; 1 2 3 4 5 6 7 8 9 10 11 12 22-Jul-2008 15
  • 66. Shorthand Notations 22-Jul-2008 16 You can also use a shorthand notation to declare, create and initialize a two-dimensional array. For example, int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; This is equivalent to the following statements: array[0][0] array[1][0] array[2][0] array[3][0] = 1; array[0][1] = 4; array[1][1] = 7; array[2][1] = 10; array[3][1] = 11; array[3][2] = 2; array[0][2] = 3; = 5; array[1][2] = 6; = 8; array[2][2] = 9; = 12;
  • 67. 17 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; 22-Jul-2008
  • 68. 22-Jul-2008 18 Exercise : Bubble Sort int i[] = {2, 9, 5, 4, 8, 1, 6}; // Unsorted Pass 1: 2, 5, 4, 8, 1, 6, 9 Pass 2: 2, 4, 5, 1, 6, 8, 9 Pass 3: 2, 4, 1, 5, 6, 8, 9 Pass 4: 2, 1, 4, 5, 6, 8, 9 Pass 5: 1, 2, 4, 5, 6, 8, 9 Pass 6: 1, 2, 4, 5, 6, 8, 9
  • 69. What is a Function ? • Function is a self contained block of statements that perform a coherent task of some kind. • Every C program can be a thought of the collection of functions. • main( ) is also a function.
  • 70. Types of Functions. • Library functions. These are the in-built functions of ‘C’ library. These are already defined in header files. e.g. printf( ); is a function which is used to print at output. It is defined in ‘stdio.h’ file . • User defined functions. Programmer can create their own function in C to perform specific task.
  • 71. User defined functions. • e.g. #include<stdio.h> main( ) { message( ); } message( ) { printf(“Hello”); }
  • 72. Declaration of many functions. #include<stdio.h> main( ) { printf(“I am in main”); poly( ); engg( ); agri( ); } poly( ) { printf(“I am in polytechnic”); } engg( ) { printf(“I am in engineering”); } agri( ) { printf(“I am in agri”); }
  • 73. Some conclusions. • Any C Program must contain at least one function. • If program contains only one function it must be main( ). • There is no limit on the number of functions present in a C program. • Each function in a program is called in the sequence specified by functions call in main( ). • After each function has done its thing, control returns to main( ). When main( ) run out of function calls program ends.
  • 74. Summarization. • C Program is a collection of one or more functions. • A function gets called when its name is followed by a semicolon. e.g. main( ) { fun( ); } fun( ) { statement1; statement2; statement3; }
  • 75. Summarization Contd………. • Any function can be called by any other function. e.g. main( ) { printf(“I am in main.”); fun( ); } fun( ) { printf(“I am in fun.”); main( ); } This will run in infinity.
  • 76. Summarization Contd………. • A function can be called by number of times. e.g. main( ) { printf(“I am in main.”); fun( ); fun( ); fun( ); } fun( ) { printf(“I am in fun.”); }
  • 77. Summarization Contd………. • A function can call itself, it is called as a ‘recursion’. e.g. main ( ) { printf(“I am in main”); main( ); } • A function can be called from another function but can not be defined in another function. It should be defined outside of the main.
  • 78. Why use functions ? • Writing functions avoids rewriting of the same code again and again in the program. • Using a function it becomes easier to write program to keep track of what they are doing.
  • 79. Passing values to functions. The values that we pass to the function called as function arguments. e.g. main( ) { int i=10, j=12, k=20; calsum(i,j,k); } calsum(int x, int y, int z) { printf(“Sum is : %d”,(x+y+z)); } i, j, k are actual arguments x, y, z are formal arguments.
  • 80. Returning a value. • The keyword ‘return’ to used to return value from function which is present in the parenthesis of return. • On executing return statement it immediately transfers control back to the main program. e.g. main( ) { int a = 30, j = 14; int k; k = addin(a, j); printf(“%d”, k); } int addin(int x, int y) { int z; z = (x + y) +1; return(z); }
  • 81. return • There is no restriction of return statements in a function. • Whenever the control returns from the function some value is definitely returned. It should be accepted in the calling program. e.g. int sum; sum = calsum(a,b,c); here the value returned by calsum must be of type int. • Some valid return statements. /*a is a variable name */ return a; return (23); return (15.32); return (‘v’); return; • If you are not returning any value from a function they it should be declared as void. (void is a keyword). e.g. void display( ) display is not returning any value.
  • 82. Function declaration and Prototype. Any C function by default returns and integer value. More specifically, whenever a call is made to a function, the compiler assumes that this function would return value of type int. Function prototype : #include<stdio.h> int addin(int, int); void main( ) { statements; statements; } int addin(int a, int b) { statements; } Function prototype.
  • 83. Structures  In general, we can call a structure is a collection of different types of data.  A Structure contains number of data types grouped together. These data types may be or may not be of same data type.
  • 84. ‘C’ implementation of Structure. • The keyword ‘struct’ is used for creating a structure. Syntax: struct structure-name { datatype1 varname1; datatype1 varname2; datatype1 varname3; }; creating the object of structure: struct structure-name var1, var2, var3;
  • 85. Accessing structure elements. . (dot operator) is used to access individual structure element. e.g. struct list { int roll; char name[10]; float marks; }; struct list a , b , c; a.roll – is the integer element of structure a. a.name – is char array element of structure a b.marks – is a float element of structure b. a.marks – is a float element of structure b. scanf(“%d”, &b.roll); this statement can accept an integer roll of structure b from user. This is applied to all the elements of a structure.
  • 86. How structure elements are stored. e.g. struct book { char name; int pages; float price; }; struct book z = {‘s’, 125, 90.0}; Here value of : z.name is ‘s’. z.pages is 125 and z.price is 90.0 Memory map: ‘s’ 125 90.0 z.name z.pages z.price
  • 87. Valid declaration. struct list { int roll; char name[10]; float marks; }; struct list a , b , c; It is equivalent to : struct list { int roll; char name[10]; float marks; }a, b, c;
  • 88. Remember:  The closing bracket of structure type declaration must be followed by a semicolon.  Usually structure declaration appears at the top of the source code file before any variables and structures are defined.  Accessing single variable in a structures must be followed by a . (dot operator).
  • 89. Example: Creating a student database of 3 students. #include<stdio.h> void main( ) { struct student { int roll; char name[10]; float marks; } a, b, c; printf(“Enter all information of students:” ); scanf(“%d %s %f”, &a.roll, a.name, &a.marks); scanf(“%d %s %f”, &b.roll, b.name, &b.marks); scanf(“%d %s %f”, &c.roll, c.name, &c.marks); printf(“You entered this information:”); printf(“n%d %s %f”, a.roll, a.name, a.marks); printf(“n%d %s %f”, b.roll, b.name, b.marks); printf(“n%d %s %f”, c.roll, c.name, c.marks); }
  • 90. Array of structures.  We can create the array of structures. Thus, we can use the same structure for more than one variables which adds more flexibility in your program. Let’s view the previous example. #include<stdio.h> void main( ) { struct student { int roll; char name[10]; float marks; } a[10]; int j; printf(“Enter all information of students:” ); for(j = 0 ; j < 10 ; j++) scanf(“%d %s %f”, &a.roll[i], a.name[i], &a.marks[i]); for(j = 0 ; j < 10 ; j++) printf(“n%d %s %f”, a.roll[i], a.name[i], a.marks[i]); }
  • 91. Memory map for arrays. a[i].roll a[i].nam e a[i].marks 8 9 i 0 1 2 a[5].roll 3 4 5 6 7 a[9].name
  • 93. Pointer Variables • Pointers are often referred to as references • The value in a pointer variable is interpreted as a memory address • Usually, pointer variables hold references to specific kinds of data (e.g.: address of an int, address of a char, etc) int * p; char * chptr; /* variable p can hold the address of a memory location that contains an int */ /* chptr can hold the address of a memory location that contains a char */
  • 94. Dereferencing Operator • The expression *p denotes the memory cell to which p points • Here, * is called the dereferencing operator • Be careful not to dereference a pointer that has not yet been initialized: int *p; p ? *p = 7; Address in p could be any memory location Attempt to put a value into an unknown memory location will result in a run-time error, or worse, a logic error
  • 95. • To help keep things straight, it’s useful to pretend there are parentheses in the pointer declarations: • (int *) p; means that p is of type int* (i.e.: that is, p is a pointer to an int location) • int (*p); means that location *p has the potential to hold an int value • Don’t actually write declarations this way
  • 96. The Address Operator • The expression &x denotes the address of a variable x • Here, & is called the address operator or the reference operator int x, *p; p ? x ? p = &x; *p = 4; p x ? p x 4 Value of x has been changed Value of p has been changed
  • 97. The Null Pointer • The null pointer is a special constant which is used to explicitly indicate that a pointer does not point anywhere • NULL is defined in the standard library <stdlib.h> • In diagrams, indicated as one of: NULL .
  • 98. Pointer Example int *p, x, y, *q = NULL; p = &x; *p = 4; p x (or *p) y 4 ? p = &y; p x y 4 ? *p is now another name for y q q . .
  • 99. *p = 8; p x y 4 8 q = p; p x y 4 8 q *p or *q q *p .
  • 100. p = &x; p x y 4 8 *q *p = *q; p x y 8 8 q *p q *p *q 8
  • 101. Arrays of Pointers • It’s possible to have arrays of pointers • The array name is a pointer to an array of pointers: int j = 6; k = 4; int * arrayOfPtr[4]; j k 6 4 arrayOfPtr ? ? ? ? 0 1 2 3 Pointers in array are not initialized yet
  • 102. arrayOfPtr[0] = &k; arrayOfPtr[2]=&j; j k 6 4 arrayOfPtr ? 0 1 2 3 ?
  • 103. Array Names as Pointers • Array name is really a pointer to the first element in the array • Consider the declaration int arr[5]; • arr has the same meaning as &arr[0] • *arr has the same meaning as arr[0] • Indexing into an array is really a pointer dereferencing operation
  • 104. Generic Pointers • Sometimes we need to use pointer variables that aren’t associated with a specific data type • In C, these generic pointers simply hold memory addresses, and are referred to as pointers to void: void* ptr;
  • 105. • Any kind of pointer can be stored in a variable whose type is void* • If we know that a value in a pointer p of type void* is really of a specific pointer type x, and we want to treat the value p points to as a value of type x, we have to cast the pointer to type x
  • 106. Generic Pointer Example void * arr[6]; int j = 7; double k = 5.9; int * n; double x; j arr x n k ? ? ? ? ? ? ? ? 7 5.9 0 1 2 3 4 5
  • 107. arr[2] = (void*)&j; /*cast is okay, but not needed here */ j arr x n k ? ? 7 5.9 ? ? ? ? ? 0 1 2 3 4 5
  • 108. arr[5] = &k; /* cast not needed, but could be used */ j arr x n k ? ? ? ? ? ? 7 5.9 0 1 2 3 4 5
  • 109. n = (int*)arr[2]; /* cast is required here */ j arr x n k 0 1 2 3 4 5 ? ? ? ? ? 7 5.9
  • 110. x = *((double*)arr[5]); /* cast is required here */ j arr x n k 0 1 2 3 4 5 ? ? ? ? 5.9 7 5.9
  • 111. File Handling in ‘C’
  • 112. File.  A file is used for permanent storage. Opening a file. FILE *fp; fp is a file pointer variable which contains address of structure FILE which is defined in stdio.h fopen(“file-name”,”opening mode”); file-name – name of the file to open. opening-mode – mode in which is file is to be opened. This may be: r – reading mode. w – writing mode. a – appending mode. e.g. fopen(“abc.txt”,”r”); it will open file in reading mode. Means we can only read its data.
  • 113. Creating new file. fopen(“abc.txt”, “w”); it will open file in writing mode means you can only write to this file. If name of the file file is not existing then it creates new blank file. caution: if you create an existing file in writing mode, then its previous contents gets destroyed. fopen(“abc.txt”, “a”); it will open the existing file in appending mode. In this case the previous contents doesn’t get destroyed you can only append new data to this file.
  • 114. Reading from a file. fscanf is used to read the contents from the file. Syntax: fscanf(file-pointer,”access-specifier”,variables); e.g. FILE *fp; char name[10]; fp = fopen(“abc.txt”, “r”); fscanf(fp,”%s”, name); printf(“%s”, name); File name name fscanf Print to output
  • 115. Writing to a file fprintf is used to write the contents to the file. Syntax: fscanf(file-pointer,”access-specifier”,variables); e.g. FILE *fp; char name[10]; fp = fopen(“abc.txt”, “w”); fprintf(fp,”Your name : KKWP”); This will print ‘Your name : KKWP’ in the file name ‘abc.txt’.
  • 116. Some file operations. fclose(file-pointer); when you open a file using fopen() is must be closed using this statement after use. e.g. fclose(fp); Checking exiting file: if(fp==NULL) then file is not existing. feof(file-pointer) it checks that end of file is reached or not. If yes returns 1 else false. e.g. while(feof(fp)) fscanf(fp,”%s”, name);