an imperative study of c

76
Tushar B. Kute, Department of Information Technology, Sandip Institute of Technology and Research Centre, Nashik An Imperative Study of ‘C’

Post on 18-Oct-2014

1.172 views

Category:

Education


2 download

DESCRIPTION

The Presentation given at KK Wagh Polytechnic, Nashik for Second Year Information Technology Students on15/01/2011.

TRANSCRIPT

Page 1: An imperative study of c

Tushar B. Kute,Department of Information Technology,

Sandip Institute of Technology and Research Centre, Nashik

An Imperative Study of ‘C’

Page 2: An imperative study of c

Outline

• Basic programming concepts.• Decision making statements.• Arrays and Strings.• Functions.• Structures.• Pointers.

Page 3: An imperative study of c

Why ‘C’ only?

Page 4: An imperative study of c

Problem Solving

• Analysis• Design• Code• Maintain• Test

Page 5: An imperative study of c

Two views of program

user interface

software layers hidden by user interface

user’s view

programmer’s view

Page 6: An imperative study of c

Alphabets,Digits, Special

Symbols.

Constants,Variables,

And KeywordsInstructions

Program.

Forming a C program

Page 7: An imperative study of c

Compiling a C program

Page 8: An imperative study of c

Basic Programming Concepts

• Constants.• Data Types.• Keywords.• Operators.

– Arithmetic– Logical– Bitwise– Relational– Conditional

Page 9: An imperative study of c

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

}

Page 10: An imperative study of c

Control Statements• Selection StatementsSelection Statements

– Using if and if...else– Nested if Statements– Using switch Statements– Conditional Operator

• Repetition StatementsRepetition Statements– Looping: while, do-while, and for– Nested loops– Using break and continue

Page 11: An imperative study of c

if Statements

if (Condition) { statement(s);}

Example:if (i > 0) {

printf("i = %d “, i );}

Condition ?

statement1

statement2

statement3

true

false

Page 12: An imperative study of c

The if...else Statement

if (condition) { statement(s)-for-the-true-case;}else { statement(s)-for-the-false-case;}

Page 13: An imperative study of c

if...else Example

if (radius >= 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 ");}

Page 14: An imperative study of c

Multiple Alternative if Statementsif (score >= 90) grade = ‘A’;else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;

if (score >= 90) grade = ‘A’;else if (score >= 80) grade = ‘B’;else if (score >= 70) grade = ‘C’;else if (score >= 60) grade = ‘D’;else grade = ‘F’;

Page 15: An imperative study of c

switch Statementsswitch (variable-name)

{ case value1:

Execute this; break; case value2:

Execute this; break;

case valueN: Execute this;

break; default: Execute this;}

Page 16: An imperative study of c

switch Statement Flow Chart

Page 17: An imperative study of c

Repetitions

while Loops

do-while Loopsfor Loops

break and continue

Page 18: An imperative study of c

while Loop

while (continuation-condition)

{

// loop-body;

}

Page 19: An imperative study of c

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;

Page 20: An imperative study of c

do-while Loop

false

true

Statement(s)

Next Statement

Continue condition?

do

{

// Loop body;

} while (continue-condition);

Page 21: An imperative study of c

for Loop for (initialization; condition; increment/decrement){ //loop body;}

Page 22: An imperative study of 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

Page 23: An imperative study of c

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

Page 24: An imperative study of c

Which Loop to Use?

Page 25: An imperative study of c

The break Keyword

Page 26: An imperative study of c

Example: break statementint a = 10;

while( a >= 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

Page 27: An imperative study of c

The continue Keyword

Page 28: An imperative study of c

Example: continue statement

int a = 6;

while( a >= 0 )

{

a--;

if(a==3)

continue;

printf(“\nValue of a = %d”,a);

}

Page 29: An imperative study of c

ArraysArray 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 Elementsof type int

Page 30: An imperative study of c

Declaring Array Variables

• datatype arrayname[index];

Example:

int list[10];

char num[15];

float hat[20];

Page 31: An imperative study of c

Creating Arrays

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.

Page 32: An imperative study of c

Declaring and Creatingin One Step

• datatype arrayname[arraySize]= {values seperated by comma};

Example :

char c[5] = {‘a’,‘F’,‘4’,‘=’,‘n’};

int i[4] = {12,15,0,2};

Page 33: An imperative study of c

The Length of Arrays

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

Page 34: An imperative study of c

Declaring, creating, initializing Using the Shorthand Notation

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;

Page 35: An imperative study of c

CAUTION

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

Page 36: An imperative study of c

Copying Arrays

With direct assignment:

int array1[5] = {2, 3, 1, 5, 10};

int array2[5];

array2 = array1;

Page 37: An imperative study of c

Multidimensional ArraysDeclaring 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];

Page 38: An imperative study of c

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

7

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

8

9

10

11

12

Page 39: An imperative study of c

Function

Page 40: An imperative study of c

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.

Page 41: An imperative study of c

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.

Page 42: An imperative study of c

User defined functions• e.g.

#include<stdio.h>message( ){

printf(“Hello”);}

main( ){

message( );}

Page 43: An imperative study of c

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”);}

Page 44: An imperative study of c

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.

Page 45: An imperative study of c

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;

}

Page 46: An imperative study of c

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.

Page 47: An imperative study of c

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.”);

}

Page 48: An imperative study of c

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.

Page 49: An imperative study of c

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.

Page 50: An imperative study of c

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.

Page 51: An imperative study of c

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

}

Page 52: An imperative study of c

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.return a; /*a is a variable name */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.

Page 53: An imperative study of c

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.

Page 54: An imperative study of c

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.

Page 55: An imperative study of c

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

Page 56: An imperative study of c

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

Page 57: An imperative study of c

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’s’ 125125 90.090.0

z.name z.pages z.price

Page 58: An imperative study of c

Valid declarationstruct 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;

Page 59: An imperative study of 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).

Page 60: An imperative study of c

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

}

Page 61: An imperative study of c

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

}

Page 62: An imperative study of c

Memory map for arraysa[i].roll a[i].name a[i].marks i

2

1

9

3

0

7

6

5

4

8

a[5].roll

a[9].name

Page 63: An imperative study of c

Pointers

Page 64: An imperative study of 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; /* variable p can hold the address of a

memory location that contains an int */

char * chptr; /* chptr can hold the address of a

memory location that contains a char */

int * p; /* variable p can hold the address of a

memory location that contains an int */

char * chptr; /* chptr can hold the address of a

memory location that contains a char */

Page 65: An imperative study of c

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; int *p; p ?

*p = 7; *p = 7;

Address in p could be any memory locationAddress 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

Attempt to put a value into an unknown memory location will result in a run-time error, or worse, a logic error

Page 66: An imperative study of c

• 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

Pointer

Page 67: An imperative study of c

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

Page 68: An imperative study of c

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>

Page 69: An imperative study of c

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 .

.

Page 70: An imperative study of c

*p = 8;

p x y 4 8

q = p;

p x y 4 8

q

*p or *q

q

*p

.

Page 71: An imperative study of c

p = &x;

p x y 4 8

*q

*p = *q;

p x y 8

8

q

*p

q

*p

*q

8

Page 72: An imperative study of c

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 k6 4

arrayOfPtr

? ? ? ?

0 1 2 3

Pointers in array are not initialized yet

Page 73: An imperative study of c

arrayOfPtr[0] = &k;

arrayOfPtr[2]=&j;

j k

6 4

arrayOfPtr

?

0 1 2 3

?

Page 74: An imperative study of c

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

Page 75: An imperative study of c

Functions Calls

• Call by value.• Call by reference.

Page 76: An imperative study of c

References

• “Let us C” by Yashwant Kanetkar, BPB Publications.

• “Programming in ANSI C” by E Balagurusamy, Tata McGraw Hill Publishing.

• “How to Program: C”, by Deital and Deital, Prentice Hall of India.

• “The Complete Reference: C” by Herbert Schildt, McGraw Hill International Publishing.