You are on page 1of 60

UNIT IV

C PROGRAMMING FUNDAMENTALS

Structured Programming A technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward Three types of control flow are used: (1) sequential, (2) selection, and (3) iteration. All programs can be written in terms of only three control structures The sequence structure Unless otherwise directed, the statements are written. The selection structure Used to choose among alternative courses of action. The repetition structure executed in the order in which they are

Allows an action to be repeated while some condition remains true.

The smallest element in the C language is the token. It may be a single character or a sequence of characters to form a single item. Tokens can be:

Numeric constants Character constants

String constants Keywords Names (identifiers) Punctuation Operators Numeric Constants Contain period but never contain comma. Examples:

123 98.6 1000000 Character Constants Surrounded on the single quotation mark. Examples:

A a $ 4 String Constants A sequence characters surrounded by double quotation marks.

Considered a single item. Examples: DAVV I like ice cream. 123 DHOOM-2 car

Keywords Sometimes called reserved words.

Are defined as a part of the C language. Cannot be used for anything else! Examples: int While For Identifiers Rules for identifiers Punctuation Semicolons, colons, commas, apostrophes, quotation marks, braces, brackets, and parentheses. First character must be an alphabet (or underscore) Must consist of only letters, digits or Only first 31 characters are significant. Cannot use a keyword. Must not contain white space. underscore.

;:,[]{}() VARIABLES A variable is a data name that may be used to store a data value. Variable names (identifiers) in C:

May only consist of letters, digits, and Underscores May be as long as you like, but only the first 31 characters are significant May not begin with a digit May not be a C reserved word (keyword)

Case Sensitivity C is case sensitive

It matters whether an identifier, such as a variable name, is uppercase or lowercase. Example: area Area AREA ArEa

Are all seen as different variables by the compiler. Data Type Data type is the type of the data that are going to access within the program user defined derived empty

primary

char int float double

typedef

Arrays Pointer Structures union

void

Integer data type Short integer or signed Occupies 1 byte in memory short int Long integer or signed long Occupies 4 bytes in memory int

Range Program runs faster Format specifier is %d Eg: short int b=2;

Range: Program runs slower Format specifier is %ld Eg: long int c;

Character, signed & unsigned Char or Signed character Unsigned character

Occupies 1 byte in memory

Occupies 1 byte in memory

Range

Range

Format specifier %c

Format specifier %c

When printed using %d control string corresponding ASCII number is printed

When printed using %d control string corres number is printed

char ch=b;

unsigned char ch=b;

Float and Double float Occupies 4 bytes in memory

Range Format specifier %f

float a;

double

Occupies memory Range

bytes

in

Format specifier %lf

double y;

Data type

Format specifiers

char unsigned char

%c %c

short or int unsigned int

%d %u

long unsigned long Data type

%ld %lu Format specifiers

float double long double

%f %lf %lf

User defined Syntax: Where type refers to an existing data type Identifier refers to the new name given to the data type E.g.: typedef int units; typedef float marks; Marks m1, m2, m3; The main advantage of typedef is that we can create meaningful data type names for increasing the readability of the program. Another user-defined data type- enumerated data type Syntax : enum identifier {value1,value2, value n}; enum day {mon,tue sun}; enum day week_st,week_end; week_st=mon; week_end=fri; if(week_st==tue)

week_end=sat; Void type The void type has no values. Used to specify the type of functions. void- does not return any value to the calling function

Operators

An operator is a symbol that specifies an operation to be performed on the operands. The data items that operators acts upon are called operands. Types of operators: Arithmetic operators Relational operators Logical operators Assignment operators Increment & decrement operators Conditional operators (ternary operators) Bitwise operators Special operators

Arithmetic operators operator Meaning E.g.

+ *

Addition Subtraction multiplication

2+9=11 9-2=7 2*9=18

/ % Arithmetic operators Main () { int a=10,b=3,c; c=a%b; printf (%d,c);

Division Modulo division

9/3=3 9%2=1

} Integer division truncates the fractional part Arithmetic operators can be classified as

i) Unary arithmetic - it requires only one operand e.g.: +x, -y; ii) Binary arithmetic - it require two operands e.g.: a+b, a-b, a/b; iii) Integer arithmetic - it require both operands are integer iv) Floating point arithmetic - it require both operands are float type for arithmetic operation operation result e.g.

int /int

int

10/3=3

real/int

real

5.0/2=2.5

int/real real / real

real real

5/2.0=2.5 5.0/2.0=2.5

Relational operators Relational operators are used to compare two or more operands. Operands may be variables, constant or expression. Meaning e.g. Return value

operator

< <=

is less than is less than or equal to

2<9 2<=2

1 1

>

is greater than

2>9

>=

is greater than or equal to

3>=2

== != Void main { printf(%d,5!=5); printf(%d,5==5); printf(%d,5>=5); printf(%d,5<=50); printf(%d,5!=3); } Logical operators

is equal to is not equal to

2==3 2!=2

0 0

Logical operators are used to combine the results of two or more conditions. operator && || Meaning Logical Logical AND OR e.g. (9>2)&&(17>2) (9>2)||(17==7) Return 1 1

! Assignment operator

Logical

NOT

29!=29

Assignment operators are used to assign a value or an expression or a value of a variable to another variable E.g.:

X= 10; X= a+b; X= y; Void main() { int i,j,k; k=(i=4,j=5); printf(%d,k); } Increment and decrement operators (unary operators) ++ -> adds one to the variable --> subtracts one from the variable. Meaning

Operators

++x --x X++ X-main() { printf(a %d,a++); printf(a %d,++a); printf(a %d,--a); printf(a %d,a--); }

Pre increment Pre decrement Post increment Post decrement

o/p 10 12 11 11 Conditional operator (or) ternary operator main() { int a=5,b=3,c; c=a>b?a:b; printf(%d,c); } Special operator Operators Meaning Conditional operator itself checks the condition on the condition and executes the statement depending

, sizeof() & and * . and -> Comma operator

Comma operator Size of operator Pointer operators Member selection operators

Usually the comma operator is used to separate the statement elements such as variables, constants or expression etc., and the operator is used to link the related expressions together, such expressions can be evaluated from left to right and the value of right most expression is the value of combined expression

val=(a=3,b=9,c=77,a+c);

Sizeof() operator The sizeof() is a unary operator, thats returns the length in byte of the specified variable, and it is very useful to find the bytes occupied by the specified variable in the memory.

main() { int a; printf(%d,sizeof(a)); } Pointer operators and Member selection operator Pointer operators & : this symbol specifies the address of the variable * : this symbol specifies the value of the variable

Member selection operators . and -> : these operators used to access the elements from a structure.

Bitwise operator Operator >> << ^ ~ Meaning Right shift Left shift Bitwise XOR (Exclusive OR) Ones complement

& |

Bitwise AND Bitwise OR

Right shift and Left shift main() { int x,y; scanf(%d,&x); x>>=2; y=x; printf(%d,y); } Y=n/(2^s) n=number s=number of position to be shifted Y=8/2^2=2 main() { int x,y; scanf(%d,&x); x<<=3; y=x; printf(%d,y); } Y=n*(2^s) n=number s=number of position to be shifted Y=2*2^3=16

AND , OR, XOR AND: main() { int a,b,c; scanf(%d %d,&a,&b); c=a &b; printf(%d,c); } OR: main() { int a,b,c; scanf(%d %d,&a,&b); c=a I b; printf(%d,c); } XOR: main() { int a,b,c; scanf(%d %d,&a,&b); c=a ^ b; printf(%d,c); } Precedence of arithmetic operators An arithmetic expression without parenthesis will be evaluated from left to right using the rule of precedence of operators

Higher priority * / % Lower priority + Type conversion Implicit Explicit

Implicit : c automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. This automatic conversion is known as implicit type conversion. If the operands are of different types, the lower type is automatically converted to the higher type before the operation proceeds. The result is of the higher type.

Explicit: When we want to force a type conversion in a way that is different from automatic conversion. (type-name) expression X=(int)7.5; A=(int)21.3/(int)4.5;

CONTROL STRUCTURES Decision making and branching Decision making and looping

Decision making and branching if switch Conditional operator Goto Simple if ifelse

Nested ifelse else if ladder

Simple if If(test exp) { Stmt1; } Stmt-x; }

if-else if (expression) statement;

else statement;

Nesting of ifelse statement if(test condition1) { if(test condition2) { Stmt1; } else { Stmt2; } } else { Stmt3; }

Stmt-x;

The else if ladder if (expression) statement; else if (expression) statement; else if (expression) statement; . . else statement;

Switch-case switch (expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break;

default statement sequence }

There are three important things to know about the switch statement:

The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of relational or logical expression. No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are in common. If character constants are used in the switch statement, they are automatically converted to integers The ?: operator

Can be written as

The goto statement C supports goto statement to branch unconditionally from one point to another in a program. It requires a label in order to identify the place Label- any valid variable name and must be followed by a colon ( : ) The label: can be anywhere in the program statement either before or after the goto label;

The

goto

statement

If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly backward jump

If the label: is placed after the goto label; some statements will be skipped forward jump

Decision making and looping while entry controlled do-while exit controlled

While statement

Entry controlled loop

Do statement

The for statement { Body of the loop } Nesting of for loop (inner loop, outer loop) Infinite loop for (initialization; condition; increment)

Jump in loops Break continue

FUNCTION A function is a set of instructions that are used to perform specified tasks which repeatedly occurs in the main program By using function we can divide complex tasks function can also helps to avoid duplication of work into manageable tasks. The

The difference between these two categories of functions is that predefined or library functions are not required to be written by the programmer, whereas the user defined function has to be written by the programmer at the time of programming.

Advantages of user-defined functions the length of the source program can be reduced by dividing it into the smaller functions ii) by using functions it is very easy to locate and debug an error. The user-defined function can be used in many other source programs whenever necessary. iii) functions avoid coding of repeated programming of the similar instructions iv) functions facilitate top-down programming approach How function works Whenever function is called control passes to the called function and working of the calling function is temporarily stopped, when the execution of the called function is completed then control returns back to the calling function and executes the next statement.

Elements of user-defined functions function definition function declaration function call

Function declaration

Like the normal variables in a program, the function can also be declared before they defined and invoked Syntax:

return_type function_name(parameters list); Eg: int add(int x,int y); i) the list of parameters must be separated by comma. ii) the names of the parameters are optional but data type is must. iii) if the function does not return any value, then the return type void is must. iv) if there is no parameters, simply place void in braces v) the data type of actual and formal parameters must match. Function definition It is the process of specifying and establishing the user all of its elements and characteristics datatype function_name (parameters list) { Local variables declaration; . Body of the function; .. Return(expression); } Function call Eg: fun(); fun(a,b); The function can be called by simply specifying the name of the function,return value and parameters if presence. defined function by specifying

c=fun(a,b); parameters Parameters provides the data communication between the calling function and called function. There are two types of parameters

i) Actual parameters: these are the parameterstransferred from the calling program (main program) to the called program (function). ii) Formal parameters: These are the parameters, transferred into the calling function (main program) from the called program (function) main() { fun(a,b); .. } a,b are actual parameters x,y are formal parameters There are two kinds of variables local variables global variables local variables: the local variables are defined within the body of the function. These variables are defined is local to that function only. Other functions can not access these variables fun(int a, int b) { int c,d; . .. } Global variable: global variables are defined outside the main() function, multiple functions can use these variables } fun(x,y) { .. . ..

int m=5,n=10; main() { int a,b; } return statement The return statement may or may not send back any values to the main program (calling program). If it does, it can be done using the return statement.

Syntax: return; return(exp); Eg: if(a<b) return(1); else return(0); the return statement can return only one value from the called function to the calling function The return statement can be present anywhere in the function The return statement not necessary at the end of the function If the called function does not return any value, then the keyword void must be used as the return type specifier main() { message(); printf(main message); } message() {

printf(function message);

Function prototypes The function are classified into the following types depending on whether the arguments are present or not and whether a value is returned or not. These are also called function prototype.

i) function with no arguments and no return value ii) function with arguments and no return value iii) function with arguments and return value iv) function with no arguments and return value Function with no arguments and no return values In this prototype, no data transfer takes place between the calling function and the called function i.e.. The called program does not receive any data from the calling program and does not send back any value to the calling program. void add(void); main() { add(); } void add() { int a,b,c; scanf(%d %d,&a,&b); c=a+b; printf(%d,c); }

Function with arguments and no return values In this prototype, data is transferred from calling function to called function. i.e., the called program receives some data from the calling program and does not send back any values to calling program. (one way communication). void add(int,int); main() { int a,b; scanf(%d %d,&a,&b); add(a,b); } void add(int x,int y) { int z; z=x+y; printf(%d,z); } Function with arguments and with return value In this prototype, the data is transferred between the calling function and called function. i.e., the called program receives some data from the calling program and send back a value return to calling program (two way communication).

Function with no argument and with return value In this prototype, one way data communicate takes place. i.e.; the calling program can not pass any arguments to the called program but, the called program may send some return value to the calling program.

Parameter passing methods There are two ways that the parameters can be passed to a function, they are i) call by value ii) call by reference Call by value This method copies the values of actual parameters into the formal parameters of the function. Here the changes of the formal parameters cannot affect the actual parameters, because formal arguments are photocopy of actual arguments. Changes made in the formal arguments are local to the block of the called functions. Once control returns back to the calling function the changes made disappear. int cube(int); main() { int n=5; printf( cube of %d is %d,n,cube(n)); } int cube(int x) { int y; y=x*x*x; return(y); } Call by reference Call by reference is another way of passing parameters to the function. Here, the address of arguments are copied into the parameters inside the function, the address is used to access the actual arguments used in the call. Hence changes made in the arguments are permanent. void interchange(int *a,int *b); void main() { int i=5,j=10; printf(before interchange %d %d,i,j); interchange(&i,&j); printf( after interchange %d %d,i,j); printf(after interchange in the main %d %d,i,j); } void interchange(int *a,int *b) { int t; t=*a;

*a=*b; *b=t; } INPUT OUTPUT STATEMENTS

Input output statements We have two methods for providing data to the program i)assigning the data to the variables in a program ii)by using the input/output statements unformatted input/output statements formatted input/output statements

Unformatted input/output statements

Input getc() getchar()

output putc() putchar()

gets() Formatted input/output statements

puts()

Input

output

scanf() fscanf() getchar() It reads a single character from a standard input devices Syntax: char variable=getchar(); Eg: char x; x=getchar(); main() { char ch;

printf() fprintf()

ch=getchar(); printf(%c,ch); } putchar() It is used to display one character at a time on the standard output device.this function does the rerverse operation of the single character input function. Syntax: putchar(character variable); Eg:char x; putchar(x); main() { char ch; ch=getchar(); if(islower(ch)) putchar(toupper(ch)); else putchar(tolower(ch)); } getc()->it is used to accept a single character from the standard input to a character variable. syntax:character variable=getc(); Eg:char c; c=getc(); putc()->it is used to display a single character in a character variable to standard output device. syntax:putc(character variable); eg: char c; putc(c); The getc() and putc() functions are often used in file processing. gets()->it is used to read the string from the standard input device syntax:gets(char type array variable); Eg:gets(s); puts()->it is used to display the string to the standard output device. Syntax:puts(char type array variable); Eg:puts(s); main() { char s[40]; gets(s); puts(s); }

FORMATTED INPUT/OUTPUT scanf()->this function is used to enter any combination of input. It is used to read information from the standard input device. Syntax:scanf(control string,&var1,&var2&varn); Eg: int n; scanf(%d,&n); Control string:it is the type of data that the user going to accept via the input statements,this can be formatted and always preceded with a % sign. Each variable name must be preceded by an ampersand(&). The(&) symbol gives the meaning address of the variable. RULES FOR WRITING SCANF() FUNCTION

i) the control string must be preceded with(%) sign and must be within quotations.i.e.,the address of variable should be passed. ii)if there is a number of input data items.the items must be separated by commas and must be preceded with (&) sign except for string input iii)the control string and the variables going to input should match with each other. iv) it must have termination with semicolon V)the scanf() reads the data values until the blank space in numeric input or maximum number of cahracter have been read,or an error is detected void main() { int I,j,k; scanf(%d %d,&i,&j); k=i+j; printf(%d,k); } void main() { int i,j,k,h; i=scanf(%d %d %d,&j,&k,&h); printf(%d,i); printf(%d %d %d,j,k,h); }

printf()->this function is used to output any combination of data. syntax:printf(control string,var1,var2,var3); Eg:printf(%d,n); void main() { printf(HELLO); }

void main() { int i; i=printf(ABCDE\n); printf(total number of character printed %d,i); } READING AND WRITING INTEGER NUMBERS The integers can be read/write through the scanf() and printf() statements with the field specification along with the control string. Syntax: scanf(%wd,&n); W->is an integer number that is used to specify the field width of the number to read. Eg:scanf(%2d %5d,&x,&y); Scanf(%d %*d %d,&x,&y,&z); 39 17 77 X=39 Z=77 The value 17 will not assigned to y because of(*) in field width ,it will be skipped printf()

READING AND WRITING REAL NUMBERS Writing->the writing of real numbers may be displayed in decimal point notation using the field width specification Syntax: printf( %w.p.f,var(s));

W->is the minimum number of position that are to be used for displaying the output. P->specified the number of digits to be displayed after the decimal point.

READING AND WRITING CHARACTER STRING Reading-> %ws Syntax: scanf(%ws,var(s)); Eg: scanf(%12s,name); Writing-> %w.ps Syntax:printf(%w.ps,var(s)); p->specifies that only the first p character of string are to be displayed.

POINTERS The memory address is the location where program instructions and data are stored, pointers can be used to access and manipulate data stored in the memory In computers memory each cell is 1 byte, and it has a number called address, this address is numbered consecutively starting from zero to last address.

main() { int no=39; printf(%d,no); printf(%u,&no); } Here &no returns the address of the variable no (i.e) 3977 A pointer is a variable, it may contain the memory address of the another variable. It is declared in the same manner like other variable. It is always denoted by * operator. A pointer is a variable whose value is also an address. Each variable has two attributes: address and value Features of pointers Pointers are efficient in handling data and associated with array. Pointers reduce length and complexity of the program Since the pointer data manipulation is done with address, the execution time is faster. The two-dimensional and multi-dimensional array representation is easy in pointers Advantages of using pointers Pointers are more compact and efficient code Pointers can be used to achieve clarity and simplicity Pointers are used to pass information between function and its reference point. Pointers enables us to access the memory directly Pointer declaration Syntax: data-type *pointer-name; Eg: int *a; *a->mean a contains the address of variable, which is integer variable.

main() { int a=22; int *b; b=&a; printf(%d,a); printf(%d,*(&a)); printf(%d,*b);

Null pointer A pointer is said to be a null pointer when its right value is 0. A null pointer can never point to a valid data for checking a pointer, if it is assigned to 0,then it is a null pointer. int *a; int *b; b=a=0;

Pointer to pointer Pointer is a variable that contains the address of the another variable. simlarly another pointer variable can store the address of the address of this pointer variable. so we can say, this is a pointer to pointer variable. main() { int a=22; int *b; int **c; b=&a; c=&b;

printf(%d,a); printf(%d,*(&a)); printf(%d,*b);

Initializing pointer variable The process of assigning the address of a variable to a pointer variable is known as initialization We can use the assignment operator to initialize the pointer variable. int *p; p=&n; Where *p is called the indirection operator it operates only on pointers POINTERS AND ARRAYS Array elements are always stored in consecutive memory locations according to the size of the array. The size of the data type with the pointer variables refer to, depends on the data type pointed by the pointer. A pointer when incremented, always points to a location after skipping the number of bytes required for the data type pointed to by it.

The base address of the array start with 0thelement of the array. The array is in integer type,the integer will have 2 bytes and hence the address of the next address element is incremented by 2. int a[5]={10,20,30,40,50}; int *b; b=a; b is a pointer variable which holds the base address of the array a (i.e) b=&a[0]

main() { int a[5]={10,20,30,40,50}; int b; for(b=0;b<5;b++) { printf(the value of a[%d]=%d,b,a[b]); printf(address of a[%d]=%u,b,&a[b]); } }

main() { int arr[5]={10,20,30,40,50}; int i,*p; p=arr; for(i=0;i<5;i++) { printf(address=%u,&arr[i]); printf(element =%d,&arr[i]); printf(%d,*(arr+i)); printf(%d,p[i]); printf(%d,*(p+i)); } } When pointer variable is incremented by 1 then the related base address will be incremented by address+2 because pointer is of type integer.

POINTERS AND CHARACTER STRINGS The character arrays are declared and initialized as follows Char str[5]=good; The compiler automatically inserts the null character \0 at the end of the string. C supports an alternate method to create strings unsing pointer variables of type char Char *str=good; the pointer str now points to the first character of the string good

main() { char name; char *cptr=name; name=DELHI printf(%s,name); While(*cpte!=\0) { printf(%c %u,*cptr,cptr); cptr++; } }

STORAGE CLASSES 1.automatic variables 2.external variables 3.static variables 4.register variables Scope: The scope of the variable determines over what region of the program a variable is actually available for use (active) Longevity->it refers to the period during which a variable retains a given value during execution of a program (alive) Visibility->it refers to the accessibility of a variable from the memory.

Automatic Automatic variables are declared inside the function, they are created when the function is called and destroyed automatically when the function is exited, hence the name automatic Automatic variables are therefore private (or local) to the function in which they are declared.

Also called as local or internal variables

main() { int number; } main() { auto int number; } How automatic variables work void func1(void); void func2(void); main() { int m=1000; func2(); printf("%d\n",m); }

External variables Variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables. External variables are declared outside a function. int number; //global declaration main() { } fun() { }

int count; main() {

count=10; ---} fun() { int count=0; ---count=count+1; } int x; //global main() { x=10; printf("x=%d\n",x); printf("x=%d\n",fun1()); printf("x=%d\n",fun2()); printf("x=%d\n",fun3()); } fun1(void) { x=x+10; } int fun2(void) { int x; x=1; return(x);

} fun3(void) { x=x+10; }

External declaration

Static variables The value of static variables persists until the end of the program. static int x; a static variables may be either an internal type or an external type depending on the place of declaration.

Register variables We can tell the compiler that a variable should be kept in one of the machines registers, instead keeping in the memory (where normal variables are stored). Since the register access in much faster than a memory access. register int count;

ARRAYS

Fixed-size sequenced collection of elements of the same data type. E.g., list of employees in an organization emp[100] Types of arrays: 1. One-dimensional array 2. Two-dimensional array 3. Multidimensional array One-dimensional array A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array. E.g., int number[5]; Declaration of one-dimensional array type variable_name [size]; E.g. char name[10]; When the compiler sees a character string, it terminates it with null character \0. When declaring character arrays, we must allow one extra element space for the null terminator. Initialization of one-dimensional array After an array is declared, its element must be initialized. Otherwise, they will contain garbage. It can be initialized, At compile time At run time Compile time initialization type array_name[size]={list of values}; E.g., int number[5]={ 1,2,3}; remaining two elements to 0 int number[]={ 1,2,3,4,5,6,7}; compiler allocates enough space char name[]={j, o, h, n, \0}; or john int no[3]={1,2,3,4,5}; compile time error Run time initialization Explicitly initialized at run time E.g., for(i=0;i<100;i++) { if (i<50) sum[i]=0.0; else sum[i]=1.0; }

type array_name [row_size] [column_size]; E.g. int table[2][3]={0,0,0,1,1,1}; int table[2][3]={ {0,0,0}, {1,1,1}}; int table[2][3]={ {0,0,0}, {1,1,1} };

You might also like