Sunday, April 6, 2008

Arrays in C

Arrays is a type of Data Structure
  • An array is a collection of elements of the same data type
  • All the elements have the same name
  • They are differentiated from one another by their positions (index) within the array .
  • Data is stored in contiguous (one next to the other ) memory locations.Hence array processing is faster.

e.g. int arr[ 5 ] = { 1,2,5,7,9 } ;

Here arr is an array of 5 integers referred as arr[0] , arr[1] , arr[2] , arr[3] , arr[4]

Memory mapping:

arr[0] arr[1] arr[2] arr[3] arr[4]

1 2 5 7 9

Index or subscript of an array :- The numbers 0 , 1, 2 , 3, …. are used as array index to refer to each element of the array. The first element of array is indexed as 0 and not 1. Hence arr[4] is the 5th element. Arrays are known as indexed or subscripted variables

Arrays and Loops :

Generally a loop is used to process all the elements of the array

Programs:

void main( )

{

int i , a[5] = { 1, 2, 5, 7, 9 } ; /* An array can be assigned */

/* while declaring */

clrscr( ) ;

for( i = 0 ; i < style=""> i++ )

printf(“ %d ”, a[ i ] ) ; /* Output */

} /* 1 2 5 7 9 */

void main( )

{ /* F O C U S */

int i;

char a[5] = { ‘F’, ‘O’, ‘C’, ‘U’, ‘S’ };

clrscr();

for( i = 0 ; i< style=""> i++)

putchar (a [ i ] ) ;

}


Two Dimensional Array

  • A Two dimensional array is a data structure
  • It means an array involving two dimensions with rows and columns .
  • We interpret 1st dimension as row and 2nd as column (matrix).

eg. int a [ 2 ] [ 3 ] = { 1 , 5 , 7 , 9 , 11 , 25 } ;

a[2][3] has 2 rows with each row having 3 columns

Human interpretation

column# 0 1 2

row#0 0 1 5

row#1 9 11 25

MEMORY MAPPING :The elements of a 2d array are stored in contiguous locations just like a single dimensional array

1 5 7 9 11 25

0th array 1st array

A two dimensional array is a collection of single dimensional arrays.

MEMORY ALLOCATION =No.of elements X Sizeof Datatype = 6 X 2 = 12 bytes

Two Dimensional Arrays and Nested Loops :

Generally nested loops are used to process all the elements of a 2d array. The outer loop gen. refers to rows and the inner loop to columns.

eg:

main( )

{

int i , j ;

int a[2][3] = { 10, 20 , 30 , 4 , 5 , 6 } ;

clrscr( ) ;

for ( i = 0; i <>

for ( j = 0 ; j <>

printf ( “%5d“ , a [ i ] [ j ] ) ;

}

A 2D array can be used to store a collection of words , lines (strings)

In the following example note the use of a single loop to process the names.

main( )

{

char names[5][10]; /* 5 names each with max 10 characters */

int j ;

for ( j = 0 ; j <>

{

printf(“ Enter name : “);

gets ( names [ j ] );

}

printf(“ You have entered : \n\n “);

for( j = 0 ; j <>

puts( names [ j ] ) ;

getch();

return 0 ;

}



A Data Structure is a way of managing data i.e., storing and retrieval .

· C provides basic data types char , int , float , double and pointers

· It is possible to derive several data structures like arrays , linked list, queue from these basic data types to suit our applications

Saturday, April 5, 2008

Functions in C

User Defined Functions

What is a Function ??

  • A function is a named code block
  • It is created for a specific purpose
  • The name of a function is a pointer to the starting address of the function code in memory

For e.g : A function may carry out some complex calculations based on a formula and return an end result .You may have to pass some values for this calculation which the function utilizes for calculations

Advantages of Functions :

  • A function can be called upon repeatedly
  • Arguments may be passed to a function
  • A function may return a valueFunctions make a large program modular and easy to manage

Library Functions:

Functions which come with C compiler are known as Standard Library Functions These functions are useful for several commonly carried out tasks

E.g. printf( ) , scanf ( ) , getch( ) , clrscr( ) etc…..

User Defined Functions (UDF) :

We can create functions to suit our needs.

Every function has

  • Name
  • Return data type
  • Arguments list (optional)

Format of a function declaration :-

Return Data Type Function name ( arguments / parameters List ) ;

Eg. void display(void);

Name of the function : display

Return data type void (nothing is returned)

Argument type void (nothing is passed)

float CalculateArea ( float radius) ;

Name of the function : CalculateArea

Return data type float

Argument One argument is passed of type float

float amount( float p , int n , float r ) ;

Function prototype

A Function prototype/declaration informs the model of the function. It consists of:

1) Function name 2) Return data tytpe 3)Argument list

For e.g int f1 ( int ) ;

Function Definition :

We define a code block for a function. This states what is the action to be carried out if the function is called

int f1(int i)

{

-------

}

Function Call

A function is called in another function by actually passing arguments

X = f1(10);

Program:

#include

#include

float area( float radius); /* Function prototype */

float area ( float r) /* Function definition */

{

return ( 3.14 * r * r);

}

main( )

{

float r, a;

clrscr( );

printf(“Enter radius :- “);

scanf(“%f” , &r);

a = area ( r ); /* Function call */

printf( “ AREA = %f Square Units “ , a ) ;

getch( ) ;

return 0 ;

}

Note : A function cannot be defined inside another function in C

Recursive Functions

A recursive function is one that calls itself but which halts at some definite point to avoid infinite recursion. This concept can be explained by reference to the factorial function in mathematics. Given a positive n, the factorial of that number can be defined as 1! = 1

n! = (n) ( ( n – 1 )! )

Suppose we wish to find the factorial of 7. Note that the second line in the first formula makes reference to itself, which is what we mean by recursion. Therefore,

7! = ( 7 ) ( 6 ! )

6 ! = ( 6 ) ( 5 ! ),

7 ! = ( 7 ) ( 6 ) ( 5 ) ( 4 ) ( 3 ) ( 2 ) ( 1 !) but 1 ! = 1

The recursive function factorial calls itself.

long factorial ( int n )

{

if ( n = = 1 )

return 1L ;

else

return ( n * factorial ( n – 1 ) );

}

Program prints the revere of input text data. It uses a recursive function called reverse( )

#include

void reverse ( void );

void reverse( void )

{

char ch;

if ( (ch = getchar( ) ) ! = EOF )

/* Accept a character and push it into stack */

reverse ( ) ; /* recursion ; Function calls itself */

putchar ( ); /* pop out from the stack

}

void main ( )

{

clrscr( );

printf( “ Enter text , press ^z to end : );

reverse (); /* Call reverse ( ) function */

getch();

return 0;

}

Recursive functions look easy to code but involve stack overhead and hence come with performance penalty.

Friday, April 4, 2008

Control Structures

Control Structures decide the flow of control.

Flow of control means which code line will be executed after which code line in a program. There are 3 types of flow in a computer program

1. Sequential

2. Branching

3. Iterations or Looping

Sequential:

The natural flow of control is sequential. This means the computer executes one line after another line of a program

Branching:

Based on the outcome of a condition a program branches to different lines of coding

A condition is true if it evaluates to a non-zero value

A condition is false if it evaluates to zero

Key words used for branching are – if, switch, goto.

The format of a branch with if :

1. if ( somecondition)

some action

2. if (some condition )

{

Action if the condition is true

-----------

}

else

{

Action if the condition is false

-----------

}


Nested if :-

An if within another if is called as nesting

if (condition)

if(condition)

Someaction ;

else

someaction ;

else

Someaction

Note : An else is related to a nearest if
Code Block : If you want more than one statement to be executed when a condition is satisfied then enclose them in a code block { }

goto : The keyword goto unconditionally transfers control to a label. Avoid using goto as it results in a code difficult to understand and maintain.

Format of goto :-

goto somelabel
------

------

somelabel :

someaction

switch

switch is a keyword. It is useful for multiple branching. Based on the value of a variable or an expression the program branches to different actions

Program:

void main( )

{

int option;

clrscr();

printf(“Enter an option [1 – 3 ] : “);

scanf(“ %d”, &option);

switch ( option )

{

case 1 :

printf( “ ONE “) ; break;

case 2 :

printf( “ TWO “) ; break;

case 3 :

printf( “ THREE “) ; break;

default :

printf(“ \n You did not enter in range [1 – 3 ] “);

}

}

Note:

· Switch is not a loop.

· We can pass int or char data type or an expression involving arithmetical operators to switch .

· Matching is done only once.

· If a match is found then subsequent statements are executed till a break or a closing brace is encountered. This is called CASCADING effect of a switch.

· If a match is not found then statements following default is executed.

· Default may be placed anywhere.

/* Program: Accept a character and display if it is a vowel or not. */

void main( )
{

char ch;
clrscr();
printf(“Enter a character : “);
scanf(“ %c”, &ch);

switch ( ch )

{

case ‘A’ : case ‘a’ : case ‘E’: case ‘e’:

case ‘I’ : case ‘I’ : case ‘O’: case ‘o’:

case ‘U’ : case ‘u’ :

printf( “VOWEL “); break;

default : printf(“ \n NOT A VOWEL “);

}

}

Loops or Iteration

Loop means your program keeps on executing the same lines of codes again and again until some condition is met . This is called as a loop. The programmer must ensure that a loop terminates properly Key words used for looping are – for, while, do-while.

Programs on looping:

E.g. of For loop:

main ( )

{

int i;

clrscr();

for ( i = 0 ; i < style=""> i++ )

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

getch();

return 0;

}

Output:

0 1 2 3 4

E.g. of While loop:

main()

{

int i;

i=0;

while( i<5)

{

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

i++;

}

printf(“\n I = %d “, i);

getch();

return 0;

}

Output:

0 1 2 3 4

I = 5

E.g of Do while loop:

main()

{

int i;

i = 0;

do{ printf( “%d”, i); } while( i > 10);

getch();

return 0;

}

Output:

0

Nested Loops

Nested loops means one loop inside another loop. The inner loop executes fully from initialize to finish for every single execution of the outer loop

For e.g :

for(…….) /* Outer loop */

{ -----

-----

for(…….) /* Inner loop */

{ -----

}

}



for( i=0, k=1; i < 5 ; i++)

for(j=0; j<3; j++ , k++)

printf(“%d\t ”, k);

NOTE:
The inner loop executes from start to finish from every one pass of the outer loop.
The values of i, j , k can be traced as follows: ( Dry run)

i j k

0 0 1

0 1 2

0 2 3

1 0 4

1 1 5

1 2 6

2 0 7

2 1 8

2 2 9

3 0 10

3 1 11

3 2 12

4 0 13

4 1 14

4 2 15


continue and break

Continue: Transfers control to the top of the loop ignoring further statements.

Break: It breaks the execution of the loop in between and goes out of the loop.

Program:
main( )
{

int i=0;

while ( i <>

{

printf(“i=%d”, i);

i+=5;

if ( i == 5)

continue;

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

if ( i == 10 )

break;

printf(“ \n GOOD “);

}

printf(“\n OK ! “);
getch();

return 0;

}

Wednesday, April 2, 2008

Understanding Operators in C

Operators in C

C has a rich set of operators that makes C so powerful. Operators may be classified, for the purpose of understanding as follows:

1. Classify operators on the basis of Number of operands:-

Unary Operator which takes one operand

Binary Operator which takes two operands

Ternary Operator which takes three operands

E.g of Unary Operator -x

Here the Operator is unary negation i.e. -

and the Operand is the variable x .

Unary Operators are ! ( not operator.)

& ( address operator )

++ (increment operator ) ,

-- (decrement operator )

- (Unary negation)

* (Indirection or dereferencing operator)


E.g of Binary Operator a + b

Here the operator is addition +

and the operands are a and b

2. Classify operators on the basis of the operations they perform :-

The operators are classified as:-

-Arithmatic Operators ( + , - , * , / etc)

-Relational Operators (> , < , >= , <= , = = )

-Logical Operators (&& , || , ! )

-Assignment Operators ( = , *= , += , /= , %= , -=)

and so on

Precedence & Associativity of operators :-

It is very important to understand these two terms in C.

Precedence :- When there are several operators in one expression , which one will be carried out first? This is what precedence is all about .

Note :-

Unary Operators have a higher precedence than binary Operators.

Arithmetic operators have a higher precedence to relational operators.

Relational operators have a higher precedence to logical operators.

Within arithmetic operators / , * , % have a higher precedence to + , - .

/ , * , % have equal precedence.

Associativity: Will the operator scan the left side data first or the right side data ? Associativity is specified as:

Left -> Right (L -> R)

Right -> Left (R -> L)

1. The arithmetical addition operator + associates L -> R. This means it reads the data on the left side first and then the data on the right side.

2. The assignment operator = associates R -> L. This means it reads the data on the right side first and then assigns it to the variable on the right side.

Some discussion on some operators:

Arithmetic operators :

All are binary operators, associate L - > R except unary negation which associates R -> L .

* Multiplication Operator

/ Division Operator

% Modulus Operator returns the remainder of integral division

+ Addition

- Subtraction, Unary negation

Note :

% operator is applicable only to char and int types; cannot be applied to floating point numbers. The % operator returns a periodic value. x % n always returns a value between 0 to n-1 for any value of x . The % operator returns the sign of the numerator irrespective of the sign of denominator.

Program :

Accept an amount and rate of an item, outputs how many items can be purchased and what is the balance amt

main( )

{

int amt, rate;

clrscr( );

printf(“Enter amount : ”);

scanf(“%d” , &amt);

printf(“Enter rate : “);

scanf(“%d” , &rate);

printf(“No. of articles = %d\nBalance Rs. %d”, amt/rate,

amt % rate) ;

getch( );

return 0;

}

Relational Operators: Binary operators, associate L -> R

> (Greater than)

< (Less than)

>= (Greater than or equal to)

<= (Less than or equal to)

= = (Relational equality)

!= (Relational inequality)

Note:

Relational operators return 1 if true and 0 if false.

<, >, >=, <= have equal precedence

= = , != have equal precedence

<, >, >=, <= have higher precedence to = =, !=

Relational operators have a lower precedence to arithmetical operators.


Logical Operators :

&& logical and operator (binary, associates L -> R)

|| logical or operator (binary, associates L -> R)

! logical not operator (unary, associates R -> L)

Truth table for logical operators: ( T : true F: false)

! operator

x

!x

T

F

F

T

|| operator

x

y

X || y

T

T

T

T

F

T

F

T

T

F

F

F

&& operator

x

y

X && y

T

T

T

T

F

F

F

T

F

F

F

F

Note:

Logical operators return 1 if true and 0 if false.

Any expression evaluating to a non zero value is treated as true

Any expression evaluating to a value of zero is treated as false

The logical not operator ( ! ) has the highest precedence

&& operator has higher precedence to || operator

Both && and || operator have lower precedence to relational operators.

Program:

Accept a character from user. Check if it is in upper case or lower case

main( )

{

char ch ;

clrscr( );

printf(“Enter a character:- ”);

scanf(“%c” , &ch);

if( ch >= ‘A’ && ch <=’Z’)

printf(“%c is in upper case”, ch);

else

if( ch >= ‘a’ && ch <= ‘z’)

printf(“%c is in lower case” , ch );

else

printf(“%c is neither in lower case nor in upper case”);

getch( );

return 0;

}

Program 2:

main( )

{

clrscr( );

printf(“%d %d %d %d” , 10 > 20 , 20 ==20 , !( 50 != 100) , 20 && 23);

}

Output: 0 1 0 1

Explanation:

10 > 20 is false , hence 0, 20 == 20 is true hence 1

50 != 100 is true hence 1 ; not true is false; hence 0

20 && 23 is interpreted as true and true, which evaluates to 1


Increment and Decrement operators:- ++ , --

Both are unary operators, associating from R -> L , with highest priority.

The ++ operator increases the value of its operand by one, while the decrement operator decreases the value of its operand by one.

Program:

main( )

{

int a = 10 ;

a++;

printf(“a = %d” , a );

++a ;

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

}

Output: a = 11

a = 12

Post and pre increment/decrement

When the ++/-- operators are part of an expression, then there are two possibilities - post and pre increment/decrement.

x = ++a ;

This is interpreted as : first increase the value of variable a by one and then assign it to x

x = a++ ;

This is interpreted as : first assign the value of variable a to x, then increase the value of variable a by one before executing the next statement.