Вы находитесь на странице: 1из 25

Unit III

CONTROL SRUCTURES Decision Making And Branching Looping: In c the following are the control or decision making statements: If statement Switch statement Goto statement
If statement

It is used to control the flow of execution of statement. Syntax: if(condition) Evaluate the condition first and then depending on whether the value of the expression is true or false it transfers the control to a particular segment. Different types: Simple if: Syntax: if(condition) { statement _block; } statement_x; If the condition is true, the statement block will be executed. Otherwise, statement_block will be skipped and the execution will jump to statement_x. When the condition is true both statement block and statement x will be executed in sequence. Eg: #include<stdio.h> #include<conio.h> void main() { int a,b; 1 Simple if if ..else Nested if..else else.if

a=30; b=20; if(a>b) { a=a+b; } printf(%d,a); getch(); } The output is: 50. In this program, value of a is 30 and value of b is 20. Check the condition (a>b) if its true the control execute the statement a=a+b and print the value of a. Otherwise the control execute only one statement that statement is print the value of a. if.else: Syntax: if(condition) { true _block statement; } else { false _block statement; } statement_x; if condition is true, true _block statements will be executed. Otherwise, false _block statements will be executed. Eg: #include<stdio.h> #include<conio.h> void main() { int a,b;

a=30, b=20; if(a>b) { printf(a is greatest); } else { printf(b is greatest); } printf(\n Welcome); getch(); } The output is: a is greatest Welcome If condition is true, print the statements a is greatest and Welcome. Otherwise print the statements b is greatest and Welcome. Nested if statements Here more than one if.else statements are nested. Syntax: if( condition1) { if(condition2) { statement_1; } else { statement_2; } } else { statement_3; } statement_x;

When both the conditions 1 and 2 are true, it executes the statement_1 and statement_x. If condition1 is false, it execute the statement_3 and statement x. If condition2 is false, it execute the statement_2 and statement x else if ladder Syntax : if(condition1) statement1; else if(condition2) statement2; else if(condition3) statement3; else default_statement; statement_x; The conditions are evaluated from the top. If a true condition is found, the statement associated will be executed and the control is transferred to statement_x. if all the conditions are false, default_statement will be executed. Eg: #include<stdio.h> #include<conio.h> void main() { int avg; printf(Enter the average:); scanf(%d,&avg); if(avg>79) printf(Grade=Honours); else if(avg>59) printf(Grade=First Class); else if(avg>49) printf(Grade=Second Class);

else if(avg>39) printf(Grade=Third Class); else printf(Grade=Fail); getch(); } The Switch statement: If we use else-if ladder, the program becomes complex. So we use switch statement. Multiway decision statement. Tests the value of a given variable against a list of case values and when a match is found , block of statement associated with that case is executed. Syntax : switch(expression/variable) { case val-1: block-1; break; case val-2: block-2; break; case val-3: block-3; break; default: default_block; break; } statement_x; The expression is an integer or character expression. Val-1, val-2, val-3..are called case_labels. Each case_label should be unique. The value of expression is compared against, val-1, val-2 if a match is found; the block of statements of that case will be executed. If there is no_match default_block will be executed. Default is optional. The break statement signals to exit from switch statement.

Eg:

#include<stdio.h> #include<conio.h> void main() { int x; printf(Enter the x value:); scanf(%d,&x); switch(x) { case 1: printf(one); break; case 2: printf(two); break; case 3: printf(three); break; default: printf(invalid); break; } }

Output: Enter the x value: 1 one. Enter the x value: 4 invalid In this program, the value of x is 1. The value of x is compared against, 1, 2, 3, a match is found; the block of statements of case 1 will be executed. Second time it getting another one value, that value is 4. There is no_match default_block will be executed. It print the statement is invalid. LOOPING: looping statements execute the body of the loop repeatedly until some conditions are satisfied. There are 2 types of loops. Entry controlled loop Exit controlled loop

In entry controlled loop the conditions are tested first if the conditions are not satisfied the body of the loop will not be executed. In exit controlled loop the conditions are tested at the end of body of body of loop, so the body of loop is executed for the first time. C language has 3 looping statements. They are, While statement Do statement For statement While statement: Syntax : while(condition) { body of the loop } while is an entry controlled loop. Condition is evaluated first. If it is true loop is executed. This process is repeated until the test condition becomes false. The body of loop may have one or more statements. Braces are needed only if the body has more than 1 statement. Eg: #include<stdio.h> #include<conio.h> void main() { int i=1; while(i<=5) { printf(Welcome); i++; } getch(); }

Output: Welcome Welcome Welcome Welcome Welcome Do statement Syntax: do { body of the loop; }while(condition); This is an exit controlled loop. The body of the loop is executed first. Then the condition is evaluated. If it is true then the body of loop is executed again. This process continues until the test condition becomes false. So the body of loop is executed at least once. Eg: #include<stdio.h> #include<conio.h> void main() { int i=10; do { printf(Welcome); i++; } while (i<=5); getch(); } Output: Welcome

For statement Syntax: for(initialization part; condition part;increment/decrement part) { body of the loop; } This is an entry controlled loop. Initialization of variables is done first using assignment statements. Condition is evaluated next. If it is true body of the loop is executed. Then the increment part is evaluated condition is evaluated and the process repeats until the test condition becomes false. Eg: #include<stdio.h> #include<conio.h> void main() { int i; for(i=1;i<=5;i++) { printf(Welcome); } getch(); } Output: Welcome Welcome Welcome Welcome Welcome

Unconditional Statement The goto statement: C uses goto statement to branch from one point to another point unconditionally. Goto statement requires a label to identify the place label is any valid variable name. Syntax : goto labelname; labelname is referred to identify the location. goto statement used to transfer control to another location in a program.

forward jump goto label; : : label: statement;

backward jump label: statement; : : goto label;

label: can be written either before or after the goto statement. During the running of the program, when goto statement is met, control will jump to the statement immediately following the label. This happens unconditionally. Eg: #include<stdio.h> #include<conio.h> void main() { int x; lb: printf(Enter the x value:); scanf(%d,&x); goto lb; }

10

Break statement If you want to jump out of the loop during the execution of loop we can use break statement. Syntax: Continue statement Transfer the control to the next iteration of the nearest enclosing do, for or while statement. Syntax: continue; These 3 types are unconditional statements. break;

Functions
C functions are classified into 2 categories: 1. Library functions. Library functions are predefined functions. It is not written by the user. Eg: printf(), scanf(), sqrt(), etc 2. User_defined functions. This function should be written by the user. Eg: add(), f1(), f4(), etc Advantages: Length of source program can be reduced.

Form of c functions:(Function definition) Syntax: Datatype Functionname(argument list) { Local variable declaration; Executable stmt1; Executable stmt2; --------------------return(expression); }

11

All parts are not essential some may be absent. Functionname is similar to other variables in c. The argument list contains valid variable names separated by commas. List is surrounded by commas. Eg: power(x,n) Return values: A function may or may not send back values to the calling function. The value is returned thru return statement. The function can return only one value per call. Syntax : Eg1 Eg2 return; (or) return(expression)

return(x*y); if(x<=0) return(0); else return(1);

We can specify the return type of a function in the function header. Eg double product(x,y) It means that the return type is double. Function declaration: Syntax: Datatype Functionname(parameters) Eg: Calling a function: A function can be called by using the function name in a stmt. Eg x=add(10,5); When the compiler finds a function call control is transferred to that function. Eg program: #include<stdio.h> #include<conio.h> void main() 12 int add(int,int)

{ int add(int,int); printf(Functions); x=add(%d,x); } int add(int x,int y) { int z; z=x+y; return(z); } In the program, x takes the value 10, y takes value 2.add these two values and stored in variable is z and returned to add() which is then returned to x and print the value of x. Category of function: Functions , depending on the arguments , and return values , are classified as 1. Functions with no argument and no return value. 2. Functions with argument and no return value. 3. Functions with no argument and one return value. 4. Functions with argument and one return value. 1. Functions with no argument and no return value Here there is no data transfer between the calling function & the called function. A function does not receive any data and it does not return any value. Function defination Function header Function call printf(value of x is: %d,x); Function declaration

Function1() { ----------------------------Function2(); }

no input

Function2() { -----------------------------

no output 13 }

Eg #include<stdio.h> #include<conio.h> void main() { clrscr(); printf(Functions); printline(); printf(First Category); getch(); } printline() { Printf(----------------------); } The output is: Functions -------------------First Category 2. Functions with argument and no return value. We make calling function to read date from the terminal and pass it on to the called function. One way data communication.

14

Function1() { ----------------------------Function2(a); }

argument

Function2(f) { -----------------------------

no return values }

The argument in the function call is called actual argument and the values in the called function are called formal arguments. The actual and formal arguments should match in number type and order. If in case the actual arguments are more than formal arguments, then the extra actual arguments are discarded. If actual arguments are less, then the extra formal argument will be initialized to garbage values. When a function call is made, only a copy of the values of actual argument is passed into function. Main() { ---Fun1(a1,a2am) 15 actual arguments

} Fun1(f1,f2.fn) Formal arguments { ----------------------------------} Eg: #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf(Enter the values for a&b ); scanf(%d%d,&a,&b); mul(a,b); getch(); } void mul(int p,int q) { int m; m=p*q; printf(The value of m is%d,m); } The output is: Enter the values for a&b 10 20 The value of m is 200 p & q are Formal arguments a & b are actual arguments

16

3. Functions with no argument and one return value Passes no arguments but the called function returns a value of the function call/calling function.

Function1() { ----------------------------Function2(a); } result

Function2(f) { ----------------------------Return(e); }

Eg: #include<stdio.h> #include<conio.h> void main() { int c; clrscr(); c=add(); printf(The value of c is%d,c); 17

getch(); } int add() { int x,y,z; printf(Enter the values for x & y); scanf(%d%d,&x,&y); z=x+y; return(z); } The output is: Enter the values for x & y 10 20 The value of c is 30 4. Functions with argument and one return value. Passes arguments but the called function returns a value of the function call/calling function. Two way communication.

Function1() { ----------------------------Function2(a); }

argument

Function2(f) { -----------------------------

result

Return(e); }

18

Eg: #include<stdio.h> #include<conio.h> void main() { int x; clrscr(); x=int div(10,2); printf(The value of x is%d,x); getch(); } int div(int a, int b) { int c; c=a/b; return(c); } The output is: The value of x is 5. Recursion A function calling itself is called recursion. Eg: main() {

19

printf(example); main(); }

File Management In C
File is a technique to store the information in the Secondary Storage Device (SSD). Informations are permanent. The informations available in the program are stored in the memory without using a file.. Place on the disk where a group of related data is stored and data can be read whenever necessary File operations Naming, opening, reading from, writing to, closing

The four steps needed for writing a file program Step 1: Declaring the filepointer Declaring the file pointer by using the format is FILE*filepointername; filepointername denotes the pointer which points to the address of the latest information stored in the file. Initially, the filepointer value is null since there is no data in the file. When the data is written in the file, the file pointer moves to the lastly accessed data.

Step 2: Opening a file If we want to perform an operation on a file, the file must be opened. To open a file by using the format is filepointername = fopen(filename,mode); where the mode may be 3 types , we can use anyone at time. They are w r for writing an information into the file for reading an information from the file 20

for appending an information into the file. When file is opened in the append mode, the file is opened for writing without deleting the already data if present

Note: w a file with specified name is created if the file contents deleted, if the file exists. r if exists file is opened with the current content safe otherwise error. a file opened with the current contents safe. a file created if not exists . . Step 3: Input and output operation After the file is open, we can perform the input & output operation. Input / Output Operations for file Character Function: Used to read & write character functions. getc() & putc() getc() Read the single character from the text file and assigned to c. c= getc(fp) putc() - Handles one char at a time. Writes a char to the file opened with write mode putc(c,fp) fp - filepointer The getc will return an end of file markers EOF when end of file has been reached. So reading should be terminated when EOF is encountered Integer Function: Used to read & write integer functions. getw() & putw() getw() Read the integer value from the file and assigned to n. n= getw(fp) putw() - Writes a integer to the file opened with write mode putw(n,fp) Mixed Data File Input and Output: Used to read and write more than one different data at time. Like character , float and integer. fprintf and fscanf Can handle a group of mixed data. Similar to printf & scanf.

21

Syntax : fscanf(fp,format specification,&variable); fprintf(fp,format specification,variable); Eg: fprintf(f1,%s%d%f,name, age,7.5); fscanf(f2,%s%d,item,&quantity); There is no & symbol for string variable. Step 4: Close a file After the operation is performed on a file ,the file must be cosed. Syntax : fclose(file-pointer); file must be closed as soon as all operations are over. All outstanding information flushed out from buffers, links are broken. Prevents any accidental misuse. Close the file when we want to reopen the same file in different mode. File input/output function in c library fopen() Creates a new file opens. fclose() Closes which has been opened for use. getc() Reads a char from file. putc() Writes a char to file. fscanf() Reads a set of data values from a file. fprintf() Write a set of data values into a file getw() Read an integer. putw() Write an integer. fseek() Used to move the filepointer to the specified location randomly.accessing a file randomly. Syntax: fseek(filepointer,offset,position); Offset Specifies the number of positions to be moved from the current location. Offset may be positive or negative Offset positive moving forward. Negative - backward. 22

Position Position may be 0,1,2 0 if the move from the beginning of the file. 1 fp is to be moved from the current position. 2 fp is to be moved from end of the file. Eg: fseek(f1,4,0) moves the fp to the 5 th byte in the file from beginning of the file(forwardmore). fseek(fp,OL,O) - Goto begin fseek(fp,m,o) Move to (m+1)th byte. fseek(fp,m,1) Go forward by m bytes. fseek(Fp,-m,1)- Go backward current fseek(Fp,-m,2) Go backward from end. If open is success return 0, otherwise -1.

ftell() It returns the current position in file. (in terms of bytes) Syntax: N=ftell(fp); N will be 0. First byte will be number as 0 , second as 1 ,.. Helps in reading a file more than once, without having to close & open the file. When a file is opened rewind is done implicitly. rewind() Used to move the filepointer to the beginning of the file. Syntax: rewind(fp); Error Handling During Input/Output: Error which may occur during input/output operations on a file. 1.trying to read beyond EOF. 2. trying to use a file that has not been opened. 3. trying to perform an op. when the file is opened for another type of operation. 4. opening a file with an invalid filename 5. attempting to write to a write. Protected file . If we fail to check such errors a programs behave abnormally.

23

feof: Test an end of file condition Returns nonzero int if all data from the specified file has been read & returns zero otherwise. Eg: if(feof(fp)) printf(end of data); ferror() Report the states of file. Returns nonzero if an error occurs up to that pt. zero otherwise. Eg: if(ferror(fp)!=0) printf(error); NULL pointer: While using fopen, if the file cannot be opened then it returns a null pointed. Used to test whether the file has been opened or not. Eg if(fp==NULL) Printf(File cannot be opened); Eg:2 If((fp2 =fopen(filename,r))==NULL) Printf(cannot open); Eg program: // Creating a text file #include<stdio.h> #include<conio.h> void main() { FILE *fp; 24

fp=fopen(sample.txt,w); while((c=getc(fp))!=EOF) putc(c,fp); fclose(fp); }

25