You are on page 1of 54

UNIT IV C PROGRAMMING

Introduction to C: Computer languages are basically classified into two types: System Programming Languages (SPL) and Application Programming Languages (APL). SPLs are difficult to develop when compared to APLs. But in the generations of computers SPLs play a vital role. SPLs are basically classified into two types (i) High Level Languages (ii) Machine Level Languages /Low Level Languages. There are many HLL like COBOL, ForTran, C, C++, Java etc. Out of these the most widely used programming language is C. C is a general purpose programming language which is well structured. Hence it is known us Structured Programming Language. Before the development of C COBOL & Pascal were well used. Pascal is known as sister of C. C resembles high level language & also used as

MLL. In order to fill the bridged gap between HLL & MLL C is well known. Because of this flexibility C is known as Middle Level Language. C is basically used for designing compilers. C is very powerful because of its features like C is very precise programming language. C programs are well structured. Error checking is highly easy. C is a highly portable, so it can be easily carried from one platform to another platform. History of C: C was originally developed in 1972 by a person named as Dennis Ritchie working at AT & T Bell Laboratories in U.S.A. C is an outgrowth of 2 High level programming languages like B & BCPL. The abbreviation form of BCPL is Beginners Combined Programming Language. Dennis Ritchie inherited the properties of BCPL & B and added his own developments & designed a new programming language known as C. Since it is an advanced version of B it is named as C. BCPL & B were designed in 1970s. Which led to the development of C in 1972, gradually Cs popularity has been increased by 1980s & C was well used for various commercial applications & by various software companies. The code of C was standardized by as organization in America known as ANSI (American National Standardized Institute) & the code is known as ASCII code (American Standard code for Information Interchange). By using ASCII code a MLL can be converted into Machine level language.

C PROGRAMMING

C Character set: Write a short note on C character set. The set of characters that are used for the representation of information in C language is known as C character set. C character set is basically classified into 3 sets. They are Alphabets Digits Special characters The 3 C character sets are represented in following table C character set 1. Alphabets: Alphabets in C are classified into 2 types upper case, lower case Upper case: Lower case: 2. Numericals/Digits: The numbers available in C character 0---------9 set are ranging from 0 to 9 3. Special Characters: {, }, [, ], (, ), $, @, *, |, %, +, -, _, :, ;, &, =, <>, <, A---------Z a---------z List of characters available

These special symbols are used for >, <=, >=, , , ,, !, ?, ., ~(Tilde), ^(carot), #(Hash) specific purpose in C language.

Reserved words: Key words are the reserved words whose meaning is already defined in C library. They are known as reserved words because they are reserved for specific purpose. These key words cannot be used as variable names. There are 32 key words available in C language. They are listed as follows: auto break case char const continue default do double else enum extern float far for goto if int long near register return short signed static struct switch typedef union unsigned void while

C PROGRAMMING

Briefly explain the types of variables in C. Variables: A variable is defined as a name given to a value which is hot constant. In other words the value of a variable will be varying. Consider for example the following expression, X + Y = 10. In the above expression, 10 is a constant whereas x, y are known as variables. Variables are used to store values in the memory. The name given to the memory location to store a value is known as a variable. For example x = 10. In the above example, x is called as variable name & 10 is called as value assigned to variable x. Types of C variables: A variable is a name given to value in other words variable can store a value. These variables are classified into 3 types. They are Integer variables. Float /Real variables. Character variables. Integer variables: These variables are the variables which hold only integer values. Eg :- int x = 10 In the above example, x is the variable name & 10 is a value assigned to that variable. Float /Real variables: These variables can hold only decimal values. Eg:- Float y = 32.33; In the above example y is a float variable & 32.33 is the value assigned for that variable. Character variables: It is a variable which holds a single character. Eg:- char Z = a; In the above eg, Z is the variable name & a is the value assigned to that variable. The value assigned to the character variable should always be enclosed in single quotes. Rules for constructing C variables: While writing a C program the major step is declaration of C variables. The C variables are declared with certain rules. They are given as follows:Rule (i):- A variable name should not exceed more than 8 characters. Some of the advanced C compilers supports 40 characters variables but it is safer to stick on to 8 character variable.

C PROGRAMMING

Rule (ii):- The first character of the C variable should not start with a number or numeric value. It should only start with an alphabet. Rule (iii):- The C variable should not include special symbols, in between the variable names. Rule (iv):- commas, blank spaces, hyphens are not allowed in the declaration of C variables. Rule (v):- The most important point to be remembered in constructing a C variable is, a C variable should be defined in a meaningful simple manner where an user can understand what the variable is, For eg:- To declare Rate of interest, simple interest, compound interest it is given as follows: float float float ROI = 0.05; CI = 1.25; SI = 0.25;

C Tokens:The C tokens are basically classified into 3 categories. They are Lexical Fundamental Secondary Lexical Tokens: Keyword, variables, constants are grouped together as lexical constants in C. Fundamental Tokens: These Tokens are the primary data types available in C. These primary data types are classified as Numeric & Alphabet/Character data types. The Numeric data type is further classified as integer & float data type whereas character data types are divided as character & string data types. Secondary Tokens: These tokens play an important role in C programming. They are arrays, structures, unions, pointers, enumerations etc.

C Constants: Constants are the quantities whose value cannot be changed i.e., the value of a constant remains the same throughout the program. A constant is always declared with the keyword const. For eg: (Pi) is a constant with the value 3.14 in C program it is defined as follows. const Pi = 3.14;

Types of C constants: C Constants are basically classified into 2 types. They are Primary constants C PROGRAMMING 4

Secondary constants Primary constants: These constants are further classified into numeric & character constants. Numeric constants are further classified into integer & float values where as character constants are classified into character & string constants. Secondary constants: The various secondary constants supported by C programming are arrays, pointers, structures & unions.
CONSTANTS

PRIMARY

SECONDARY Arrays Pointers

NUMERIC

CHARACTER

Structures Unions

INT FLOAT/REALL

CHAR STRINGS

There are certain rules for constructing various types of constants. They are given as follows:Rules for constructing integer constants: An integer constant must have at least one digit. An integer constant should not have decimal points. An integer constant can be preceded by either positive or negative sign. If no sign is specified by default it is assumed to be positive. Blank spaces, commas, hyphens, special symbols are not included in between an integer constant. The maximum allowable range of an integer constant is -32768 to 32767. Rules for constructing Real constants:The real constants ate basically classified into decimal form & exponential form. Rules for constructing Decimal constants:i. ii. iii. A decimal constant must have at least one digit. A decimal constant should include a decimal point. A decimal constant should be preceeded by either +ve or ve sign. If no sign is specified by default it is assumed to be +ve. iv. Blank spaces, commas, hyphens, special symbols are not allowed within the real constants. 5

C PROGRAMMING

v.

The value before decimal is called as mantissa. The value after decimal point is called as decimal or fractional part.

Rules for constructing Exponential constants:a) An Exponential constant must have at least one digit. b) An Exponential constant should include a decimal point. c) An Exponential constant should be preceeded by either +ve or ve sign. If no sign is specified by default it is assumed to be +ve. d) An Exponential constant does not allow any Blank spaces, commas, hyphens, special symbols. e) The Exponential constant are indicated by e. The value before decimal is called as mantissa. The value after decimal point is called as decimal or fractional part. The value specified at e power is called as exponential part. The maximum range of exponential part is given by -3.4e38 to 3.4e38. Rules for constructing Character constants:i. It should at least contain a single character. ii. Character constant should always be enclosed in single quotes. iii. These single quotes should point towards left. Rules for constructing String constants:a) A String is a group of characters. Hence a string constant should have at least more than one character. b) A String constant should always be enclosed in double quotes. c) These double quotes should always point to words left i.e., .

Data types in C Briefly explain various data types available in C (OR) What is a data type? Explain how data is stored in variables. The data in C is stored in variables. Variables are stored in memory. Hence data type is defined as the type of data that is been specified in a data. Variable is named as a data type. In C programming data types play a major role. The data types in C are basically classified into 3 types: Primary / Fundamental Data types Secondary / Derived Data types User Defined Data types

C PROGRAMMING

C language is a rich in data types and their representations. From the available 3 types of data types primary/fundamental data types play a major role because they are the basic data types which are defined by C language whereas secondary data types are derived from the fundamental data types. Hence they are known as Derived data types. The various examples for derived data types are arrays, structures, pointers & unions, similarly the data types which are not primary & secondary & which are defined by the users are named as user defined data types. These user defined data types are designed during designing of operating system. The example for user defined data type is Enumerations.
DATA TYPES

Primary/fundame ntal data types

Secondary/Derived data types

User Defined data types

Arrays

Integer data type

Character data type

Float/Real data type

Pointers Structures Unions

Enumerations

Signed Char

Float Double Long Double

Iot

Short Int

Long Int

Unsigned Char

Signed Int Unsigned Int

Signed short Int Unsigned short Int

Signed Long Int Unsigned Long Int

Classification of Primary data types: From the available data types, primary data types are classified in various ways. Classification chart of Primary Data types:Data type Integer int Signed short int Unsigned short int Signed long int Unsigned long int Character Signed Char Unsigned Char Float/Real Float Double Long Double C PROGRAMMING range - 32768 to 32767 - 32768 to 32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 -128 to 127 0 to 255 - 3.4e38 to 3.4e38 - 1.7e308 to 1.7e308 - 1.7e4932 to 1.7e4932 Bytes occupied 2 Bytes 2 Bytes 2 Bytes 4 Bytes 4 Bytes 1 Bytes 1 Bytes 4 Bytes 8 Bytes 12 Bytes Format %d %d %u % ld % lu %c %c %f % lf % Lf 7

Integer data types:This is the primary fundamental data type which stores only integer values. The max range of integer data type is given as 32768 to 32767. The integer data type occupies 2 bytes of memory space. This integer data type is further divided into 2 types, long int & short int. Long int:The integer data type which can store a bigger range of values is defined as Long int. Long integer occupies 4 bytes of memory space whose range is given by -2147483648 to 2147483647 Short int:The integer value which can store small values are defined as short int. Short int occupies 2 bytes of memory space with the range 0 to 65535. These integers are further classified into signed and unsigned, which are given as Signed short int Unsigned short int Signed Long int Unsigned Long int Character data type:The data type which holds single character is named as character data type. Within the character data a single character is specified in single quotes. These single quotes should always point towards left. The character data type is further classified into 2 types, signed & unsigned. The range of signed character is 128 to 127 which occupies one byte of memory space. Whereas the range of unsigned character is 0 to 255, which occupies 1 byte of memory space. Float/Real Data Type:The data type which can store decimal values are named as Float/Real data types. It is broadly classified into 3 types Float Double Long Double A Float data type occupies 4 bytes of memory space with the range 3.4e38 to 3.4e38. If a variable wants to hold greater value than float then C offers Double data type which occupies 8 bytes of memory space with the range - 1.7e308 to 1.7e308. If the situation occurs to hold the value bigger than double, then C offers Long double data type which occupies 16 bytes of memory space with the range - 1.7e4932 to 1.7e4932.

C PROGRAMMING

Operators in C:An operator is a symbol which is used to connect two or more operands. C is rich in operators. These operators in C are basically used to perform mathematical or logical calculations or computations. The operators in C are basically used to join two or more operands. The various operators supported by C program are listed as follows. They are Arithmetic operators Relational operators Logical operators Assignment operators Increment Decrement operators Condition operators Bitwise operators Special operators Arithmetic operators: The fundamental operators supported by C are Arithmetic operators. These operators are basically used to perform Arithmetic operators. These operators basically work on two operands. Sample table to demonstrate arithmetic operators in C:Arithmetic Description operator Addition operator + Subtraction operator Arithematic multiplication * Arithematic division / Arithematic modulus % Relational operators: Example a+b ab a *b a/b a%b Output If a = 10, b = 3 it is equal to 13 7 30 3.33 1

The comparison between two operators is done with the help of relational operators. These operators are basically used to compare two or more values. C supports various types of relational operators. Sample table to demonstrate Relational operators in C. Relational operator == != > < <= >= Description Equality operator Not equality operator Greater than Lesser than Less than or equality operator Greater than or equality operator Example a+b a != b a>b a<b a <= b a >= b Output a = 10, b = 3 False True True False False True

Logical operators: Logical operator logically relates the operands in C program. C basically supports 3 types of logical operators. They are Logical AND && C PROGRAMMING 9

Logical OR || [pipe symbol] Logical NOT ! Logical AND:This operator returns a true value when both the operands are true else it returns false. Truth table for logical AND: a b a&&b F F F F T F F F T T T T Logical OR: This operator returns a true value when at least one of the operands are returns a true value. Truth table:a b a&&b F F F T T F T F T F T T Logical NOT: This operator returns a negative value of the corresponding operand. Hence, it is known as negation operator. Truth table:a !a F T T F Assignment operators: These operators are basically used to assign a certain value to a variable. C supports various types of assignment operators. Sample table to demonstrate assignment operators in C. Assignment operator = += + *= /= %= Description Assignment operator Arithematic addition assignment operator Arithematic subtraction assignment operator Arithematic product assignment operator Arithematic division assignment operator Arithematic modulu assignment operator Example a=b a += b a=b a b = a a*=b a*b a /= b a/b a %= b a%b Output If a = 10, b = 3 a=3 a = a+b a = 13 a=7 a = 30 a = 3.33 a=1

C PROGRAMMING

10

Incrementation and Decrementation operators: C supports two powerful operators known as incrementation & Decrementation operators. Incrementation operators (++):This operator is used to increment the value of a variable by one 1. In other words this operator is used to increase the value of the operand by one. Consider for ex: X is the operand then the incrementation operator is written as X++ or ++X X++ or ++X means X = X+1 X++ is called as post incrementation & ++X is called as pre incrementation operator. When these incrementation operators are assigned to a value in a statement they differ. Decrementation operators (--):This operator is used to decrement the value of a variable by one. In other words this operator is used to decrease the value of the operand by one. Consider for example X is the operand then the decrementation operator is written as X or X. X & X means X = X 1. X is called as post decrementation & X is called as pre decremetation operator. When these decremetation operator are assigned to a value in a statement they differ. Conditional operators: Conditional operators are used to check a single condition is as expression. The conditional operator is denoted by ?: The syntax for conditional operator is cond 1? value 1: value 2; In the above syntax if condition 1 is satisfied value 1 will be executed otherwise value 2 will be executed. Ex:- X[A>b? Big = A: Big = B;] x a>b? Big = a: Big = b; Bitwise operators: C supports certain distinct operators known as Bitwise operators. They are listed as follows:Operators & | ^ << >> Special operators: Description Bitwise AND Bitwise OR Bitwise exclusive OR Left shift Right shift

C supports four types of special operators. They are Size of operator Comma operator C PROGRAMMING 11

Pointer operator (&, *) Member operator (,)

Loops in C/Control statements in C: Briefly explain about various looping constructs in C. What are various control statements available in C. (or) (or)

What is a loop & how many types of loops are there in C. C Programming supports various statements which are executed repeatedly in order to perform certain tasks. Hence the process of repeated execution of block of code until some specified condition is satisfied is known as Loop. A Loop is executed depending on the test condition. If this test condition is satisfied the control enters into the loop otherwise the control jumps out of the loop. Since the loop is executed depending on the condition, loops are also known as conditional or control statements or control structures. Loops are basically used as decision making statements. The various looping structures available in C are listed as follows: If loop While . loop Do .while loop For .loop Switch .case. If loop:This is the primary looping construct available in C programming. This looping construct is basically classified into 3 types. 1. Simple If loop 2. Ifelse loop 3. NestedIf loop Simple If loop:This is the simple if looping structure which is used to test a single condition. If this condition is satisfied the If loop will be executed. The syntax far the loop is given as follows If { Statement 1; Statement 2; -------------Statement n; Loop code (condition)

} In the above syntax if the condition is satisfied then the loop code is executed. C PROGRAMMING 12

Flowchart of the simple If:-

If

Code

True Statement 1

Statement 2

Statement 3

Next

If else loop:In order to test two conditions If else loop is been used. If .else loop basically consists of two part (i) if part & (ii) else part. (i) If part:If the first condition of the if loop is satisfied then if part is executed. (ii) Else part:If the first condition of the if loop is not satisfied then else part is executed. Syntax of If ..else:If { Statement 1; Statement 2; --------------------------Statement n; } else { Statement a; Statement b; --------------------------Statement z; } In the above syntax if condition-1 is satisfied then the corresponding if part will be executed. If the first condition is not satisfied then else part will be executed. Sample Program to demonstrate Ifelse:# include<stdio.h> # include<conio.h> C PROGRAMMING 13 (condition1)

(If block/code/part)

(else block/code/part)

void main( ) { int bonus = 1000,yoj,cy,yos; printf(Enter yoj and cy); scanf(%d%d, &yoj, &cy); yos = cy-yoj; If (yos>3) { bouns =bouns+1500; printf(yours bouns is %d, bouns); } else { printf (yours bouns is %d, bouns); } get ch( ) } Flowchart of If..else:If No Statement - a
Condition 1

True Statement 1

Statement - b

Statement 2

Statement - m

Statement 3

Next - st

Nested If loop:When a series of decisions are involved the user has to use more than one checking conditions. In such a case nested if statement is been used. Nested if is basically classified into 2 types:Ifelse ladder. Elseif ladder. Ifelse ladder:The nesting that is done with Ifelse loop is known as Ifelse ladder. C PROGRAMMING 14

SYNTAX: If(Condition-1) { If( Condition-2) { statement-1 statement-2 } else { statement-3 statement-4 } } else { statement-5 statement-6 } next-st ; In the above syntax if Condition-1 is satisfied, Condition-2 is executed. If Condition-2 is also satisfied then statement 1 & 2 are executed. If Condition-2 is not satisfied statement 3 & 4 is executed. If Condition-1 is not satisfied statement 5 & 6 is executed. Hence the control jumps to the next statement. Flow chart of if else :If False
Condition 1

True If False True

Condition 2

Statement 1 Statement 2

Statement - 3 Statement - 4

Statement - 1 Statement - 2

Next - st

C PROGRAMMING

15

Sample program to demonstrate Ifelse ladder :Write a C program to find biggest of three numbers. # include<stdio.h> # include<conio.h> void main( ) { int a, b, c, big; printf(Enter any 3 Number); scanf(%d %d %d , &a, &b, &c); If(a>b) { If(a>c) { big=a; printf( biggest of 3 numbers %d , big); } else { big=c; printf( biggest of 3 numbers %d , big); } } else { If(b>c) { big=b; printf ( biggest of 3 numbers %d , big); } else { big=c; printf ( biggest of 3 numbers %d , big); } } } Else If ladder: The loop that is constructed by using elseIf statements are known as else..if ladder. The syntax for elseIf ladder is given as follows. Syntax: If ( Condition 1) { statement 1; statement 2; C PROGRAMMING 16

} else If( Condition 2) { statement 3; statement 4; } else If( Condition 3) { statement 5; statement 6; } . . . else If( Condition n) { statement n; } next-st ; In the above syntax, if condition 1 is satisfied, statement 1 & 2 are executed else the control jumps to condition 2. If condition 2 is satisfied statements 3 & 4 are executed else the control jumps to 3 rd condition. If condition 3rd is satisfied statements 5 & 6 are executed, so on if condition n is satisfied statement is executed otherwise the control is transferred to next statement. Flow chart of elseif ladder:-

False

Condition 1

True

Statement - 1 False
Condition 2

True Statement - 2 Statement - 3 Statement - 4

False

Condition 3

True

Statement - 5
Condition n

Statement - 6

Statement - n

Sample program to demonstrate else.if ladder: # include<stdio.h> # include<conio.h> void main( ) { int S, E, M, Cs, El, Tot; C PROGRAMMING 17

float per; char grade; printf(enter your 5 subjects marks); scanf(%d %d %d %d %d, &S, &E, &M, &Cs, &Fl); Tot = S + E + M + Cs + El; Per = Tot/5 *100; If(Per >=90) { grade =A+; } else if((Per >=70)&&(Per <90)) { grade =A; } else if((Per >=60)&&(Per <70)) { grade =B+; } else if((Per >=50)&&(Per <60)) { grade =B; } else if((Per >=40)&&(Per <50)) { grade =C+; } else grade =fail; print if (your grade is %C, grade); } While loop:This is the simplest form of looping structures in C programming. In the while loop the condition is checked at the top of the loop. Hence it is called a top check loop or entry controlled. Because the condition is checked at beginning of the loop. In while loop if the condition is true the

C PROGRAMMING

18

body of the loop is executed repeated. If the condition is false the control comes out of the loop & goes to next statement. Syntax: While (condition) { statement 1; statement 2; statement n; } Next statement. In the above syntax if the condition is true statement 1,2,.n is executed repeatedly until the condition becomes false. if the condition is false the control comes out of the loop. Flow chart of while loop:
While
Condition

body of loop

False

True Statement 1 Next Statement

Statement 2

Statement - n

Sample program to demonstrate while loop:# include<stdio.h> # include<conio.h> void main( ) { int X = 1; while(X<=10); { printf(%d, X); X=X+1 } }

C PROGRAMMING

19

General Program: # include<stdio.h> # include<conio.h> void main( ) { int X = 1, n; clrscr(); printf(enter number of digits to be printed); scanf(%d, &n); while (X<=n) { printf(%d, X); X=X+1; } getch(); } Do.while loop: It is the secondary form of while loop where the condition is checked at bottom of the loop, hence it is called as bottom check loop or exit controlled loop. Since the condition is checked at the bottom of the loop ever if the condition is false the loop is executed at least once. Syntax: do { statement 1; statement 2; . statement n;

Body of do while loop.

} while (condition); Next statement In the above syntax statement 1,2,n are executed and then the condition is checked. If the condition is true the loop is repeated else the control comes out of the loop. Sample program to demonstrate do.while loop: # include<stdio.h> # include<conio.h> void main( ) C PROGRAMMING 20

{ int X = 100; clrscr( ); do { printf(%d, X); X=X+1; } while (X<=100); getch( ); } Flow chart of do.while loop:
do Statement - 1

Statement - 2

Statement - n

True

Condition

False

Next Statement

For loop: This is another form of entry controlled loop where the condition is checked at the beginning of the loop. For loop basically consists of 3 parts. Initialization Condition Auto incrementation/decrementation Initialization:The first step in the execution of a for loop is done through variable initialization. Initialization means assigning value for a variable. Condition: The second step in execution of a for loop is conditional checking. If the condition is true the body of the for loop is executed otherwise the control goes to the next statement. Incrementation/Decrementation: Once the body of the loop is executed the loop variable is incremented or decremented automatically. Hence for loop is also known as Auto Incrementation/Decrementation loop. Syntax; For (Initialization; Condition; Auto Inc/dec) C PROGRAMMING 21

{ statement 1; statement 2; . statement n; } Next statement In the above syntax if the condition is true the loop code is executed otherwise the control goes to the nextstatement. Flow chart of for loop:
Initialization

Condition

False

True Statement 1 Next Statement

Statement 2

Statement - n Auto Inc/Dec

Sample program to demonetrate for loop in C:Program to print number in descending order:# include<stdio.h> # include<conio.h> void main( ) { int i; clrscr ( ) for(i=10,i=0,i--) { printf(%d, i); printf(/n ); } getch( ); } C PROGRAMMING 22

Write a program in C to find factorial of given number: # include<stdio.h> # include<conio.h> void main( ) { int fact = 1, n, on; clrscr ( ); printf(enter a number); scanf(%d, &n); on = n; while (n!=0) { fact = fact *n; n = n 1; } printf(factorial of %d is %d, on, fact) getch( ); } write a program in C to reverse a number: # include<stdio.h> # include<conio.h> void main( ) { int n, Rev = 0, digit; printf(enter any number); scanf(%d, &n); while(n!=0) { digit = n% 10; Rev = Rev*10 + digit; n=n/10; } printf(The reverse of given nos is % d, rev); getch( ); } C PROGRAMMING 23

Switch..case: In the case of using many alternative values a new looping structure is used. However by using nested if or If else ladder the complexity of the program gradually increases. Hence in such cases C programming has a building in decision statement known as switchcase. This statement is basically used to test multiple values for a given condition. If the match occurs with a particular value then that corresponding loop code is executed. Syntax of switch..case: Switch (logical condition) { Case value 1: Statement 1; Statement 2; break; Case value 2: Statement 3; Statement 4; break; Case value 3: Statement 5; Statement 6; break; : : : case default: Case value 1: Statement n; Statement n+1; break; } statement X; In the above syntax if the logical condition is matched with first case then that particular body of the case is executed. If the logical condition matches with the 2nd case then that particular body of the case is executed then the loop control jumps to the next statement i.e., st X. If none of the cases are matched with given condition then default loop code is executed. Sample program to demonstrate Switch Case: Write a C program to execute favorite Flower. # include<stdio.h> # include<conio.h> C PROGRAMMING 24 default loop code case 3 loop code case 2 loop code case 1 loop code

void main( ) { char ch; printf( Enter Your Choice:); scanf(%c, &ch); switch(ch) { case r: case R: printf(Your favourite Flower is Rose); break; case l: case L: printf(Your favourite Flower is Lily); break; case j: case J: printf(Your favourite Flower is Jasmine); break; case default: printf(Your favourite Flower is Hibiscus); break; } } Flow chart of switchcase loop:

Logical condition

Case 1 loop code Case 2 loop code Case 3 loop code

C PROGRAMMING

Default loop code St-X

25

Control Statements of Looping Structures: Briefly explain various control statements supported by loops. There are three control statements that are supported by various looping structures. These three statements are basically used to control the flow of execution. They are Goto Statement Break Statement Continue Statement Goto Statement: C language supports Goto Statement to jump from one point of the program to the another point of the program. Goto is basically used in two cases: In Forward direction In Backward direction The jump that occur by the Goto statement in forward direction is known as Forward jump. Syntax of Forward Jump: Statement 1; Statement 2; ------------------------------------------------Statement n; Go to Resume; Statement a; ----------------Statement p; St X: Resume:

Forward Jump

In the above syntax after execution of st-1..n the go to statement jumps in the forward direction to the label resume & execute statement-X. In the above syntax the label is specified by colon(:) & so to statement is specified by semicolon(;). In the forward jump the statements in between go to & label are skipped off. Syntax of backward Jump: Statement 1; Statement 2; --------------------------------Statement n; Resume; Statement a; Statement b; ----------------- backward jump. ----------------Statement p; Go to Resume; Statement X; C PROGRAMMING 26

The jump that occurs in the backward direction of the loop is known as backward jump. In this jump group of statements are repeatedly executed. In the above syntax label in followed by colon & go to statement is followed by semicolon. Sample program to demonstrate go to statement:Wirte a C program to execute volume of a cube. # include<stdio.h> # include<conio.h> void main( ) { int s, cube ; cuboid: printf(Enter side of cube); scanf(%d, &s); cube=s*s*s; printf(volume of cube is %d, cube); go to cuboid; getch( ) } Break statement: In order to come out of the loop in between the execution break statement is used. In other words break is used to exit from the loop. Break statement is comfortably used in switch case. It can also be used in various looping structures likes nested if. While, do..while, for etc. When break, statement is encountered the control comes out of the loop. Syntax: While (condition) { Statement 1; Statement 2; --------------------------------Statement n; Break; Statement a; Statement b; control comes out of the loop. } Statement X; In the above syntax when break is encountered after execution of statement 1 to n the control comes out of the loop & execute Statement X. Syntax of break in do while: Do { C PROGRAMMING 27

Statement 1; Statement 2; --------------------------------Statement n; Break; Statement a; Statement b; } While (condition); Statement X; Syntax of break in for loop: For (Initialization; condition; auto inc/dec). { Statement 1; Statement 2; --------------------------------Statement n; Break; Statement a; Statement b; } Statement X; Syntax of break in switch case: Switch (logical condition) { Case value 1: Statement 1; case 1 loop code Statement 2; Break; Case value 2: Statement 3; case 2 loop code Statement 4; Break; Case value 3: Statement 5; case 3 loop code Statement 6; Break; . . . Case default: Statement n; default loop code Statement n+1; Break; } statement-x; Continue statement: C language supports another control statement continue. This is the reverse procedure of break statement. Syntax: C PROGRAMMING 28

While (condition) { Statement 1; Statement 2; --------------------------------Statement n; Continue Statement a; Statement b; } Statement X; In the above syntax when continue is encountered the control goes back to the beginning og the loop. STORAGE CLASSES Briefly explain various types of STORAGE CLASSES in C. In C programming we need to define C variables along with its data types. C variables not only have the data type but also have the storage classes. A storage class is defined as the class, which tells where the variable is stored. The storage classes in C are basically classified into four types. They are Automatic Register Static External

These four storage classes have four default properties. They are Storage area It defines where the variable is i.e., either in memory or in C.P.U. register. Default initial value of the variable The default initial values for a variable can be either garbage value or zero. Scope of variable Scope is nothing but the limit of the variable, which can be either local or global. Life of variable The life span of a variable can persist up to the block or until the function call or until the program terminates. Sample table to demonstrate storage classes: Default properties Storage area Default initial values Scope of variables Life of variables Automatic Memory Garbage Local to block Until the control remains within the block. Register CPU Registers Garbage Local Until the control remains within the block. Static Memory 0 Local Until the function call persists. External Memory 0 Global Until the program terminates. 29

C PROGRAMMING

Automatic Storage Classes: The first & foremost storage class defined in C programming is automatic storage class. This storage class is defined with the key word auto. The storage area of automatic storage class is within the memory & the default initial value is specified as garbage value. Sample Program to demonstrate Automatic Storage Class: # include<stdio.h> # include<conio.h> void main( ) { auto int I=1; { auto int I=2; { printf(%d, I); } printf(%d, I); } printf(%d, I); } Register Storage Class: The most important storage class defined in CPU registers is known as register storage class. The storage class is defined with the keyword Register. The default initial value is some garbage value. Sample program to demonstrate register storage class in # include<stdio.h> # include<conio.h> void main( ) { Register int i; for(i=1; i<10; i++) { printf(%d, i ); } } :

C PROGRAMMING

30

Output of the above program is 123456789. In register storage class since storage area is very small we can store only integer or character data types but not float or double data types because they occupy more bytes of memory. Static storage class: The storage area of Static storage class is within the memory. The default initial value for the static storage class is given as zero, it is defined within the keyword static. Sample program to demonstrate static storage class: # include<stdio.h> # include<conio.h> void main( ) { increment ( ); increment ( ); increment ( ); } void increment( ) { static int I=1; printf(%d, I); I=I+1; } Output of the above program is 123. External Storage Class: The External storage class is defined with the keyword Extern. In this storage class the variables defined as global to the program. The life span of a variable exist until the program (execution) comes to an end. Sample program to demonstrate static storage class: # include<stdio.h> # include<conio.h> void main( ) { extern int i; printf(%d, i); increment ( ); increment ( ); decrement ( ); decrement ( ); C PROGRAMMING 31

} void increment( ) { i=i+1; Printf(%d, i); } void decrement( ) { i=i-1; Printf(%d, i); } Output of the above program is 01210. FUNCTIONS Briefly explain the concept of functions in C. (or) What is a functions, explain in detail. (or) Explain various types of C functionalities. A function is self contained block of statements or block of codes, which performs certain specific task. C program supports functions in large. The process of breaking down the C program into small blocks of code is known as modularization and each block of code is known as a function. User of function in C: i. The primary advantage of C program is modularization. Modularization is the process of breaking a huge programming code into smaller components. ii. With the help of modularization error detection is very easy. iii. The concepts of C functions promote the user to write very precise programs. iv. With the help of C functions same function code can be utilized n number of times, with a function call. Classification of function in C: C functions are basically classified into 2 types. They are Pre-defined functions. User defined functions.

C PROGRAMMING

32

Pre-defined functions: The Pre-defined functions available in C programming are also known as built in functions because they are already defined in C library. Hence they can also be called as Library Functions. Within the C library Pre-defined functions functionalities are defined in header-files, which are included in C programming. C library is a place, which is commonly used to define various functionalities of C program. The well known examples of library functions are main( ), printf ( ), scanf( ). These 3 functions play an important role in C programming. User defined functions: In addition to Pre-defined functions C also supports the programmer to define his own individual functions in order to perform specific task. Hence the functions defined by C programmers are known user-defined functions. User-defined functions are declared outside the main function. The function call is specified within the main functions i.e., all the user-defined functions are called by main function through a function is known as calling function & userdefined functions are known as called function. The declaration of User-defined functions is defined with the following rules: In The declaration of User-defined functions data-type should be specified first. Function name should be declared next. List of parameters are specified & if there are more than one parameters they should be separated by commas. Syntax: function declaration

datatype function name (list of parameters) { function code; ------------------------------------------------} Accessing a function: Consider for example the following syntax in Accessing a function. # include<stdio.h> # include<conio.h> void main( ) calling function { Statement 1; Statement 2; --------------------------------- actual parameters function call (parameter1,parameter2) --------------------------------Statement n; called function } formal parameters datatype function name (arg1,arg2) function declaration Data type arg1, arg2; { C PROGRAMMING 33

Statement 1; Statement 2; --------------------------------Statement n; }

function code

In the above syntax main function is called as calling function because main is responsible to call the User-defined function with a function call. The function call is declared within the main function. The parameters declared within the function call are known as Actual Parameters. Where as the parameters declared within the function declaration are named as Formal Parameters. There are certain rules regarding actual and Formal Parameters. They are The number of Actual Parameters must match with the number of Formal Parameters. The data type of Actual Parameters must match with the data type of Formal Parameters. The name of Actual Parameters should differ from the names of Formal Parameters. The variables declared in the main function are called as global variables can be accessed both in the main function as well as user-defined functions whereas the variables declared in user-defined functions are known as local variables because they can be accessed only within the user-defined function. Sample program to demonstrate functions in :

Write a program in C to find the sum of three numbers using functions. # include<stdio.h> # include<conio.h> void main( ) { int a, b, c, sum; clrscr( ); printf(enter any three numbers); scanf(%d %d %d, &a, &b, &c); sum=calsum(a, b, c); printf(sum of three number is %d, sum); getch( ) } int calsum(x,y,z); int x, y, z; { int add; add = x+y+z; return (add); } C PROGRAMMING 34

POINTERS Breifly expain the concept of pointers in C. Pointers: A pointer is a variable which holds the address of another variable. Consider for example int i=10; In the above example i is an integer value variable, which holds only integer values and its value is 10. In memory i occupies 2 bytes of memory space and stores the value 10 in it with an address of 2869. i variable name
10

variable value

2869 variable address. In the above example in order to read the address of variable i, & is used. Hence & is known as address of operator or reference operator or reading operator. In the above example in order to display the value of a variable i, * operator is been used. Hence * operator is also known as value at address of operator or indirection operator or pointer operator. Consider for example the following statements. &i = 2869 *(&i) = i = 10 Call by value & call by reference: Call by value: The process of calling a function by passing a value is known as call by value. Within the function call if the values are send as actual parameters then it is called as call by value. Sample program to demonstrate functions in # include<stdio.h> # include<conio.h> void main( ) { int a, b; void swap(int, int); printf(enter any two values); scanf(%d %d, &a, &b); swap(a, b); getch( ) } void swap( x, y) int x,y; C PROGRAMMING 35 :

{ int temp; temp = x; x = y; y = temp; printf(swapped values of a = %d, b = %d x, y); } Call by reference: In this method rather than passing values of a function the addresses of the variables are been passed i.e., the variables and the variables declared in the function declaration are pointer variables. i.e., the actual parameters are declared as reference variables and the formal parameters are declared as pointer variables. Sample program to demonstrate functions in # include<stdio.h> # include<conio.h> void main( ) { int a, b; void swap(int*, int*); printf(enter any two values); scanf(%d %d, &a, &b); swap(&a, &b); getch( ); } void swap( *x, *y); int *x,*y; { int temp; temp = *x; *x = *y; *y = temp; printf(swapped values of a=%d, b=%d, *x,*y); } In the above program the function call is done with reference variables i.e., &a and &b. In order to access the values from the reference variables, the formal parameters are declared as *x :

C PROGRAMMING

36

and *y. i.e., pointer variables. Hence in call by value the value of the variables is passed to the function & in call by reference the address of variables are passed to the function. Write a C program to display roots of quadratic equation. # include<stdio.h> # include<conio.h> void main( ) { int a, b, c, sum; float dis, x1, x2; printf(enter values of a, b and c); scanf(%d %d %d, &a, &b, &c); dis = b*b 4*a*c; x1 = b + sqrt (dis)/2*a; x2 = b sqrt (dis)/2*a; printf(The roots of quadratic equation are x1 = %f, x2 = %f, x1, x2); getch( ); } ARRAYS IN C language is rich in data types. In C programming data is stored in variables. A variable is a name given to the memory location, which can store certain value. Consider for example the following program: # include<stdio.h> # include<conio.h> void main( ) { int i; i = 10; i = 5; printf (%d, i); } The output for the above program is given as 5 rather than 10. From the above program it is known that a variable can store only one value at a time. If we want to store more than one value it is not possible with normal variables. For this reason Arrays came into existence.

C PROGRAMMING

37

Array: An array is defined as a variable, which can store more than one values of same data type in other words it, is also defined as collection of elements of same data type. All these elements are stored with the common name. Syntax of Array: The array syntax in C programming is given as follows. datatype arrayname [size of the array]; Example for an Array: The declaration of array in C programming is given as follows. Consider for example the capacity of a class is 100 students. The marks of these 100 students are stored in a array variable known as Marks. i.e., int Marks[100]; In the above example, int is the data type of array marks and marks is the name of the array with the specified size 100. Accessing of array elements in memory: Once the array is declared the array elements number starts from zero th element and ends at (size1)th element. All these elements are known as subscripts of an array. The elements of the array are accessed with the help of subscripted values. These subscripted values are indicated within the square brackets. Hence array variable is also known as subscripted variable.
Marks Marks [0] Marks [1]

Subscripted values Marks[99]

In the above example, if the user wants to return marks of third student it is given as Marks[2] because the array count starts from zero th element. Advantages of an array: An array is a collection of elements of same data type. All the array elements are stored in continuous memory locations. As a result data accessing is very easy. Since array elements are stored in sequential manner data retrieval is more faster. The array count starts from zeroth element and ends at (size1)th element. All these elements are known as subscripts, which are indicated in []. Sample program to demonstrate arrays in :

Write a C program to find average marks of a class in one particular subject with the strength 30 by using arrays. C PROGRAMMING 38

# include<stdio.h> # include<conio.h> void main( ) { int i, sum, marks[30]; float avg; clrscr ( ); sum = 0; printf (enter the marks of 30 students); for (i = 0; i<=29; i++) scanf(%d, &marks [i]); for (i = 0; i<=29; i++) sum = sum + marks[i]; Avg = sum/30; Printf (Average mark of class is %f, Avg); getch( ); } Initialization of an array: Just like ordinary variables, Array variables can also be initialized. Initialization of an array means assigning values to the assay elements. Consider for example the following cases. int A[6] = {10, 20, 30, 40, 50, 60}; int B[ ] ={a, b, c, d, e, f, g}; In the above declaration of arrays the first example is static initialization. In static initialization the array size is fixed. In the above eg: A is a static array of size 6. That means the array A can hold only 6 values. On the other hand the array B is declared as dynamic array whose length is not fixed. We can increase or decrease the length of the dynamic array. In the above eg: B is a dynamic array of size 7. Memory Allocation of an array: When an array is declared the data of the array is stored in continuous memory lo0cations. Consider for example, int A[6] = {10, 20, 30, 40, 50, 60}; The memory allocation of an array is given as follows:
A[0] A[1] A[2] A[3] A[4] A[5]

10
2 bytes

20

30

40

50

60

2 bytes - - - - - - - - - - - - -- - - - - - - 2 bytes 12 bytes

C PROGRAMMING

39

In the above eg: six continuous memory locations are allocated. Each occupying 2 bytes of memory space and the arrangement of array elements starts from zeroth element and ends at (size 1)th element. Consider the example, int B[ ] ={a, b, c, d, e, f, g};
B[0] B[1] B[2] B[3] B[4] B[5] B[6]

a
1 bytes

1 bytes - - - - - - - - - - - - -- - - - - - - - - - - - - 1 bytes 7 bytes

2Dimensional Array: It is defined as a grid of rows & columns, which is represented in tabular format. Syntax of 2 Dimensional Array: In defining 2dimensional array the row size and column size should be specified. datatype Arrayname [row size] [column size]; eg: int A[3] [3]; Initialization of 2Dimensional Array: The 2dimensional array should be initialized depending on the row size & column size. Consider for eg, int A[3] [3] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}}; the initialized above array is displayed as follows: col 0 col 1 col 2 row 0 1 row 1 4 row 2 7 2 5 8 3 6 9

In the above eg:, the row & column count starts from zerth element and ends of (size1)th element. Memory allocation of 2Dimensional Array: Just like 1dimensional array the 2dimensional array is also indexed from zeroth element to the (size1)th element occupying corresponding bytes of memory depending on the data type. Representation of 2 D array in memory:
A[0][0] row 0 A[0][1] A[0][2]

1
A[1][0]

2
A[1][1]

3
A[1][2]

2 bytes

row 1

4
A[1][0]

5
A[1][1]

6
A[1][2]

2 bytes

6 bytes

row 2

7
Col 0

8
Col 1 18 bytes

9
Col 2

2 bytes

C PROGRAMMING

40

STRINGS Introduction in handling character strings: A string is a combination of group of individual characters. In other words a string can also be defined as an array of characters. A string is always enclosed in double quotation marks. The string enclosed in double quotation marks is also known as A constant string. Declaration & Initialization of a string constant: Declaration of a string: A string variable in C is declared as an array of characters. It is defined with the data type char and number of characters in a string is specified as an array. The general syntax of string variable: datatype stringname[size of the string]; Ex: Char stname [30]; Char city [25]; In the above examples if the size of the string is defined as n then the max number of character location available in memory are n+1 because one location is allocated for string terminator (10). Hence the size of the string is always equal to (size+1) character locations. Initialization of a string variable: Once a string is declared it must & should be initialized. The initialization of a string variable is gives as follows. Syntax-1: datatype stringname[size] = list of string characters. Eg: Syntax-2: datatype stringname [size] = {list of individual character} Eg: Char City [25] = {H, Y, D, E, R, A, B, A, D}; Char Sname[30] = Kamala;

Memory allocation of strings: The allocation of memory for a string variable where each character occupies 1 byte of memory is given as follows: Eg: (1) Char
1 bytes

S name[30] = Kamala;
1 bytes - - - - - - - - - - - - -- - - - - - - - - - - - - 1 bytes

A
7 bytes

(2) Char City [25] = {D, E, L, H, I};


1 bytes 1 bytes - - - - - - -- - - - - - - - - - - - - 1 bytes

6 bytes

C PROGRAMMING

41

String Handing Function: What are various string handing function in C, explain briefly. String Handing Function in C: The various string handing functions available in C are listed as follows: Read & Write Functions. String Concatenation String Copy String comparision Sub String String length Read & Write Functions: Read Functions: The most popular input function which is used to read the values of a character string is scanf. scanf is predefined function which is used to take input value. Eg:- char sname[30]; Scanf(%s, & sname); In the above examples sname is a character string where the value of a sname is read with scanf statement. %s is the string format. Write Functions: The most popular output function which is used to display the value is printf. Printf is the predefined function available in C programming to write a value. Eg:- Printf(your name is %s, Sname); In the above examples the contents sname are written in the place of string format %s. String Concatenation: The process of combining two different strings into a single resultant String is known as String Concatenation. In C programming there is a predefined function strcat( ) for combining two different strings into a single resultant String. Syntax: strcat(String1,String2); Eg: strcat(very, good); o/p: verygood String Copy: In order to cioy the contents of one string into another string the predefined function strcpy( ) is used. Syntax: strcpy(String1,String2); Eg: strcpy(city, Delhi); o/p: City=delhi In the above syntax, String2 contents are copied into string1. C PROGRAMMING 42

String Comparison: This function compares two strings according to their ASCII values. In order to handle this functionality the predefined function strcmp() is used. Syntax: Strcmp(string1, string2); Ex: strcmp(RAMA, RAMU); In the above example, if string1 is equal to string2 the output is 0. If string1< string2 the output is 1 and if string1>string2 the output is 1. Sub string: This function is used to retrieve the remaining part of the string after deleting the sub string. In order to handle this functionality the predefined function is substr() Syntax: substr(string1, string2); Ex: substr(Madhu, Mad); o/p: hu String Length: This function is used to return number of characters present in a string. In order to handle this functionality the predefined function is given as strlen() Syntax: strlen(string1); Ex: strlen(Elephant); o/p: 8.

UNIT-5
BITWISE OPERATORS
The bitwise operators in C basically used to represent binary values. They are basically classified into two types: Logical Operators Shift Operators Bitwise Operator Logical Bitwise Compliment 1s Compliment 2s Compliment Bitwise AND Bitwise OR Bitwise Ex-OR Shift Left Shift Right Shift Symbol ~ & | ^ << >>

C PROGRAMMING

43

Bitwise Compliment: the operator Tilde(~) is called as bitwise compliment operator. The functionality of this operator is to reverse the bit-string i.e. it converts ones into zeros and zeros into ones. This functionality is named as 1s compliment function. Consider for example the following bit-string: A = 11011011 10101011 10000000

The 1s compliment for the above bit-string is given as follows: ~A = 00100100 01010100 01111111

The 1s compliment is denoted by (~A) where ones are converted into zeros and zeros are converted into ones. 2s Compliment: The 2s compliment value is given by adding +1 to the 1s compliment value. 2s compliment = 1s compliment + 1; 1s = 00100100 01010100 01111111 +1 -----------------------------------------------------2s = 00100100 01010100 10000000

Bitwise AND, Bitwise OR Bitwise Ex-OR: the three Bitwise logical operators Bitwise AND, Bitwise OR and Bitwise Ex-OR are known as binary operators because they work with two operands. Sample table to demonstrate bitwise logical operators: a 0 0 1 1 Shift Operators: These operators are basically used to shift the bit string either towards left or towards right. These operators are classified into two types: Left Shift Operator Right Shift Operator Left Shift Operator: this operator shifts the bit string towards the left and number of shifts depend upon the values specified. Left shift operator is denoted by <<. Right Shift Operator: this operator shifts the bit string towards the right and number of shifts depend upon the values specified. Right shift operator is denoted by >>. Sample table to demonstrate Left Shift Operator and Right Shift Operator: b= Left Shift: b<<2 = 00000000 00000000 00000001 00010100 00000100 01010000 00110011 11001100 Original Bit string Left shift by 2. 44 b 0 1 0 1 a&b 0 0 0 1 a|b 0 1 1 1 a^b = ab`+a`b 0 1 1 0

C PROGRAMMING

b<<4 = Right Shift: b>>2 = b>>4 =

00000000 00000000 00000000

00010001 01000011 00000000 01000101 00000000 00010001

00110000 00001100 01000011

Left shift by 4. Right shift by 2. Right shift by 4.

ENUMERATION DATA TYPES Enumeration data types: Enumeration data types are also named as user defined data types. Enumeration data types are defined as the data types, which are used for naming finite set of values. The declaration of enumeration data type is done by using the keyword enum. The finite values present in enumeration are known as elements of the enumeration data type. Syntax: Enumeration data type name list of variables; Eg: (i) enum day d1, d2; (ii) enum month m1, m2; In the above eg (i) d 1 & d2 are the variables of data type day. (iii) enum suit s1, s2; In the above eg (iii) s1 & s2 are the variables of data type suit. In the above eg (ii) m1 & m2 are the variables of data type month. Initialization of finite elements to the enumeration data type: Just like normal data types enumeration can also be initialized. These initialized values are finite set of values. These values are known as elements or identifiers of Enumeration data type. Syntax: Enumeration data type name {finite set of values}; Eg: (i) enum day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; In the above eg: the data type is initialized with seven finite values. These values are called as elements or identifiers. (ii) enum suit {spade, club(elements or identifiers), diamond, heart} (iii) enum month {Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov, Dec}; initialization of elements or identifiers: The elements or identifiers of enumerations can also be initialized. Consider for example, (i) enum fruit {apple = 1, custard apple, pineapple = 7, green apple}; In the above eg, the enumeration element apple is initialized to 1. Hence custard apple = 2 and pineapple is initialized is 7, hence green apple = 8. C PROGRAMMING 45

(ii) enum veg {bottle guard = 1, snake guard, bitter guard, ribbed guard}; In the above eg, the enumeration element bottle guard is initialized to 1, therefore snake guard, bitter guard, ribbed guard are initialized with corresponding values 2, 3, 4 etc. Sample program to demonstrate Enumeration data types in # include<stdio.h> # include<conio.h> void main( ) { enum day {Sun, Mon, Tues, Wed, Thu, Fri, Sat}; day d; printf(enter your day); if(d = = sat); { printf (weekend); } else { printf (weekday working day); } } write a program in C to conclude next day by using enumeration data type: # include<stdio.h> # include<conio.h> void main( ) { enum day {Sun, Mon, Tues, Wed, Thu, Fri, Sat}; day d; clrscr( ); d = sum; day next day (day d); { day nd; switch( ) { case sun: C PROGRAMMING 46 :

nd = Mon; break; case mon: nd = tue; break; case tue: nd = wed; break; case wed: nd = thu; break; case thu: nd = fri; break; case fri: nd = sat; break; case sat: nd = sun; break; } printf (next day is :, nd); } getch( ); } PREPROCESSOR: Write a short note on Preprocessor? Every C program starts with a preprocessing directive # has certain pre-defined functionality to execute the C programming code. The preprocessing directives in C as defined by ANSI-C. This preprocessing directives are basically classified into two types: # include # define # include: This directive is basically used to include standard header files available in C library. C PROGRAMMING 47

Eg:

# include <stdio.h> # include <conio.h> # include <math.h> In the above examples, stdio.h, conio.h, math.h are the predefined header files available in

C library. Consider for example the another form of # include: # include area.h # include compute.h # include square.h In the above examples area.h, compute.h, square.h are user defined header files, which are defined by the C users. Hence the preprocessing directive # include replaces the entire programming code with the standard header file properties. Because of this directive the program execution is more faster. Sample program to demonstrate # include: # include<stdio.h> # include<conio.h> void main( ) { int a, b, c, small; clrscr ( ); printf (enter the three nos); scanf(%d, %d, %d, &a, &b, &c); If(a<b) { If (a<c) { small = a; Printf (smallest of 3 nos %d, small); } else { small = c; Printf (smallest of 3 nos %d, small); } } else If (b<a) 48

C PROGRAMMING

{ If (b<c) { small = b; Printf (smallest of 3 nos %d, small); } else { small = c; Printf (smallest of 3 nos %d, small); } } } # define: The second preprocessing directive which is used to define constant values in C is (hash) # define. The functionality of # define is it replaces every occurance of the variable with the given value. Hence # define is used to define constant values of C. Sample program to demonstrate C constant: # include<stdio.h> # include<conio.h> #define Pi 3.14 void main( ) { int radius; float circumference: printf (enter the radius of circle); scanf(%d, &radius); circumference = 2 * Pi * radius; printf (circumference of given circle is %f, circumference); getch( ); } STRUCTURES AND UNIONS: Briefly explain the concept of structures and unions in C. (or) What are heterogeneous data types, define them. (or) C PROGRAMMING 49

Write a short note derived secondary heterogeneous data types. (or) What is a structure and union? Hexo unions differ from structures. C is an extensible programming language, which is provided with different data types. The basic data types of C are known as fundamental data types. The data types that are derived from fundamental data types are known as derived /secondary data types. The examples of these secondary data types are Arrays Structures Unions Pointers Arrays: An array is a homogeneous secondary data type, which can hold elements of same data type where as structures and unions are heterogeneous data types which can hold different data type values. Structures: Structures are the secondary derived data types, which can hold values of different data types. Hence they are also known as heterogeneous data types. They are defined with the key word struct. Syntax for a structure: Struct stryctname { datatype1 var1, var2, - - - - - - - - - - - var n; datatype2 var1, var2, - - - - - - - - - - - var n; : : datatypen var1, var2, - - - - - - - - - - - var n; }struct 1, eg: struct EMP { int Eid, Esal; char[25] Eadd, Ename; }E1, E2, E3; In the above example, E 1, E2 & E3 are the 3 structure variables of employee structure. Memory allocation of structure variale employ: The heterogeneous data type structure occupies 27 bytes of memory, where the integer data type occupies 2 bytes & the character string occupies 25 bytes. Hence a total 27 bytes of memory is occupied by the structure variable employee. struct 2, - - - - - - - - - - - - struct n;

C PROGRAMMING

50

Unions: Similar to structures unions are the derived data types which follow the same syntax as structures. Unions are defined with the key word union. It is also a heterogeneous data type, which can hold different data type values. Syntax: union union name { datatype1 var1, var2, - - - - - - - - - - - var n; datatype2 var1, var2, - - - - - - - - - - - var n; : : datatypen var1, var2, - - - - - - - - - - - var n; } union 1, union 2, - - - - - - - - - - - - union n; eg: union EMP { int Eid, Esal; char[25] Eadd, Ename; } E1 , E2 , E 3 ; The only difference between structures & unions is unions occupy less memory. When compared to structures i.e., the difference exists in memory allocation. Memory allocation for unions: Unions are supported with dynamic memory allocation i.e., unions consider the maximum memory occupied by a particular data type & share the memory to the remaining data types. Hence all the data types are defined within the same memory location dynamically. In the above eg, employee the maximum size of the memory is 25 bytes, which can also be used dynamically to store integer bytes. As a result unions occupy less memory through dynamic memory allocation and utilize the memory in an efficient way. Hence unions are more flexible when compared to structures. Explain the differences between structures and unions. Structures Structures are the heterogeneous data types which are derived from the primary data types. Structures are defined with the keyword struct. They occupy more memory. They follow static memory allocation. Memory sharing is not possible in structures. The total memory bytes depends on available data types. The structural syntax of a structure is struct structname Unions Unions are also heterogeneous data types which are derived from the primary data types. Unions are defined with the keyword union. They occupy less memory. They follow dynamic memory allocation. Memory sharing is possible in unions. The total memory bytes depends on the maximum values of the data type. The structural syntax of a union is union unionname 51

C PROGRAMMING

{ data type 1 data type 2 : : data type n } struct 1, struct 2, - - - - - - - - - - struct n; var1, var2, - - - - - - - var n; var1, var2, - - - - - - - var n;

{ data type 1 data type 2 : : data type n } union 1, union 2, - - - - - - - - - - - union n; var1, var2, - - - - - - - var n; var1, var2, - - - - - - - var n;

var1, var2, - - - - - - - var n;

var1, var2, - - - - - - - var n;

Explain the differences between homogeneous and heterogeneous: Homogeneous i. The data types, which can store values of same data type, are known as homogeneous data types. ii. The example for these data types is arrays. iii. These data types occupy more memory when compared to heterogeneous data types. iv. Memory is not well utilized in these data types. v. In these data types data is stored in requencial manner. vi. Data accessing is more faster in these data types. vii. In these data types the size of the array must be specified. Heterogeneous i. The data types which can store values of different data type are known as heterogeneous data types. ii. The example for these data types is structures and unions. iii. These data types occupy less memory space. iv. Memory is well utilized by unions in these data types. v. In these data types data is stored in random manner. vi. Data accessing is consuming under these data types. vii. In these data types the size need not be specified.

INPUT OUTPUT OPERATIONS Briefly explain about the input & output operations performed in C programming. (or) Explin in detail about printf & scanf functions. Input & Output operations in C: The input & output operations in C are performed by using the predefined functions printf( ) & scaf( ). The functionalities of these functions are defined within the standard header file <stdio.h>. The input functionality is carried out by scanf( ) and the output functionality is carried out by printf( ). Input operation: The input operation in C is provided by the predefined function scanf( ). In C programming reading of variable values is done by using scanf( ) function. Scanf( ) is the basic input function which is highly flexible to read the values in C program. The functionality of scanf( ) is defined in the standard header file <stdio.h>. The standard header file informs the scanf( ) to read the values from various input devices like Keyboard Mouse

C PROGRAMMING

52

Joystick Light pen ect.

Within the scanf( ) variable values are read by using reference operator &. In order to read values scanf( ) is provided with various formats. Format table for scanf( ): Format %c %d %f %lf %Lf %s %o %x Description Used to represent single character. Used to represent integer value. Used to represent float value. Used to represent double value. Used to represent long double value. Used to represent string character. Used to represent octal value. Used to represent hexa decimal value.

Output operation: The output operation in C is provided by the predefined function printf( ). In C program values are displayed by using the output function printf( ). Printf( ) is the most highly flexible output function used in C programming. The functionality of printf( ) is defined in the standard output file <stdio.h>. The standard output file informs the printf( ) to display the values on various output devices like i. ii. iii. VDU/Monitor Printer Speaker etc.

The data that is to be displayed on the output devices is to be included within the doub le quotes in printf( ). The various formats that are used to display values in printf( ) are given as follows: Format table for printf( ): Format Description %c Used to represent single character. %d Used to represent integer value. %f Used to represent float value. %lf Used to represent double value. %Lf Used to represent long double value. %s Used to represent string character. %o Used to represent octal value. %x Used to represent hexa decimal value. Sample program to demonstrate printf( ) and scanf( ): # include<stdio.h> # include<conio.h> void main( ) C PROGRAMMING 53

{ int i; float per; long int mobile; char[25] name, address; clrscr( ); printf(enter your name); for (i = 0; i<=24; i++); scanf(%s, &name[i]); printf(enter your address); for (i = 0; i<=24; i++); scanf(%s, &address[i]); printf(enter your %); scanf(%f, &per); printf(enter your mobile no); scanf(%ld, &mobile); for (i = 0; i<=24; i++); { printf(your name is %s, name[i]); printf(your address is %s, address[i]); } printf(your per is %f, per); printf(your mobile no is %ld, mobile no); getch( ); } Brifly explain the differences between input & output functions in C: Input functions Output functions 1. The function that is used to read the value 1. The function that is used to display the value from various input devices like keyboard, on various output devices like VDU/Monitor, mouse, etc is known as input function. printer, speaker etc is known as output function.

C PROGRAMMING

54

You might also like