complete c slides

143
Welcome

Upload: shuja-khan

Post on 27-May-2017

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Complete C Slides

Welcome

Page 2: Complete C Slides

C

Page 3: Complete C Slides

Introduction

C programming language was developed in 1972 by Dennis

Ritchie at Bell Laboratories.

It‟s an offspring of “Basic combined programming” called „B‟

which was developed by Ken Thomson

B language was interpreter-based so it was very slow

Then Dennis Ritchie modified the „B‟ language and named it as

„C„

Page 4: Complete C Slides

History… ALGOL

Traditional C

BCPL

ANSI C

K&R

B

ANSI/ISO C

1960

1967

1970

1972

1978

1989

1990

International Group

Martin Richards

Ken Thompson

Dennis Ritchie

Kernighan & Ritchie

ANSI Committee

ISO Committee

Page 5: Complete C Slides

Benefits

C programs are efficient, fast & Highly portable

It can be written in one computer and can be run in another

computer without any Modification.

Its easy for debugging, testing & maintenance because of

structured programming

Functions can be used many Number of building blocks

Page 6: Complete C Slides

Why C used Widely

Pointers it allow reference to memory location by

a name

Memory allocation Allow static as well as

dynamic memory location

Recursion Is a process in which a function can

call itself

Bit Manipulation Allows manipulation of data in its

lowest form of storage

Page 7: Complete C Slides

Structure of the programming

Documentation Section

Link Section

Definition Section

Global Declaration Section

Main() Function Section

{

Declaration Part

Executable Part

}

Subprogram Section (User-defined FUnctions)

Page 8: Complete C Slides

Simple Programs

# include <stdio.h>

# include <conio.h>

Void main()

{

/*Program to Display The Content*/

clrscr();

printf(“Good Morning..! Have a Nice Day”);

getch();

}

Page 9: Complete C Slides

Simple Programs # include <stdio.h>

# include <conio.h>

Void main()

{

/*Program for Addition*/

int a,b,c;

clrscr();

printf(“Enter the value of A :”);

scanf(“%d”,&a);

printf(“Enter the value of B :”);

scanf(“%d”,&b);

c=a+b;

printf(“The Value of C is :”,c);

}

Page 10: Complete C Slides

Character Set

The Character that can be used to form words,

numbers and expression depends upon the

computer on which the program runs.

Letters

Digits

Special Character

White Space

Page 11: Complete C Slides

, .Comma & .Ampersand

. .Period ^ .Caret

; .Semicolon * .Asterisk

: .Colon - .Minus Sign

? .Question Mark + .Plus Sign

' .Aphostrophe < .Opening Angle (Less than sign)

" .Quotation Marks > .Closing Angle (Greater than sign)

! .Exclaimation Mark ( .Left Parenthesis

| .Vertical Bar ) .Right Parenthesis

/ .Slash [ .Left Bracket

\ .Backslash ] .Right Bracket

~ .Tilde { .Left Brace

- .Underscore } .Right Bracket

$ .Dollar Sign # .Number Sign

% .Percentage Sign . .

Page 12: Complete C Slides

Keywords

“Keywords” are words that

have special meaning to the

C compiler.

These keywords cannot be

used as identifiers in the

program

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default go to size of volatile

do if static while

Page 13: Complete C Slides

Identifiers

Identifiers" are the names you supply for variables,

types, functions, and labels in your program.

Identifier names must differ in spelling and case from

any keywords.

You cannot use keywords as identifiers; they are

reserved for special use.

Rules:

First character must be an alphabet (or underscore).

Must consist of only letters, digits or underscore.

Only first 31 characters are significant.

Cannot use a keyword.

Must not contain white space .

Page 14: Complete C Slides

Constants

Constants

Numeric Constants Character Constants

Integer Real Single

Character String

Page 15: Complete C Slides

Data Types

This enables the

programmer to select the

appropriate data type as per

the need of the application

ANSI C supports three

classes of data types

Primary data types

Derived data types

User-defined data types

Data Type Bytes Default Range

signed char 1 -128 to 127

Unsigned char 1 0 to 255

short signed int 2 -32768 to 32767

short unsigned int 2 0 to 65535

long signed int 4 -2147483648 to 2147483647

long unsigned int 4 0 to 4294967295

Float 4 -3.4e38 to +3.4e38

Double 8 -1.7e308 to +1.7e308

long double 10 -1.7e4932 to +1.7e493

Page 16: Complete C Slides

Operator and Expressions Operator indicates an operation to be performed on data

that yields a value

1. Arithmetic operators (+,-,*,/,%)

2. Relational operators (>,<,= =,>=,<=,!=)

3. Logical operators (&&,||,!)

4. Increment and decrement operator (++,--)

5. Assignment operator (=)

6. Bitwise operator (&,|,^,>>,<<)

7. Comma operator (,)

8. Conditional operator (?,:)

Page 17: Complete C Slides

Operator Precedence

Operator Description Associativity

()

[]

.

->

++ --

Parentheses (function call) (see Note

1)

Brackets (array subscript)

Member selection via object

name

Member selection via pointer

Postfix increment/decrement (see

Note 2)

left-to-right

++ --

+ -

! ~ (type)

*

&

sizeof

Prefix increment/decrement

Unary plus/minus

Logical negation/bitwise

complement

Cast (change type)

Dereference

Address

Determine size in bytes

right-to-left

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <=

> >=

Relational less than/less than or

equal to

Relational greater than/greater

than or equal to

left-to-right

Page 18: Complete C Slides

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

=

+= -=

*= /=

%= &=

^= |=

<<= >>=

Assignment

Addition/subtraction assignment

Multiplication/division

assignment

Modulus/bitwise AND

assignment

Bitwise exclusive/inclusive OR

assignment

Bitwise shift left/right

assignment

right-to-left

, Comma (separate expressions) left-to-right

Page 19: Complete C Slides

Decision Statement

To alter the flow of a program.

Test the logical conditions.

Control the flow of execution as per the selection.

if-statements

if-else statement

else-if statement

Nested if statement

switch-statement

Page 20: Complete C Slides

If-Construct

Syntax: ii) if(expr)

i) {

if (expr) statement1;

statement; statement2;

}

where expr is Boolean

Note:

True Boolean values are any integer different from zero.

False Boolean value is the integer zero.

Page 21: Complete C Slides

If-else Construct

Syntax:

if (expr)

statement1;

else

statement2;

Example: a=5,b=10

if (a<b)

{

printf(“b is bigger than a”);

}

else

{

Printf(“a is bigger than b”);

}

Page 22: Complete C Slides

Else-if Construct

Syntax:

if (expr)

Statement 1;

else if(expr1)

Statement 2;

else if(exp2)

Statement 3;

-

-

else

Statement n;

Example: a=5 b=10 c=15

If (a>b && a>c)

{

printf (“a is the biggest no”);

}

else if (b>c)

{

printf(“b is the biggest no”);

}

else

{

Printf(“c is the biggest no”);

}

Page 23: Complete C Slides

Nested if Construct

i)

If(expr)

{

-

-

if(expr2)

statement 1;

-

-

}

ii)

If(expr)

{

-

if(expr1)

statement1;

else

statement2;

}

else

{

if(expr2)

statement3;

else if(expr3)

statement4;

else

statement5;

}

Page 24: Complete C Slides

Example for Nested if A=5 b=10 c=20

If(a>b)

{

if(a>c)

{

printf(“a is the biggest no”);

}

else

{

printf(“c is the biggest no”);

}

}

Else if(b>c)

{

printf(“b is the biggest no”);

}

Else

{

printf(“c is the biggest no”);

}

evencount = oddcount = 0;

if ( (num % 2) == 0 )

{

printf(“%d is an even number.\n”, num);

++evencount;

if( (num % 4) == 0 )

printf(“It is divisible by 4\n”);

if( num == 0 )

{

printf(“It is zero.\n”);

printf(“That isn’t interesting.\n”);

}

}

else

{

printf(“%d is an odd number.\n”, num);

++oddcount;

if( (num % 9) == 0 )

printf(“It is divisible by 9\n”);

else

printf(“It is not divisible by 9\n”);

}

Page 25: Complete C Slides

Switch Construct

Syntax:

switch (expr) /* expr is a boolean expression

{

case C1:

{statement0;break;}

case C2:

{statement1;break;}

default: /* optional */

{DefaultStatement;break;}

}

Note : C1 & C2 represent values. It is the type of int or char only.

Page 26: Complete C Slides

Example for Switch Construct

Int a;

Scanf (“%d”,&a);

Switch (a)

{

case 1:

printf (“you entered : %d”,1);

break;

case 2:

printf(“you entered : %d “,2);

break;

case 3:

printf (“you entered : %d “,3);

break;

default: /*optional*/

printf (“you entered except 1,2,3”);

}

Char a;

Scanf(“% c”,&a);

Switch (a)

{

case „a‟:

printf(“you entered : a”);

break;

case „b‟:

printf(“you entered : b”);

break;

case „c‟ :

printf(“you entered : c”);

break;

default: /* optional*/

printf(“you entered except a,b,c”);

}

Page 27: Complete C Slides

Loop Control Statements • Looping is deciding how many times to take certain action.

• In looping process in general would include the following four steps 1. Setting and initialization of a counter. 2. Exertion of the statements in the loop. 3. Test for a specified conditions for the execution of the loop. 4. Incrementing the counter.

• Types

while-statement

do-while statement

for-statement

Page 28: Complete C Slides

While Constructs

Syntax:

while(expr)

while (expr) {

Statement; statement1;

statement2;

}

where expr is Boolean

Note:

True Boolean values are any integer different from zero;

False Boolean value is the integer zero.

Page 29: Complete C Slides

Example for While Construct

i=0;

while(i<10)

{

printf(“precision\n”);

i++;

}

#include<stdio.h>

int main()

{

int counter, howmuch;

scanf("%d", &howmuch);

counter = 0;

while ( counter < howmuch)

{

counter++;

printf("%d\n", counter);

}

return 0;

}

Page 30: Complete C Slides

Do-while Construct

Syntax:

do

do {

Statement; statement1;

while (expr); statement2;

}while(expr);

Note:

while statement executes zero or more iterations of the loop;

do-while statement executes one or more iterations of the loop.

Page 31: Complete C Slides

Example for do-while construct

i=0;

do

{

printf(“precision\n”);

i++;

} while(i<10);

#include<stdio.h>

int main()

{

int counter, howmuch; scanf("%d", &howmuch); counter = 0;

do

{

counter++;

printf("%d\n", counter);

}

while ( counter < howmuch); return 0;

}

Page 32: Complete C Slides

For Construct

Syntax:

for(expr1;expr2;expr3)

for(expr1; expr2; expr3) {

Statement; statement1;

statement2;

}

Semantic: equivalent to

expr1;

while (expr2)

{

Statement;

expr3;

}

Page 33: Complete C Slides

Example for For Construct

#include<stdio.h>

int main()

{

int i;

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

{

printf ("Hello\n");

printf ("World\n");

}

return 0;

}

#include<stdio.h>

int main()

{

int i;

for (i =20; i >10; i--)

{

printf ("Hello\n");

printf ("World\n");

i--;

}

return 0;

}

Page 34: Complete C Slides

Looping Related Statements

Break

Continue

Page 35: Complete C Slides

Break statement

Syntax:

break;

Semantic:

terminates the execution of a loop or a switch

Page 36: Complete C Slides

Example for Break Statement

#include<stdio.h>

int main()

{

int i;

i = 0;

while ( i < 20 )

{

i++;

if ( i == 10)

break;

}

return 0;

}

Page 37: Complete C Slides

Continue statement

Syntax:

continue;

Semantic:

terminates the current iteration of a loop

Page 38: Complete C Slides

Example for Continue Statement

#include<stdio.h>

int main()

{

int i;

i = 0;

while ( i < 20 )

{

i++;

continue;

printf("Nothing to see\n");

}

return 0;

}

Page 39: Complete C Slides

Unconditional jump statement

Syntax:

goto Label;

where Label:Statement;

belongs to the program

Semantic:

forces control to go to the Statement;

Page 40: Complete C Slides

Example for goto Statement

#include<stdio.h>

int main()

{

Int i=0;

START: i++;

printf(“%d\n”,i);

if(a<=10)

{

goto START;

}

else

{

goto END;

}

END: return 0;

}

Page 41: Complete C Slides

Array

One-Dimensional array

Two-Dimensional array

Multi-Dimensional array

Page 42: Complete C Slides

One-Dimensional Array

collection of elements of same data type

that are stored contiguous in memory.

1000 1002 1004 1006 1008 1010 1012 1014 1016 1018

10 20 30 35 6 25 50 45 28 14

data

Address

Page 43: Complete C Slides

One-Dimensional Array

The subscript, or the index of each array

element is determined based on the

number of offset positions it is from the

starting position. The starting offset is taken

as 0.

1000 1002 1004 1006 1008 1010 1012 1014 1016 1018

10 20 30 35 6 25 50 45 28 14

0 1 2 3 4 5 6 7 8 9

offset

Page 44: Complete C Slides

One-Dimensional Array Syntax:

datatype variablename [size];

Example:

int a[10];

block of 10 contiguous elements in memory.

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

a Array name (Starting address of the array)

offset

Page 45: Complete C Slides

One-Dimensional Array

Initialization

A character array needs a string terminator, the NULL character

(„\0‟) as the last character, whereas integer and float arrays do not need a terminator.

Examples: char array1[ ] = {„A‟, „R‟, „R‟, „A‟, „Y‟, „\0‟};

char array2[ ] = {“ARRAY”};

char dayofweek[7] = {„M‟, „T‟, „W‟, „T‟, „F‟, „S‟, „S‟};

float values[ ] = {100.56, 200.33, 220.44, 400.22, 0};

Page 46: Complete C Slides

Initialization

Example:

#include<stdio.h>

main( )

{

char array1[ ] = {„A‟, „R‟, „R‟, „A‟, „Y‟, „\0‟};

char array2[ ] = {“ARRAY”};

int i = 0;

printf( “String 1 is %s\n”, array1);

printf( “String 2 is %s\n”, array2);

}

One-Dimensional Array

Page 47: Complete C Slides

One-Dimensional Array

Initialization

int a[5]={7,3,8,2,25};

(or)

int a[5];

a[0]=7;

a[1]=3;

a[2]=8;

a[3]=2;

a[4]=25;

Page 48: Complete C Slides

Input To Array

Normal Variable:

int a;

scanf(“%d”,&a);

Array Variable:

int a[20];

scanf(“%d”,&a[0]);

- - -

- - -

scanf(“%d”,&a[19]);

Array Variable:

int a[20],i;

for(i=0;i<20;i++)

{

scanf(“%d”, &a[ i ]);

}

20 lines

4 lines

Which one is best ?

Array offset

always start

with 0

Page 49: Complete C Slides

Array Manipulation Using Subscripts

/* this function finds the length of a character string */

#include <stdio.h>

main( )

{

int i = 0;

char string[11]; /* char array decalaration */

printf(“Enter a string of maximum ten characters\n”);

gets(string); /* get the input from the keyboard (stdin buffer) */

fflush( stdin); /* clear the stdin buffer */

for(i =0; string[i] != „\0‟; i = i + 1);

printf(“The length of the string is %d \n”, i);

}

Page 50: Complete C Slides

Array Addressing

In the declaration:

char string[11];

the name of the array refers to the starting address of the area that gets allocated for storing the elements of the array.

Thus, string contains the address of string[0].

In the aforesaid declaration, string refers to the starting position of the array, and the subscript refers to the offset position from the starting position.

Page 51: Complete C Slides

Array Addressing

string

100

0 1 2 3 4 5 6 7 8 9 10

100 101 102 103 104 105 106 107 108 109 110

a b c d e f g h i j \0

Page 52: Complete C Slides

Array Addressing

To arrive at the address of the particular element, the compiler applies the following simple formula:

starting address of the array + ( offset position * size of data

type)

Address of element 4 = 100 + ( 3 * 1) = 100 +3 = 103

Page 53: Complete C Slides

One-Dimensional Array

Example:

#include <stdio.h>

int main()

{

int iMarks[4];

short newMarks[4];

iMarks[0]=78;

iMarks[1]=64;

iMarks[2]=66;

iMarks[3]=74;

for(i=0; i<4; i++)

newMarks[i]=iMarks[i];

for(j=0; j<4; j++)

printf("%d\n", newMarks[j]);

return 0;

}

Page 54: Complete C Slides

Two-Dimensional Array

Syntax:

datatype variablename [rowsize] [columnsize];

Example:

int a[4][3];

block of 15(5*3) contiguous elements in memory.

0

0 1 2

1

2

3

Row offset

value

Column offset

value a[0][0]

a[0][2]

1000 Address

Of a[0][0]

1004

1006

?

Page 55: Complete C Slides

Two-Dimensional Array

Initialization

Example:

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

int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };

int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };

char arr[3][12]= { "Rose", "India", "technologies" };

Page 56: Complete C Slides

Two-Dimensional Array Initialization

Example:

#include <stdio.h>

#include <conio.h>

void main()

{

char arr[3][12]= { "Rose", "India", "technologies" };

clrscr();

printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);

getch();

}

Page 57: Complete C Slides

Input To 2-D Array

1-D Array:

int a[20],i;

for(i=0;i<20;i++)

{

scanf(“%d”, &a[ i ]);

}

2-D Array:

int a[10][5],i,j;

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

{

for(j=0;j<5;j++)

{

scanf(“%d”,&a[i][j]);

}

}

Increment

column index

Increment

row index

Note:

In this 2-D array example we will get input row by row. That means get rows

value one by one using inner for loop. Increment row using outer loop.

Page 58: Complete C Slides

Two-Dimensional Array Example:

main ( )

{

int stud [4] [3];

int i, j;

for (i =0; i < =3; i ++)

{

for(j=0;j<=2;j++)

{

printf ("\n Enter roll no. and marks");

scanf ("%d%d", &stud [i] [j], &stud [i] [j] );

}

}

for (i = 0; i < = 3; i ++)

{

for(j=0;j<=2;j++)

{

printf ("\n %d %d", stud [i] [j], stud [i] [j]);

}

}

Page 59: Complete C Slides

Functions

A function is a sub-program of one or more statements that performs a

special task when called

C supports two types of function

Library Function

User Defined Function

main()

{ -------

abc(x,y,z); Function call (Actual argument)

-------

}

abc(l,k,j) Function Definition (Formal argument)

{ -------

-------

}

Page 60: Complete C Slides

Functions

A function is a sub-program of one or more statements that performs a

special task when called

C supports two types of function

Library Function

User Defined Function

A function is declared as

return-value-type function-name( parameter-list ) {

declarations and statements }

Page 61: Complete C Slides

Function definition format (continued)

return-value-type function-name( parameter-list ) {

declarations and statements }

Declarations and statements: function body

Variables can be declared inside blocks

Functions can not be defined inside other functions

Returning control

If nothing returned

return;

If something returned

return expression

Page 62: Complete C Slides

Rules and Regulations

A function should follows

1.Function Declaration

2.Function call

3.Function Definition

Page 63: Complete C Slides

Example

#include<stdio.h>

Void display() /* function declaration*/

Void main()

{

display();/*function call*/

}

Void display()/*function definition*/

{

int a,b,c;

a=10;b=20;

c=a+b;

printf(“%d”,c);

}

Page 64: Complete C Slides

Key Points

C program is a collection of one or more functions.

A function gets called when the function name is followed by a

semicolon. For example, main( )

{

argentina( ) ;

}

A function is defined when function name is followed by a pair of

braces in which one or more statements may be present.

For example,

argentina( )

{

statement 1 ;

statement 2 ;

statement 3 ; }

Page 65: Complete C Slides

Any function can be called from any other function. Even

main( ) can be called from other functions.

For example,

main()

{

message( ) ;

}

message( )

{

printf ( "\nCan't imagine life without C" ) ;

main( ) ;

}

Page 66: Complete C Slides

A function can be called any number of times.

For example,

main( )

{

message( ) ;

message( ) ;

}

message( )

{

printf ( "\n Hai Welcome to C Language !!" ) ;

}

Page 67: Complete C Slides

Advantages of Functions

Divide and conquer

Manageable program development

Software reusability

Use existing functions as building blocks for new programs

Avoid code repetition

Page 68: Complete C Slides

Types of functions

There are mainly 4 types of functions

1.Function with no arguments and no return values

2.Functions with arguments and no return values

3.Functions without arguments and no return values

4. Functions with arguments and return values

Page 69: Complete C Slides

Function with no arguments and no return values

void main()

{

Printf(“welcome to c”);

message();

printf(“for good learning c”);

}

Void message()

{

printf(“all the best”);

}

Page 70: Complete C Slides

Function with arguments and no return values

#include<stdio.h>

Void main()

{

int a,b,c;

a=10;b=20;

add(a,b);

}

Void add( int x,int y)

{

printf(“%d”,(x+y));

}

Page 71: Complete C Slides

Function without arguments and return values

#include<stdio.h>

Void main()

{

Int c;

c= add();

Printf(“%d”,c);

}

int add()

{

int a,b,c;

a=10;b=20;

return(a+b);

}

Page 72: Complete C Slides

Function with arguments and return values

#include<stdio.h>

Void main()

{

int a,b;

a=10;b=20;

c= add(a,b);

Printf(“%d”,c);

}

int add (int x, int y)

{

return(x+y);

}

Page 73: Complete C Slides

Invoking functions

Function can be be invoked by using two ways

1.Call by value

2.call by reference

Page 74: Complete C Slides

Call by value

If a function is invoked by passing values of actual arguments to is corresponding formal arguments.

Whenever using call by value, the values of actual arguments is copied into its corresponding formal arguments

Whenever we make changes in formal arguments which will not reflect to its corresponding actual arguments.

Page 75: Complete C Slides

Example

#include<stdio.h>

Void exchange(int a,int b)

{

int t;

t=a;

a=b;

b=t;

printf(“the values of a and b are:%d%d”,a,b);

}

Main()

{

int a,b;

a=10;b=20;

exchange(a,b);/* call by value procedure*/

}

Page 76: Complete C Slides

2. Call by reference

If a function is invoked by passing the address of

actual arguments to its corresponding formal

arguments.

If we make changes in the formal arguments ,all the

values will reflected into its corresponding actual

arguments.

Page 77: Complete C Slides

Example #include<stdio.h>

Void exchange(int *a,int *b)

{

int t;

t=*a;

*a=*b;

*b=t;

printf(“the values of a and b are:%d%d”,*a,*b);

}

Main()

{

int a,b;

a=10;b=20;

exchange(&a,&b);/* call by reference procedure*/

}

Page 78: Complete C Slides

Function Prototype

Function name

Parameters – what the function takes in

Return type – data type function returns (default int)

Used to validate functions

Prototype only needed if function definition comes after use in

program

The function with the prototype

int maximum( int, int, int );

Takes in 3 ints

Returns an int

Page 79: Complete C Slides

Recursion Function

A function call by itself

Example:

int main()

{

int result, number;

. . .

result = factorial( number );

}

int factorial( int num ) /* Function definition */

{

. . .

if ( ( num > 0 ) || ( num <= 10 ) )

return( num * factorial( num - 1 ) ); /*call itself */

}

Page 80: Complete C Slides

Structures

A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.

Structures help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities.

An example of a structure is the payroll record: an employee is described by a set of attributes such as name, address, social security number, salary, etc.

Page 81: Complete C Slides

Declaring a Structure

The C language provides the struct keyword for declaring a

structure. The following is a structure declaration for employee

attributes.

struct empdata

{

int empno;

char name[10];

char job[10];

float salary;

};

Page 82: Complete C Slides

Declaring a Structure Variable

struct empdata

{

int empno;

char name[10];

char job[10];

float salary;

} emprec; /* emprec is a variable of structure type empdata */

Or a structure can be declared separately as:

struct empdata emprec;/* emprec is a variable of structure type empdata */

Page 83: Complete C Slides

Accessing Elements of a Structure

Once a structure variable has been declared, the individual members of the structure can be accessed by prefixing the structure variable to the element of the structure.

struct empdata

{

int empno;

char name[10];

char job[10];

float salary;

}

struct empdata emprec;

emprec.empno=101;

/* referring to the element of the structure variable emprec */

Page 84: Complete C Slides

Structure Example #include< stdio.h >

void main() { struct

{

int id_no; char name[20];

char address[20]; int age; }newstudent;

printf(“Enter the student information”); printf(“Now Enter the student id_no”); scanf(“%d”,&newstudent.id_no); printf(“Enter the name of the student”); scanf(“%s”,&new student.name); printf(“Enter the address of the student”); scanf(“%s”,&new student.address);

printf(“Enter the age of the student”);

scanf(“%d”,&new student.age);

printf(“Student information\n”);

printf(“student

id_number=%d\n”,newstudent.id_no);

printf(“student

name=%s\n”,newstudent.name);

printf(“student

Address=%s\n”,newstudent.address);

printf(“Age of

student=%d\n”,newstudent.age);

}

Page 85: Complete C Slides

Initializing of a structure

struct empdata

{

int empno;

char name[10];

char job[10];

float salary;

}emprec={101,”Arun”,”Developer”,”20000};

Page 86: Complete C Slides

Array of Structures

Just as it is possible to declare arrays of primitive data types, it should also be

possible to declare arrays of structures as well.

Consider the structure declaration for the employee details used earlier.

struct empdata

{

int empno;

char name[10];

char job[10];

float salary;

};

struct empdata employee_array[4];

Page 87: Complete C Slides

Structure Example #include< stdio.h >

{ struct info { int id_no; char name[20]; char address[20]; char combination[3]; int age; } struct info std[100]; int I,n; printf(“Enter the number of students”); scanf(“%d”,&n); printf(“ Enter Id_no,name address combination age\m”); for(I=0;I < n;I++) scanf(%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,&std[I].age); printf(“\n Student information”); for (I=0;I< n;I++) printf(“%d%s%s%s%d\n”, ”,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age); }

Page 88: Complete C Slides

Structure within Structure

A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures.

struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; char combination[3]; int age; structure date def; structure date doa; }oldstudent, newstudent;

Page 89: Complete C Slides

Structures & Files

Consider a situation where your application needs to read records from a file for processing.

The general approach would be to read the various fields of a record into corresponding memory variables.

Computations can then be performed on these memory variables, the contents of which can then be updated to the file.

But, this approach would involve manipulating the current file offset for the relevant fields that need to be updated.

Page 90: Complete C Slides

Writing Records On To a File

The fwrite( ) function allows a structure variable to be written on to a file.

The following statement writes the structure variable salesvar on to a file “SALES.DAT, which is pointed to by the FILE type pointer fp:

fwrite( &salesvar, sizeof(struct salesdata), 1, fp);

Page 91: Complete C Slides

Reading Records from a File

Records can be read from a file using fread( ). The corresponding read statement using fread( ) for the earlier fwrite( ) statement would be:

fread(&salesvar, sizeof(struct salesdata), 1, fp);

Here, the first parameter &salesvar is the address of the structure variable salesvar into which 1 record is to be read from the file pointed to by the FILE type pointer fp.

The second parameter specifies the size of the data to be read into the structure variable.

Page 92: Complete C Slides

Structures with pointers

We can store the address structure variable in a pointer variable

The pointer variable also should be the variable for the structure data type;

#include<stdio.h>

struct student

{

int rollno;

int marks;

}s={101,99},*p;

Page 93: Complete C Slides

Accessing structure by pointer

#include<stdio.h>

struct student

{

int rollno;

int marks;

}s={101,99},*p;

main()

{

p=&s;

printf("%d",(*p).rollno);

printf("%d",(*p).marks);

}

Page 94: Complete C Slides

Accessing structure by pointer

With pointers, though, in accessing structure members an arrow notation is used, rather than the dot notation:

struct student

{

int rollno;

int marks;

}s={101,99},*p;

main()

{

p=&s;

printf("%d",p->rollno);

printf("%d",p->rollno);

getch();

}

Page 95: Complete C Slides

Passing structure in a function

struct student{

int rollno;

int marks;

}s={101,99},*p;

main()

{

p=&s;

printf("%d",p->rollno);

printf("%d", p->marks);

f1(&s);

printf("%d", p-> rollno);

printf("%d", p-> marks);

}

f1(struct student *s1)

{

s1->rollno=103;

}

Page 96: Complete C Slides

Pointers

Pointers is a memory variable that stores a memory

address

It always denoted by (*) asterisk symbol

Features Pointers save the memory space.

Direct access to memory location

Useful for representing two-dimensional & Multi- dimensional array

Declaration

int *x;

float *f;

Page 97: Complete C Slides

Example for Pointer

# include <stdio.h>

# include <conio.h>

void main()

{

int v=10, *p;

clrscr();

p=&v;

printf(“ \n Address of V = %u ”,p);

printf(“ \n Value of V = %d ”,*p);

printf(“ \n Address of P = %u ”,&p);

}

Output

Address of V = 4060

Value of V = 10

Address of P = 4062

Page 98: Complete C Slides

Pointers

Pointers are variables that contain memory

addresses as their values.

A variable name directly references a value.

A pointer indirectly references a value. Referencing

a value through a pointer is called indirection.

A pointer variable must be declared before it can be

used.

It always denoted by (*) asterisk symbol

Page 99: Complete C Slides

Concept of Address and Pointers

Memory can be

conceptualized as a

linear set of data

locations.

Variables reference the

contents of a locations

Pointers have a value of

the address of a given

location

Contents1

Contents11

Contents16

ADDR1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6

* * *

ADDR11

* *

ADDR16

Page 100: Complete C Slides

Syntax:

datatype * variablename;

Example:

int *a;

Indirection operator

identifier

Note: A normal variable(identifier) declared with * symbol is called

pointer variable.

Pointer variable

Page 101: Complete C Slides

Examples of pointer declarations:

int *a;

float *b;

char *c;

The asterisk, when used as above in the declaration,

tells the compiler that the variable is to be a pointer, and

the type of data that the pointer points to, but NOT the

name of the variable pointed to.

Page 102: Complete C Slides

Consider the statements:

#include <stdio.h>

int main ( )

{

int *aptr ; /* Declare a pointer to an int */

float *bptr ; /* Declare a pointer to a float */

int a =10; /* Declare an int variable */

float b =2.5f; /* Declare a float variable */

Page 103: Complete C Slides

aptr = &a ;

bptr = &b ;

printf(“%u”,&a);

printf(“%u”,aptr);

printf(“%d”,a);

printf(“%d\n”,*aptr);

printf(“%u”,&b);

printf(“%u”,bptr);

printf(“%f”,b);

printf(“%f”,*bptr);

return 0 ;

}

1000 10

1500 2.5

aptr

bptr

1000

1500

a

b

Page 104: Complete C Slides

Output:

1000 1000 10 10

1500 1500 2.500000 2.500000

Page 105: Complete C Slides

Use of & and *

When is & used?

When is * used?

& -- "address operator" which gives or produces

the memory address of a data variable

* -- "dereferencing operator" which provides the

contents in the memory location specified by a

pointer

Page 106: Complete C Slides

Arithmetic and Logical Operations on

Pointers

A pointer may be incremented or decremented

An integer may be added to or subtracted from a pointer.

Pointer variables may be subtracted from one another.

Pointer variables can be used in comparisons, but usually only in a comparison to NULL.

Page 107: Complete C Slides

Arithmetic Operations on Pointers

When an integer is added to or subtracted from a

pointer, the new pointer value is changed by the

integer times the number of bytes in the data

variable the pointer is pointing to.

For example, if the pointer valptr contains the

address of a double precision variable and that

address is 234567870, then the statement:

valptr = valptr + 2;

would change valptr to 234567886

Page 108: Complete C Slides

Arithmetic Operations on Pointers

Example:

int *a;

int b=10;

a=&b;

a++;

1000

a

2.5 b

1000

Before this Statement

After this Statement

a++ a=a+1

1000++ a=1000+1

a value is 1002

Integer 1=2bytes

Page 109: Complete C Slides

Arithmetic Operations on Pointers

Example:

#include< stdio.h > main() { int *ptr1,*ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 –6; y=6*- *ptr1/ *ptr2 +30; printf(“\nAddress of a +%u”,ptr1); printf(“\nAddress of b %u”,ptr2); printf(“\na=%d, b=%d”,a,b); printf(“\nx=%d,y=%d”,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(“\na=%d, b=%d”,a,b); }

Page 110: Complete C Slides

Pointer to arrays

An array is actually very much like pointer.

We can declare the arrays first element as

a[0] or as int *a

because a[0] is an address and *a is also an address

the form of declaration is equivalent.

The difference is pointer is a variable and can appear

on the left of the assignment operator that is lvalue.

The array name is constant and cannot appear as the

left side of assignment operator.

Page 111: Complete C Slides

Pointer to arrays

/* A program to display the contents of array using pointer*/

main()

{

int a[100];

int i,j,n;

printf(“\nEnter the elements of the array\n”);

scanf(“%d”,&n);

printf(“Enter the array elements”);

for(I=0;I< n;I++)

scanf(“%d”,&a[I]);

printf(“Array element are”);

for(ptr=a,ptr< (a+n);ptr++)

printf(“Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr);

}

Strings are characters arrays and here last element is \0 arrays

and pointers to char arrays can be used to perform a number of

string functions.

Page 112: Complete C Slides

File I/O in C

Page 113: Complete C Slides

Files in C

In C, each file is simply a sequential stream of

bytes. C imposes no structure on a file.

A file must first be opened properly before it can be

accessed for reading or writing. When a file is

opened, a stream is associated with the file.

Successfully opening a file returns a pointer to (i.e.,

the address of) a file structure, which contains a file

descriptor and a file control block.

Page 114: Complete C Slides

Files in C

The statement:

FILE *fp1, *fp2 ;

declares that fptr1 and fptr2 are pointer variables of

type FILE. They will be assigned the address of a

file descriptor, that is, an area of memory that will

be associated with an input or output stream.

Whenever you are to read from or write to the file,

you must first open the file and assign the address

of its file descriptor (or structure) to the file pointer

variable.

Page 115: Complete C Slides

Opening Files

Syntax:

FILE *fp;

fp=fopen(“filename”,”mode”);

The statement:

fp1 = fopen ( "mydata", "r" ) ;

would open the file mydata for input (reading).

Page 116: Complete C Slides

Opening Files

The statement:

fp = fopen ("results", "w" ) ;

would open the file results for output (writing).

Once the files are open, they stay open until you

close them or end the program (which will close all

files.)

Page 117: Complete C Slides

Testing for Successful Open

If the file was not able to be opened, then the value

returned by the fopen routine is NULL.

For example, let's assume that the file mydata does

not exist. Then:

FILE *fptr1 ;

fptr1 = fopen ( "mydata", "r") ;

if (fptr1 == NULL)

{

printf ("File 'mydata' did not open.\n") ;

}

Page 118: Complete C Slides

Open Mode

"r“ Open text file for reading only

"w“ Truncate to 0 length, if existent, or create text

file for writing only.

"a“ Append; open or create text file only for

writing at end of file

"r+“ Open text file for update (reading and

writing)

"w+“ Truncate to 0 length, if existent, or create

text file for update

"a+“ Append; open or create text file for update,

writing at end of file

Page 119: Complete C Slides

File operation functions in C

Function Name Operation

fopen() Creates a new file for use

Opens a new existing file for use

Fclose() Closes a file which has been opened for

use

getc() Reads a character from a file

putc() Writes a character to a file

Page 120: Complete C Slides

File operation functions in C

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

getw() Reads a integer from a file

putw() Writes an integer to the file

Page 121: Complete C Slides

fseek() Sets the position to a desired point in the

file

ftell() Gives the current position in the file

rewind() Sets the position to the begining of the file

File operation functions in C

Page 122: Complete C Slides

getc() & putc()

#include< stdio.h > main() { file *f1; printf(“Data input output”); f1=fopen(“Input”,”w”); /*Open the file Input*/

while((c=getchar())!=EOF) /*get a character from key board*/

putc(c,f1); /*write a character to input*/

fclose(f1); /*close the file input*/ printf(“\nData output\n”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/

while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); }

Page 123: Complete C Slides

getw() & putw()

#include< stdio.h > main() { FILE *f1,*f2,*f3; int number I; printf(“Contents of the data file\n\n”); f1=fopen(“DATA”,”W”); for(I=1;I< 30;I++) { scanf(“%d”,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(“DATA”,”r”); f2=fopen(“ODD”,”w”); f3=fopen(“EVEN”,”w”);

Page 124: Complete C Slides

getw() & putw()

while((number=getw(f1))!=EOF)/* Read from data file*/

{ if(number%2==0) putw(number,f3);/*Write to even file*/ else putw(number,f2);/*write to odd file*/

} fclose(f1); fclose(f2); fclose(f3); f2=fopen(“ODD”,”r”); f3=fopen(“EVEN”,”r”); printf(“\n\nContents of the odd file\n\n”); while(number=getw(f2))!=EOF) printf(“%d%d”,number); printf(“\n\nContents of the even file”); while(number=getw(f3))!=EOF) printf(“%d”,number); fclose(f2); fclose(f3);

}

Page 125: Complete C Slides

Reading From Files

In the following segment of C language code:

int a, b ;

FILE *fptr1, *fptr2 ;

fptr1 = fopen ( "mydata", "r" ) ;

fscanf ( fptr1, "%d%d", &a, &b) ;

the fscanf function would read values from the file

"pointed" to by fptr1 and assign those values to a

and b.

Page 126: Complete C Slides

End of File

The end-of-file indicator informs the program when

there are no more data (no more bytes) to be

processed.

There are a number of ways to test for the end-of-file

condition. One is to use the feof function which

returns a true or false condition: fscanf (fptr1, "%d", &var) ;

if ( feof (fptr1) )

{

printf ("End-of-file encountered.\n”);

}

Page 127: Complete C Slides

End of File

There are a number of ways to test for the end-of-

file condition. Another way is to use the value

returned by the fscanf function:

int istatus ;

istatus = fscanf (fptr1, "%d", &var) ;

if ( istatus == EOF )

{

printf ("End-of-file encountered.\n”) ;

}

Page 128: Complete C Slides

Writing To Files

Likewise in a similar way, in the following segment

of C language code:

int a = 5, b = 20 ;

FILE *fptr2 ;

fptr2 = fopen ( "results", "w" ) ;

fprintf ( fptr2, "%d %d\n", a, b ) ;

the fprintf functions would write the values stored in

a and b to the file "pointed" to by fptr2.

Page 129: Complete C Slides

Closing Files

The statements:

fclose ( fptr1 ) ;

fclose ( fptr2 ) ;

will close the files and release the file descriptor

space and I/O buffer memory.

Page 130: Complete C Slides

Reading and Writing Files

#include <stdio.h>

int main ( )

{

FILE *outfile, *infile ;

int b = 5, f ;

float a = 13.72, c = 6.68, e, g ;

outfile = fopen ("testdata", "w") ;

fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ;

fclose (outfile) ;

Page 131: Complete C Slides

Reading and Writing Files

infile = fopen ("testdata", "r") ;

fscanf (infile,"%f %d %f", &e, &f, &g) ;

printf ("%6.2f%2d%5.2f\n", a, b, c) ;

printf ("%6.2f,%2d,%5.2f\n", e, f, g) ;

}

12345678901234567890

****************************

13.72 5 6.68

13.72, 5, 6.68

Page 132: Complete C Slides

fseek()

int fseek ( Stream, Offset, Whence);

where stream -- file pointer

offset -- no of position in bytes

whence– from position

**whence must be one of the values 0, 1, or 2

Whence value:

0 Beginning of the file

1 Current position

2 End of the file.

Page 133: Complete C Slides

ftell() & rewind()

Ftell();

FILE *stream;

long ftell (stream);

Rewind():

FILE *stream;

void rewind (stream);

Page 134: Complete C Slides

Pre Processing

in

C

Page 135: Complete C Slides

Pre Processing

Refers before compiling the c program.

Loads the template before compiling.

Syntax

#Macro Template Macro Expansion

Page 136: Complete C Slides

Types of Macros

Defining Macros

File Inclusion

Conditional Macros

Special cases

Page 137: Complete C Slides

Defining Macros

#define <Label>(parameterlist)<Expansion>

main()

{

……………

…….

<Label>

}

Page 138: Complete C Slides

Defining Macros

Example:

#include <stdio.h>

#define PI 3.14

#define AREA(radius) (PI*radius*radius)

main()

{

float areas[3]={AREA(1),AREA(2),AREA(3)};

int count;

for (count=0; count <3; count++) {

printf("Circle area=%f\n",areas[count]);

}

return 0;

}

Page 139: Complete C Slides

File Inclusion

#include<file name>

(or) #include ”filename”

main()

{

…..

…..

}

Page 140: Complete C Slides

Conditional Macros

Syntax:

#ifdef MACRO

controlled text

#endif /* MACRO */

Syntax:

# if expression

controlled text

# endif /* expression */

Page 141: Complete C Slides

Conditional Macros

Syntax: #if expression

text-if-true

#else /* Not expression */

text-if-false

#endif /* Not expression */

Page 142: Complete C Slides

Example for elif

Example:

#if X == 1

...

#elif X == 2

...

#else /* X != 2 and X != 1*/

...

#endif /* X != 2 and X != 1*/

Page 143: Complete C Slides

Thank You….