You are on page 1of 63

Practical #1: Getting acquainted with the C program Structure and basic I/O.

Objective
The goal of this lab is to help you become acquainted with the C program structure. In this lab you will learn about how to write program in C language using Turbo C compiler.

Instructions
Before we begin with our C program do remember the following rules that are applicable to all C programs: 1. Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements. 2. The statements in a C program must appear in the same order in which we wish them to be executed; unless off course the logic of the problem demands a deliberate jump or transfer of control to a statement, which is out of sequence. 3. Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword. 4. All statements are entered in small case letters. 5. C has no specific rules for the position at which a statement is to be written. Thats why it is often called a free form language. 6. Every C statement must end with a ; acts as a statement terminator.

Instructions for compiling and executing C program:


Assuming that you are using Turbo C or Turbo C++ compiler here are the steps that you need to follow to compile and execute your first C program. 1. Start the compiler at C>prompt. The compiler (TC.EXE is usually present in C:\TC\BIN directory) 2. Select New from the file menu . 3. Type the program. 4. Save the program using F2 under a proper name (say program1.c). 5. Use Ctrl+F9 to compile and execute the program.

6. Use Alt+F5 to view the output.

C program structure:
Every C program consists of following parts: 1. Comments At the beginning of each program is a comment with a short description of the problem to be solved. A possible comment for this program might be this: /* Program program1.c print the number from 4 to 9 and their square*/ The comment begins with /* and ends with */. The symbols /* and */ are called comment delimiters. 2. The program header After the comment, we can start writing the program. The next two lines of our C program look like this: #include<stdio.h> main() The #include directive tells the compiler that we will be using parts of the standard function library. Main(), is called the main program header. It tells the c compiler that we are starting to work on the main function of this program. Every C program must have a main function since this is where the computer begins to execute the program. 3. The body or action portion of the program Just as an English language paragraph is composed of sentences, a C program is made up of C statements.

Structure of a C program:
/*program program1.c print the number from 4 to 9 and their square*/ #include<stdio.h> main() { /*action portion of the program goes here*/ .. } Sample Program: /*display a message on the monitor*/ #include<stdio.h> void main() { printf(Welcome to Computer programming\n); }

Output function:
Unlike other languages, C does not contain any instruction to display output on the screen is achieved using readymade library functions, one such function is printf() The general form of the printf() function is, Printf(<format string>,<list of variable>); <format string >can contain, %f for printing real values %d for printing integer values

%c for printing character values Summary of the printf(): Int num; float x; Num=14; X=22.6; Statement Printf(help); Printf(%d,num); Printf(14); Printf(14); Printf(%d); Printf(%fis the answer,x); Printf(%d is less then %f,num,x); Printf(Stop here); Printf(go\non\n); Result help 14 14 compilation error 14 22.600000 is the answer 14 is less then 22.600000 Stop here go on

Receiving input:
The scanf() function is used to receive the input from the keyboard. The general form of the scanf() function is, scanf(<format string>,<& with list of variable>); <format string >can contain, %f for printing real values

%d for printing integer values %c for printing character values Note that the ampersand (&) before the variable in the scanf() function is a must & is an address of operator. It gives the location number used by the variable in the memory. When we say &a, we are telling scanf() at which memory location should it store the value supplied by the user from the keyboard. Summary of the scanf(): int p,n; float r; Statement scanf(%d%d%f,&p,&n,&r); Sample Program: /*Just fun, Author Yash */ void main() { int num; printf(enter number); scanf(%d,&num); printf(Now I am letting you on a secret); printf(You have just entered the number %d,num); } Exercises: 1. Print on the Screen : Hello How are you?

2. Input and output your Rollno., marks, and percentage to an appropriate format.

Practical #2 : Getting acquainted with the various types of data used in C.


Objective
The goal of this lab is to help you become acquainted with the various types of data type in C.. In this lab you will learn about how to do operations with various types of data in C language.

C data Types:
Variable definition C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. So what data types are available? 1. int int is used to define integer numbers.
{ } int Count; Count = 5;

2. float float is used to define floating point numbers.


{ float Miles; Miles = 5.6; }

3. double double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.
{ double Atoms;

Atoms = 2500000; }

4. char char defines characters.


{ } char Letter; Letter = 'x';

Modifiers
The three data types above have the following modifiers.

short long signed unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:
short int <= int <= long int float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:
Type short int unsigned short int unsigned int int long int signed char unsigned char float double long double Bytes 2 2 2 2 4 1 1 4 8 12 Bits 16 16 16 16 32 8 8 32 64 96 Range -32,768 0 0 -2,147,483,648 -2,147,483,648 -128 0 -> -> -> -> -> -> -> +32,767 +65,535 +4,294,967,295 +2,147,483,647 +2,147,483,647 +127 +255

Exercise1. A c program contains the following statements: #include<stdio.h> int i, j; long ix; short s; unsigned u; float x; double dx; char c; For each of the following groups of variables, write a scanf function that will allow a set of data items to be read into the computer and assigned to the variables. (a) i ,j, x and dx (b) i, ix, j, x, and u (c) i, u and c (d) c, x, dx and s Exercise2. A c program contains the following statements: #include<stdio.h> int i,j; long ix; unsigned u; float x; double dx; char c; For each of the following groups of variables, write a printf function that will allow the values of the variables to be displayed. Assume that all integer will be shown as decimal quantities. (e) i ,j, x and dx (f) i, ix, j, x, and u (g) i, u and c (h) c, x, dx and s

Practical #3 : Getting acquainted with the simple arithmetic operator in C.


Objective
The goal of this lab is to help you become acquainted with the various arithmetic operators in C.. In this lab you will learn about how to use various arithmetic operators in C language

Arithmetic operator:
There are five arithmetic operator in c. They are: Operator + * / % Purpose addition subtraction multiplication division remainder after integer division

Example: Suppose that a and b are integer variables whose values are 10 and 3. Expression Value a+b 13 a-b 7 a*b 30 a/b 3 a%b 1

Hierarchy of Operations
Priorit Operators y 1st */% 2nd +rd 3 = Example: K=2*3/4+4/4+8-2+5/8 K=6/4+4/4+8-2+5/8 K=1+4/4+8-2+5/8 K=1+1+8-2+5/8 K=1+1+8-2+0 K=2+8-2+0 K=10-2+0 K=8+0 K=8 Description Multiplication, division,modulas Addition, subtraction assignment

Exercise1. A c program contains the following declarations and initial assignments: int i=8,j=5; float x=0.005,y=-0.01; char c=c,d=d; Determine the value of each of the following expressions. Use the values initially assigned to the variables for each expression. (a) (3*i-2*j))+(i%2*d-c)

(b) 2*((i/5)+(4*(j-3))%(i+j-2) (c) (i-3*j)%(c+2*d)/(x-y) Exercise2. A c program contains the following declarations and initial assignments: int i=8,j=5,k; float x=0.005,y=-0.01,z; char a,b,c=c,d=d; Determine the value of each of the following assignment expression expressions. Use the values initially assigned to the variables for each expression. (a) k=(i+j) (b) z=(x+y) (c) k=(x+y) (d) z=i/j (e) i=i%j Exercise3. Rams basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.

Practical #4: Getting acquainted with decision control statement.


Objective
The goal of this lab is to help you become acquainted with the various decision control statements in C. In this lab you will learn about how to use various decision control statements in C for taking decision. C has three major decision making instructions. 1. The if statement 2. The if else statement 3. The nested if else statement

The if statement:
This is single entry /single exit structure if (expression) { statement1; next statement; } Statement 3; The expression must be placed in parentheses In this form statement is evaluated only if expression has non zero value. If the expression has a value of zero then statement inside if statement are ignored Sample Program

#include <stdio.h> int main() { int x; printf("Please enter an integer: "); scanf("%d", &x); if (x > 10) printf(no is greater than 10\n"); printf(hello world); return 0; } The > is an example of a relational operator. A relational operator takes two operands and compares them to each other, resulting in a value of true (1) or false (0).

The if else statement:


if(expression) { Statement 1; statement2; } else { Statement 3; Statement 4; } If expression is true then statement 1,2 will be executed otherwise statement 3,4 will be executed.

Sample Program:
#include<stdio.h> int main() { printf(enter a number); scanf(%d,&num); if(num%2= = 0) printf(no is even); else printf(no is odd); return 0; }

The nested If else statement:


It is perfectly all right if we write an entire if-else construct within either the body of the if statement or body if the else statement.

Sample program of nested if else statement


/*demo of nested if else*/ #include<stdio.h> void main() { int i; printf(enter either 1 or 2); scanf(%d,&i); if(i= = 1) printf(u would go to heaven); else { if (i==2) printf(Hell was created with u in mind); else printf(How about mother earth); } } Exercise1: A five digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not. Exercise2: If the ages of Ram, Shayam and Ajay are input through the keyboard, write a program to determine the youngest of three. Exercise3: If cost and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred. Exercise4: Write a program to check whether a triangle is valid or not, when the three angles of triangle are entered through the keyboard. A triangle is valid if the sum of all three angles is equal to 180 gegrees.

Practical #5: Getting acquainted with repetition structures (loop).


Objective
The goal of this lab is to help you become acquainted with the various repetition structures (loop) in C.

In this lab you will learn about how to use various repetition structures (loop). in C for iterative type of the problems. There are three methods by which we can repeat a part of program. They are:. 1. Using a for statement 2. Using a while statement 3. Using do while statement 1. The for Statement: Syntax for for loop: for(initialization;condition;increment/decrement)

Sample program:
/*Print digits 0 to 9*/ #include<stdio.h> void main() { int i; for(i=0;i<10;i++) { printf(%d,i); } } 2. The while statement: The general form of the while is as shown below: Initialize loop counter; While(test loop counter using a condition) { do this; and this; increment loop counter; /*statements*/ }

Sample program:
/*Print digits 1 to 9*/ #include<stdio.h> void main() { int number=1;

while ( number <= 10) { printf(number=%d,number) ; number=number+1; } } 3. The do while statement: The do while loop looks like this: do { this; and this; and this; and this; /*statements*/ }while(condition is true);

Sample program:
/*Print digits 21 to 29*/ #include<stdio.h> void main() { int i=20; do { i++; printf(%d,i); } while(i<30); } Note:-attempt all the exercises given below by for, while and do-while statements.

Exercise 1:
Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of all digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153=(1*1*1)+(5*5*5)+(3*3*3).

Exercise 2:
Write a program to find the factorial value of any number entered through the keyboard.

Exercise 3:

Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs. 12.00 per hour for every hour worked above 40 hours. Assume that employees do not work fractional part of an hour.

Practical #6: Getting acquainted with switch statement, break statement and continue
statement.

Objective
The goal of this lab is to help you become acquainted with the case control structures in C. The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch case default, since these three keywords go together to make up the control statement. They most often appear as follows: switch (expression) { case constant1: do this; case constant2: do this; default: do this; }

Example:
#include<stdio.h> main() { int i = 2; switch (i) { case 1: printf(I am in case 1 ); case 2: printf(I am in case 2 ); case 3: printf(I am in case 3 ); default: printf(I am in default ); } } The output will be I am in case 2 I am in case 3 I am in default.

Break statement:

We often come across situation where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement
..

Example:
#include<stdio.h> main() { int i = 2; switch (i) { case 1: printf(I am in case 1\n ); break; case 2: printf(I am in case 2\n ); break; case 3: printf(I am in case 3\n ); break; default: printf(I am in default \n); } } The output will be I am in case 2

Continue Statement:
In some programming situations we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The continue statement passes control to the next iteration of the nearest enclosing do, for, or while statement in which it appears, bypassing any remaining statements in the do, for, or while statement body A continue is usually associated with an if.
.

Example:
#include<stdio.h> void main() { int i,j; for(i=1;i<=2;i++) { for(j=1;j<=2;j++) { if(i==j) continue; printf(\n%d%d\n,i,j); }

} } The output would be 1 2 2 1

Exercise 1:
Write a menu driven program which has following option: 1. Factorial of a number 2. Prime or not 3. Odd or Even 4. Exit Make use of switch statement. The outline of the program is given below: /*A menu driven program*/ main() { int choice; while(1) { printf(\n1. Factorial); printf(\n2. Prime); printf(\n3. odd/even); printf(\n4. Exit); printf(\n1. your Choice?); scanf(%d,&choice); switch(choice) { case 1: /*logic for factorial of a number*/ break; case 2: /*logic for deciding prime number*/ break; case 3: /*logic for even/odd*/ break; case 4: exit(); } } }

Exercise 2:
Write a switch statement that will examine the value of an integer variable called flag and print one of the following messages, depending on the value assigned to flag. 1. HOT, if flag has a value of 1

2. LUKE WARM, if flag has value of 2 3. COLD, if flag has value of 3 4. OUT OF RANGE, if flag has any other range

Practical #7: Getting acquainted with sequential, selection and iterative structures in c.
Objective
The goal of this lab is to help you become acquainted with the nested use of if, if-else, while, for, and do while statements.

Exercise 1:
Write a program to add first seven terms of the following series using any loop: 1/1! + 2/2! + 3/3! +..

Exercise 2:
Write a program to produce a following output: 1 2 4 7 8 5 9 3 6 10

Exercise 3:
Write a program to generate all combinations of 1, 2 and 3 using any loop.

Exercise 4:
Write a program to print the multiplication table of the number entered by the user. The table shoud get displayed in the following form: 11*1=11 11*2=22 .

Practical #8: Getting acquainted with logical operator used in c


Objective
The goal of this lab is to help you become acquainted with the logical operators like AND,OR and NOT used in c. The logical AND operator (&&) and the logical OR (||) operator evaluate the truth or falsehood of pairs of expressions. The AND operator evaluates to 1 if and only if both expressions are true. The OR

operator evaluates to 1 if either expression is true. To test whether y is greater than x and less than z, you would write (x < y) && (y < z) The logical negation operator (!) takes only one operand. If the operand is true, the result is false; if the operand is false, the result is true. The operands to the logical operators may be integers or floating-point objects. The expression 1 && -5 results in 1 because both operands are nonzero. The same is true of the expression 0.5 && -5 Logical operators (and the comma and conditional operators) are the only operators for which the order of evaluation of the operands is defined. The compiler must evaluate operands from left to right. Moreover, the compiler is guaranteed not to evaluate an operand if it is unnecessary. For example, in the expression if ((a != 0) && (b/a == 6.0)) if a equals 0, the expression (b/a == 6) will not be evaluated. This rule can have unexpected consequences when one of the expressions contains side effects. Truth Table for C's Logical Operators In C, true is equivalent to any nonzero value, and false is equivalent to 0. The following table shows the logical tables for each operator, along with the numerical equivalent. All of the operators return 1 for true and 0 for false. Table 5-10 Truth Table for C's Logical Operators Operand Operator Operand Result zero nonzero zero nonzero zero nonzero zero && && && && || || || zero zero nonzero nonzero zero zero nonzero 0 0 0 1 0 1 1

Operand nonzero

Operator Operand Result || ! nonzero zero nonzero 1 1 0

not applicable !

Examples of Expressions Using the Logical Operators The following table shows a number of examples that use relational and logical operators. The logical NOT operator has a higher precedence than the others. The AND operator has higher precedence than the OR operator. Both the logical AND and OR operators have lower precedence than the relational and arithmetic operators. Table 5-11 Examples of Expressions Using the Logical Operators Given the following declarations: int j = 0, m = 1, n = -1; float x = 2.5, y = 0.0; Expression j && m j < m && n < m m + n || ! j x * 5 && 5 || m / n j <= 10 && x >= 1 && m !x || !n || m+n x * y < j + m || n (x > y) + !j || n++ (j || m) + (x || ++n) Equivalent Expression (j) && (m) (j < m) && (n < m) (m + n) || (!j) ((x * 5) && 5) || (m / n) ((j <= 10) && (x >= 1)) && m ((!x) || (!n)) || (m+n) ((x * y) < (j + m)) || n ((x > y) + (!j)) || (n++) (j || m) + (x || (++n)) Result 0 1 1 1 1 0 1 1 2

Example:
Use of logical AND: /* Method 1: by using nested if else construct */ #include<stdio.h> void main() { int m1,m2,m3,m4,m5, per; printf(enter marks in five subjects); scanf(%d%d%d%d%d,&m1,&m,2,&m3,&m4,&m5);

per=(m1+m2+m3+m4+m5)/5; if(per>=60) printf(First Division); else { if(per>=50) printf(Second Division); else { if(per>=40) printf(Third Division); else printf(Fail); } } } /* Method 2: by logical operator */ #include<stdio.h> void main() { int m1,m2,m3,m4,m5, per; printf(enter marks in five subjects); scanf(%d%d%d%d%d,&m1,&m,2,&m3,&m4,&m5); per=(m1+m2+m3+m4+m5)/5; if(per>=60) printf(First Division); if(per>=50)&&(per<60) printf(Second Division); if(per>=40)&&(per<50) printf(Third Division); if(per<40) printf(Fail); }

Use of logical OR: #include<stdio.h> void main() { int i=4,z=12; if(i=5||z>50) printf(\nDean of Student Affairs);

else printf(\nDOSA); } Use of logical NOT: #include<stdio.h> void main() { int i=-1,j=1,k,l; k=!i&&j; l=!i||j printf(%d%d,k,l); }

Exercise 1:
Any character is entered through the keyboard write a program to determine whether the character entered is a capital letter, a small letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters. Characters ASCII Values A-Z 65-90 a-z 97-122 0-9 48-57 Special symbols 0-47,58-64,91-96,123-127

Exercise 2:
A library charges a fine for every book returned late. For first five days the fine is 50 paise, for 6 to 10 days fine is one rupee, and above 10 days fine is five rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the member is late to return the book and display the fine or the appropriate message.

Exercise 3:
The policy followed by a company to process customer orders is given by following rules: (a) if a customer order quantity is less than or equal to that in stock and his credit is ok, supply his requirement. (b) If credit is not ok , do not supply. Send him intimation. (c) If his credit is ok but the item in stock is less than his order, supply what is in stock. Intimate to him the date on which the balance will be shipped. Write c program to implement the company policy.

Practical #9: Getting acquainted with nested use of sequential, selection and iterative
structures in c.

Objective

The goal of this lab is to help you become acquainted with the nested use of if, if-else, while, for, and do while statements.

Exercise No.1:
Suppose that P dollars are borrowed from bank, with the understanding that A dollars will be repaid each month until the entire loan has been repaid. Part of the monthly payment will be interest, calculated as I percent of the current unpaid balance. The reminder of the monthly payment will be applied toward reducing the unpaid balance. Write a C program that will determine the following information: (i) The amount of interest paid each month. (ii) The amount of money applied toward the unpaid balance each month. (iii) The commutative amount of interest that has been paid at the end of each month. (iv) The amount of loan that is still unpaid at the end of each month. (v) The number of monthly payments required to repay the entire loan. (vi) The amount of last payment (since it will probably be less than A). Test your program using the following data: P=Rs.40000; A=Rs.2000; i=1% per month.

Exercise No.2:
Generate the following pyramid of digits, using nested loops. 1 232 34543 4567654 567898765 6 7 8 9 10 9 8 7 6 7 8 9 10 11 10 9 8 7 8 9 10 11 12 11 10 9 8 9 10 11 12 13 12 11 10 9 10 11 12 13 14 13 12 11 10 Do not simply write out 10 multidigit strings. Instead, develop a formula to generate the appropriate output for each line.

Exercise No.3:
The natural logarithm can be approximated by the following series. (x-1)/x + ((x-1)/x))2 + ((x-1)/x))3 + ((x-1)/x))4 + ((x-1)/x))5 +.. if x is input through the keyboard, write a program to calculate the sum of first seven terms of this series.

Practical #10: Getting acquainted with nested use of sequential, selection and iterative
structures in c.

Objective
The goal of this lab is to help you become acquainted with the nested use of if, if-else, while, for, and do while statements.

Exercise No.1:
Write a program to display the series of numbers as given below: 1 12 123 1234 4321 321 21 1

Exercise No.2:
Read an integer through the keyboard. Sort odd and even numbers by using while loop. Write a program to add sum of odd & even numbers separately and display the results. Eg. Enter no.=10 ODD EVEN 1 2 3 4 5 6 7 8 9 10 --------------------25 30

Exercise No.3:
Write a program to provide multiple functions such as 1. addition 2. subtraction 3. multiplication 4. division. 5. remainder. 6. larger out of two by using switch() statements.

Practical #11: Getting acquainted with nested use of sequential, selection and iterative
structures in c.

Objective
The goal of this lab is to help you become acquainted with the nested use of if, if-else, while, for, and do while statements. Exercise No.1:

Write a function that outputs a sideways triangle of height 2n-1 and width n, so the output for n = 4 would be:
* ** *** **** *** ** *

Exercise No.2: A cloth show room has announced the following seasonal discounts on purchase of items: Purchase Discount account Mill cloth Handloom Items 0-100 5% 101-200 5% 7.5% 201-300 7.5% 10% Above 300 10% 15% Write a program using switch and if statements to compute the net amount to be paid by a customer. Exercise No.3: Write a programs to print the following outputs using for loops; (a) 1 22 333 4444 55555 (b) 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Practical #12: Getting acquainted with functions in c


Objective
The goal of this lab is to help you become acquainted with the functions and modular programming in c. A complex program is often easier to solve by dividing it into several smaller parts, each of it can be solved by itself. This is called structured programming. These parts are sometimes made into functions in c. main() then uses these functions to solve the original problem.

Functions have a basic structure. Their format is:


return_data_type function name (data type variable name, data type variable name,.) { function body } This permits type checking by utilizing function prototypes to inform the compiler of the type and number of parameters a function accepts. When calling a function, this information is used to perform the type and parameter checking. ANSI C also requires that the return_ data_type for a function which does not return data must my of type void. The default return_ data_type is assumed to be an integer unless otherwise specified, but must match that which the function declaration specifies. A simple function is: void print_message () { printf(This is a module called print_message.\n); } Note the function name is print_message. No arguments are accepted by the function, this is indicated by the keyword void in accepted parameter section of function declaration. The return_data_type is void, this data is not returned by the function. An ANSI C function prototype for print_message() is: void print_message (); Function prototypes are listed at the beginning of the source file. Often, they might be placed in a users .h (header) file.

Functions
Now lets incorporate this function into a program. /* Program illustrating a simple function call */ #include <stdio.h> void print_message (void); /* ANSI C function prototype */

void print_message (void) { } int main() { print_message(); return 0; }

/* the function code */

printf(This is a module called print_message.\n);

Sample program:
/* Simple multiply program using argument passing */ #include <stdio.h> int calc_result (int, int) // ANSI function prototype { auto int result; result = numb1 * numb2; return result; } int main(void) { int digit1 = 10, digit2 = 30, answer = 0; answer = calc_result(digit1, digit2); printf(%d multiplied by %d is %d\n, digit1, digit2, answer); return 0; } Sample program output 10 multiplied by 30 is 300

Examples of function declarations, definitions, and use:

#include <stdio.h> /* Examples of declarations of functions */ void square1(void); /* Example of a function without input parameters and without return value */ void square2(int i); /* Example of a function with one input parameter and without return value */ int square3(void); /* Example of a function without input parameters and with integer return value */ int square4(int i); /* Example of a function with one input parameter and with integer return value */ int area(int b, int h); /* Example of a function with two input parameters and with integer return value */ /* Main program: Using the various functions */ int main (void) { square1(); /* Calling the square1 function */ square2(7); /* Calling the square2 function using 7 as actual parameter corresponding to the formal parameter i */ printf("The value of square3() is %d\n", square3()); /* Ysing the square3 function */ printf("The value of square4(5) is %d\n", square4(5)); /* Using the square4 function with 5 as actual parameter corresponding to i */ printf("The value of area(3,7) is %d\n", area(3,7)); /* Using the area function with 3, 7 as actual parameters corresponding to b, h respectively */ } /* Definitions of the functions */ /* Function that reads from standard input an integer and prints it out together with its sum */ void square1(void){ int x; printf("Please enter an integer > "); scanf("%d", &x); printf("The square of %d is %d\n", x, x*x); } /* Function that prints i together with its sum */

void square2(int i){ printf("The square of %d is %d\n", i, i*i); } /* Function that reads from standard input an integer and returns its square */ int square3(void){ int x; printf("Please enter an integer > "); scanf("%d", &x); return (x*x); } /* Function that returns the square of i */ int square4(int i){ return (i*i); } /* Function that returns the area of the rectangle with base b and hight h */ int area(int b, int h){ return (b*h); } /* The output of this program is: Please enter an integer > 3 The square of 3 is 9 The square of 7 is 49 Please enter an integer > 4 The value of square3() is 16 The value of square4(5) is 25 The value of area(3,7) is 21 */

Exercise 1:
Write a function which receive a float and an int from main(), find the product of these two and return the product which is printed through main().

Exercise 2:
Write a function that receive five integers and calculate the sum, average and standard deviation of these numbers. Return the standard deviation. Call this function from main() and print the result in main().

Exercise 3:
A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number. For example, prime factor of 24 is 2, 2, 2 and 3 where as prime factors of 35 are 5 and 7.

Exercise 4:
Write a function to find out the roots of quadratic equation. Equation: ax2+bx+c=0 Quadratic formula: x=(-b+-(b2-4ac)1/2)/2a

Practical #13: Getting acquainted with arguments pass by value in function.


Objective
The goal of this lab is to help you become acquainted with the functions where arguments are passing by value.. Pass by value: In this type value of actual arguments are passed to the formal arguments and the operation is done on the formal arguments. Any change made in the formal argument does not effect the actual arguments because formal arguments are photocopy of actual arguments. Hence when function is called by call or by value method, it does not affect the actual contents of the actual arguments. Changes made in the formal arguments are local to the block of the function. Once control return back to the calling function the changes made vanish. The following example illustrates the use of call by value. #include<stdio.h> void change(int,int); main() { int x,y; clrscr(); printf(\nenter the value of x and y); scanf(%d%d,&x,&y); change(x,y) printf(\n in main() x=%d y=%d,x,y); return 0; } void change(int a, int b) { int k; k=a; a=b; b=k; printf(\n in change() x=%d y=%d,a,b) }

Output: Enter the value of x and y 5 4 in change() x=4 y=5 in main() x=5 y=4

Exercise 1:
A function called abs_val that returns int and takes an int argument. It returns the absolute value of its argument, by negating it if it is negative.

Exercise 2: Exercise 3:

Write a C function that takes three integers as arguments and

returns the value of the largest one


Write a C function that takes a positive integer n as an argument and returns 0 if n is prime, and 1 otherwise.

Exercise 4:
Write a function that takes a positive integer as input and returns the leading digit in its decimal representation. For example, the leading digit of 234567 is 2.

Exercise 5:
Write a function to evaluate the following series: Sum=x + x2/2! + x4/4! + x6/6! + ..xn/n!

Practical #14: Getting acquainted with arguments pass by reference in function.


Objective
The goal of this lab is to help you become acquainted with the functions where arguments are passing by reference or address. Pass by reference: In this type instead of passing values, addresses are passed. Function operates on addresses rather than values. Here formal arguments are pointer to the actual arguments. In this type formal arguments point to the actual argument. Hence changes made in the arguments are permanent. The following example illustrates the call by reference. #include<stdio.h> void change(int*,int*); main() { int x,y; clrscr();

printf(\nenter the value of x and y); scanf(%d%d,&x,&y); change(&x,&y) printf(\n in main() x=%d y=%d,x,y); return 0; } void change(int *a, int *b) { int *k; *k=*a; *a=*b; *b=*k; printf(\n in change() x=%d y=%d,*a,*b) } Output: Enter the value of x and y 5 4 in change() x=4 y=5 in main() x=4 y=5

Exercise No.1:
Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. Call the function from main() and print the result in main().

Exercise No.2:
Write a function to find the area and perimeter of triangle, which receives the values of 3 sides of triangle as pass by value, and area and perimeter as pass by reference from main(). Calculate the area and perimeter which is printed through main().

Exercise No.3:
Write a function which receives 2 integers from main() as pass by reference, swap the values of these two and print through main().

Exercise No.4:
Write a function which receives 2 integers from main(), do addition, subtraction, multiplication and division of these two integer and print the result in main().

Practical #15: Getting acquainted with recursion.


Objective
The goal of this lab is to help you become acquainted with the use of recursion. Recursion is a ability of a function to call itself. In c it is possible for the function to call themselves. A function is called recursive if a statement with in the body of a function calls the same function.

Example: factorials 5! = 5 * 4 * 3 * 2 * 1 Notice that 5! = 5 * 4! 4! = 4 * 3! ... Can compute factorials recursively Solve base case (1! = 0! = 1) then plug in 2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6;

/*Program for calculating the factorial of a number by using recursive function*/ #include<stdio.h> #include<conio.h> int rec (int); void main() { int a, fact; printf(enter any no); scanf(%d,&a); fact=rec(a); printf(%d, fact); } rec(int x) { int f; if(x==1) return(1); else f=x*rec(x-1); return(f); } Recursion Vs. Iteration: Repetition Iteration: explicit loop Recursion: repeated function calls Termination Iteration: loop condition fails Recursion: base case recognized Balance Choice between performance (iteration) and good software engineering (recursion)

Exercise No1. Write a recursive function to obtain the first 25 numbers of a Fibonacci series. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 . Exercise No2. Write a recursive function to obtain the running sum of first 25 natural numbers. Exercise No3 A positive integer is entered through the keyboard; write a recursive function to obtain the prime factors of that integer. Exercise No4 Write a program to calculate result of following with recursive calls of a function. X=2+4+6+8..n X=1/1!+2/2!+3/3!+n/n!. Exercise No5 A five digit positive integer is entered through the keyboard, write a recursive function to calculate the sum of digits of 5 digit number.

Practical #16: Getting acquainted with Arrays.


Objective
The goal of this lab is to help you become acquainted with the manipulation of arrays.. An array is linear data structure, which is used to store similar type of data items.

Array Declaration:
To declare an array, you need: type (what sort of values will it hold?) size (how many values will it hold?) name int myArray[20];

Array Initialization:
Arrays can be initialized by a list of constant values double vector[3] = {0.0, 1.0, 2.0}; double matrix[3][2] = { {0.0, 1.0}, {1.0, 2.0}, {2.0, 3.0} }; The number of elements in an array can be inferred by the compiler from the number of initializing constants int myvector[] = {0,1,2,3,4,5,6}; //a 7-element array

Static arrays are initialized when the program is loaded, and are initialized to zero by default. Automatic arrays are initialized when they are defined, and do not have a default initial value (unless they are arrays of objects). Arrays may be initialized when they are declared: int myArray[5] = {3,5,9,32,8}; float floatArray[10] = {6,30,42,58,0, 1,3,4,2,0}; Or you can initialize them in a loop: int myArray[size]; for (i=0;i<size;i++) { myArray[i]=0; }

Arrays and I/O:


scanf and printf can't handle arrays themselves So we write I/O for arrays explicitly, usually using a loop: /* read in values for an array */ for (i=0;i<arraySize;i++) { scanf("%f",&floatArray[i]); } /* Print out all the elements of an array, one to a line */ for (i=0;i<arraySize;i++) { printf("%f\n",floatArray[i]); } /* Print out all the elements of an array */ for (i=0;i<arraySize;i++) { printf("number %d is %f\n",i,floatArray[i]); }

Sample Ptrogram:

#include<stdio.h> main() { int x[5]={10,20,30}; printf("\n%d", x[0]); printf("\n%d", x[1]); printf("\n%d", x[2]); printf("\n%d", x[3]); printf("\n%d", x[4]); } Output: 10 20 30 0 0 #include<stdio.h> main() { int x[]={10,20,30}; printf("\n%d", x[0]); printf("\n%d", x[1]); printf("\n%d", x[2]); printf("\n%d", x[3]); printf("\n%d", x[4]); } Output: 10 20 30 8817 8339

Two Dimensional Arrays:


Two dimensional array is also called matrix. Here is sample program that stores rooll no. and marks obtained by a student side by side in a matrix. Main() { int stud[4][2];

int I,j; for(i=0;i<=3;i++) { printf(\n enter roll no and marke); scanf(%d%d,&stud[i][0],&stud[i][1]); } for(i=0;i<=3;i++) { printf(%d%d,stud[i][0],stud[i][1]); }

Initialization of two dimensional Array:


Int stud[4][2]={ {1234,45}, {1212,33}, {1413,69}, {1312,68} }; or int stud[4][2]={1234,45,1212,33,1413,69, 1312,68}; or Int arr[][3]={12,34,56,56,56,57}; this would never work Int arr[2][]={12,34,56,56,56,57}; Int arr[][]={12,34,56,56,56,57};

Passing array elements to a function:


Array element can be passed to a function by calling the function by value, or by reference. /*demonstration of call by value*/ Main() { int i; int marks[]={55,65,75,56,78,79,90}; for(i=0;i<=6;i++) display(marks[i]); } Display (int m) { printf(%d,m);

/*Demostration of call by reference*/ Main() { int i; int marks[]={55,65,75,56,78,79,90}; for(i=0;i<=6;i++) disp(&marks[i]); } Disp(int *m) { printf(%d,*m); } Here we are passing address of individual array elements to the function.

Passing an entire array to a function:


Main() { int num[]={23,34,34,56,45,67}; display(&num[0],6); } Display(int *j,intn) { int I; for(i=0;i<=n-1;i++) { printf(\nelement=%d,*j); j++; } } (One Dimensional Array exercises only) Exercise No.1 Write a program for sorting the elements of an array in descending order. Exercise No.2 Write a program using an array to evaluate the following expression
i=10

Total=x2
i=1

the values of x1, x2,..are read from the terminal. Exercise No.3 Write a program to store 10 elements into an array, find out the maximum and minimum element from the array. Exercise No.4 Write a program to find out the duplicate elements in an array if any.

Practical #17: Getting acquainted with Arrays.


Objective
The goal of this lab is to help you become acquainted with the manipulation of arrays. An array is linear data structure, which is used to store similar type of data items.

Two Dimensional Arrays:


The dimensional array is also called matrix. Sample program that store all roll number and marks obtained by a student side by side in a matrix.

Inputting and outputting:


main() { int stud[4][2]; int I,j; for(i=0;i<=3;i++) { printf(\n enter roll no. and marks); scanf(%d%d,&stud[i][0],&stud[i][1]) } for(i=0;i<=3;i++) { printf(\n%d%d,&stud[i][0],&stud[i][1]) } There are two parts to the program- in the first part through a for loop we read in the values of roll no and marks where as in the second part through another for loop we print out these values.

Initialization of 2 D array:
Int stud[4][2]={ { 1234,56}, { 1212,33}, {1234,80}, {1345,78} }; or Int stud[4][2]={ 1234,56,1212,33,1234,80,1345,78}; * but loss in readability.

Exercise No1:

Write a program to display two dimensional array elements together with their addresses. Eg. Array elements and addresses Col 0 col 1 col 2 Row 0 1 [4052] 2 [4054] 3 [4056] Row 1 4 [4058] 5 [4060] 6 [4062] Row 3 7 [4064] 8 [4066] 9 [4068]

Exercise No2:
Write a program to display the balance and code no. in two separate columns. Indicate the number of columns, which are having the balance less than 1000. Eg; Enter code no. and balance 1 900 2 800 3 1200 4 550 5 600 your entered data: 6 900 7 800 8 1200 9 550 10 600 balance less than 1000 are 4

Exercise No3:
Write a program to initialize single and two dimensional arrays. Accept three elements in single dimensional array. Using the elements of this array compute addition, square and cube. Display the results in two dimensional array. Output: Number addition square cube 5 10 25 125 6 12 36 216 7 14 49 343

Exercise No4:
Read the matrix of the order up to 10X10 elements and display the same in the matrix form.

Exercise No5:
Read the matrix of the order up to 10X10, and transpose its elements.

Practical #18: Getting acquainted with Arrays.


Objective
The goal of this lab is to help you become acquainted with the manipulation of arrays.

An array is linear data structure, which is used to store similar type of data items.

Two Dimensional Arrays:


The dimensional array is also called matrix. Sample program that store all roll number and marks obtained by a student side by side in a matrix.

Inputting and outputting:


main() { int stud[4][2]; int I,j; for(i=0;i<=3;i++) { printf(\n enter roll no. and marks); scanf(%d%d,&stud[i][0],&stud[i][1]) } for(i=0;i<=3;i++) { printf(\n%d%d,&stud[i][0],&stud[i][1]) } There are two parts to the program- in the first part through a for loop we read in the values of roll no and marks where as in the second part through another for loop we print out these values.

Initialization of 2 D array:
Int stud[4][2]={ { 1234,56}, { 1212,33}, {1234,80}, {1345,78} }; or Int stud[4][2]={ 1234,56,1212,33,1234,80,1345,78}; * but loss in readability.

Exercise No1:
Write a program to perform addition and subtraction of two matrices whose orders are up to 10X10.

o/p: a

458 298 294 addition 5 8 13 2 13 12 8 16 6 subtraction 323 244 -4 2 2

135 054 572

Exercise No2:
Write a program to perform multiplication of corresponding elements two matrices whose orders are up to 10X10. o/p: a b 458 135 298 054 294 572 Multiplication 4 15 40 0 45 32 12 63 8

Exercise No3:
Write a program to display the different parameters of 10 men in a table. The different parameters are to be entered are age and weight. Find the number of men who satisfy the following condition. (A) age should be greater than 18 and less than 25 (B) Weight should be In between 45 to 60.

Exercise No4:
Write a program to read the quantity & price of various Pentium models using an array. Compute the total cost of all models. O/P: Enter qty. and price of the Pentium1: 25 25000 Enter qty. and price of the Pentium2: 20 40000 Enter qty. and price of the Pentium3: 15 35000 Enter qty. and price of the Pentium4: 20 40000 Model Pentium1 Pentium2 Pentium3 Pentium4 Qty 25 25 25 25 Rate(Rs.) 25000 30000 35000 40000 Total value 625000 600000 525000 800000

Grand total Rs.2550000

Practical #19: Getting acquainted with strings.


Objective
The goal of this lab is to help you become acquainted with the manipulation of strings.

What are Strings:


sequence of characters is called string. Each character in the array occupies one byte of memory and the last character is always \0 This is NULL character. ASCII value of this is 0 Elements of the character array are stored in contiguous memory locations. The terminating NULL is important by using this string function knows end of string.

Initializing strings:
Char name[]=HAESLER; /*printing of string*/ Main() { char name[]=klinsman; int i=0; while(i<=7) { printf(%c,name[i]); i++; } }

More about Strings:


/*printing of string without final value 7*/ Main() { char name[]=klinsman; int i=0; while(name[i]!=\0) { printf(%c,name[i]); i++; } } /*printing of string using pointer */ Main() {

char name[]=klinsman; char *ptr; ptr=name; /*store the base address of string*/ while(*ptr!=\0) { printf(%c,*ptr); ptr++; } }

Inputting and outputting strings:


/*inputting and outputting of single word string*/ main() { char name[25]; printf(enter your name); scanf(%s,name); printf(Hello %s,name); } o/p: Enter your name Devashish Hello Devashish /*inputting of multi word string using scanf*/ main() { char name[25]; printf(enter your name); scanf(%[^\n]s,name); } /*inputting and outputting of multi word string*/ main() { char name[25]; printf(enter your name); gets(name); puts(Hello); puts(name); } o/p: Enter your name Devashishn Roy Hello Devashish Roy

Pointers and strings:

char str[]=Hello; char *p=Hello;

Hello is stored as a string Stored in any memory location and assign the address of the string in a character pointer The difference of these two is that we can not assign a string to another, whereas, we can assign a char pointer to another char pointer main() { char str1[]=hello; char str2[10]; char *s=good morning; char *q; str2=str1; /*error*/ q=s; /*works*/ } Once a string has been defined it can not be initialized to another set of characters. Unlike strings, such an operation is perfectly valid with char pointer. main() { char str1[]=hello; char *p=hello; str1=bye; /*error*/ p=bye; /*works*/ }

Standard Library string functions:


Function strlen strcpy strncpy strcmp strncmp strcat strncat strlwr Use Finds length of a string Copies a string into another Copies first n characters of a string into another Compare two strings Compare first n characters of two strings Append one string at the end of another Append first n characters of a string at the end of another Converts a string to lowercase

strupr

Converts a string to uppercase

Exercise1:
Write a function that copies first n characters of a string.

Exercise2:
Write a function that concatenates first n character of a string to another string.

Exercise3:
Write a function that concatenates first n characters of two strings.

Exercise4:
Write a function that replaces all occurrences of a given character by another character.

Exercise5:
Write a program to find the reverse of a string recursively. (eg. JAYPEE---EEPYAJ).

Exercise6:
Write a program to find whether the string is palindrome or not. (eg. TIT is palindrome)

Practical #20: Getting acquainted with strings.


Objective
The goal of this lab is to help you become acquainted with the manipulation of strings.

Exercise1:
Write a program to sort a set of names stored in an array in alphabetical order.

Exercise2:
Write a program to delete all vowels from sentence, assume that sentence is not more than 80 character long.

Exercise3:
Write a program that will read a line and delete from it all occurrences of the word the.

Exercise4:
Write a program that takes a set of names of individuals and abbreviates the first, middle and other names except the last name by their first letters. Eg. Sachin Ramesh Tendulkar------------S R Tendulkar

Exercise5:
Write a program to count the no. of occurrences of any two vowels in succession in a line of text Eg. Please read this application and give me gratuity --------ea .ea io ui

Practical #21: Getting acquainted with structures.


Objective

The goal of this lab is to help you become acquainted with the structures and unions, which is collection of various types of data elements called members.

What is structure in C?
A structure is a group of items in which each item is identified by its own identifier, each of which is known as the member of structure. struct{ char first[10]; char midinit; char last[20]; } sname,ename; ename, sname are structure variables

or
Struct nametype{ char first[10]; char midinit; char last[20]; }; struct nametype sname, ename; We can assign a tag to the structure and declare the variables by means of the tag

Declaring structure using typedef:


Often, typedef is used in combination with struct to declare a synonym (or an alias) for a structure typedef struct /* Define a structure */ { char first[10]; char midinit; char last[20]; } NAMETYPE ; /* The "alias" */

NAMETYPE sname,ename /* Create a struct variable */

Examples:
struct card { int pips; char suit; } ; struct card c1, c2; Variables may also be declared in the structure definition:

struct card { int pips; char suit; } c1, c2 ; Initialisation of structures: (similar to arrays card c3 = {13,h}; /* the king of hearts */ Assignment of structures: c2 = c1; assigns to each member of c2 the value of the corresponding member of c1. Arrays of structures: card deck[52]; declares an array (of size 52) of variables of type card; the name of the array is deck. Accessing members of a structure: c1.pips = 3; c1.suit = s; members of the structure are accessed with the operator . (dot),

Inputting and outputting:


#include<stdio.h> int main() { struct student { int rollno; char name[10]; int marks; }stud1,stud2; printf("enter data for first student"); scanf("%d %s %d",&stud1.rollno,&stud1.name,&stud1.marks); printf("\n %d %s %d",stud1.rollno,stud1.name,stud1.marks); printf("enter data for second student"); scanf("%d %s %d",&stud2.rollno,&stud2.name,&stud2.marks); printf("\n %d %s %d",stud2.rollno,stud2.name,stud2.marks); }

Array of structure i/o:


#include<stdio.h> int main() { struct student { int rollno; char name[10]; int marks; }stud[5]; int i; for(i=0;i<=4;i++) { printf("enter data for student %d,i+1"); scanf("%d %s %d",&stud[i].rollno,&stud[i].name,&stud[i].marks); } for(i=0;i<=4;i++) { printf("data for student %d,i+1); printf("\n %d %s %d",stud[i].rollno,stud[i].name,stud[i].marks); } }

Structure as a member of any other structure i/o:


#include<stdio.h> int main() { struct marks { int phy; int chem; int maths; }; struct student { int rollno; char name[10]; struct marks m; }stud[3];

int i,sum=0,sum1=0,sum2=0; for(i=0;i<=2;i++) { printf("enter data for student"); scanf("%d %s",&stud[i].rollno,stud[i].name); printf("marks in physics, chemistry and maths"); scanf("%d %d %d",&stud[i].m.phy,&stud[i].m.chem,&stud[i].m.maths); } for(i=0;i<=2;i++) { printf("\n %d %s %d %d %d ,stud[i].rollno,stud[i].name,stud[i].m.phy,stud[i].m.chem,stud[i].m.maths); } for(i=0;i<=2;i++) { sum=sum+stud[i].m.phy; sum1=sum1+stud[i].m.phy; sum2=sum2+stud[i].m.phy; } printf("\n sum of marks of physics : %d",sum); printf("\n sum of marks of chemistry : %d",sum1); printf("\n sum of marks of maths : %d",sum2); }

Pointers to structures
Structures may contain large amounts of data Use pointers to pass structures to functions instead of moving them in memory If a function should modify the contents of a structure: Use pointers to pass structures to functions instead of passing the structure by value. Pointers to structures struct student *p=&tmp; Accessing a member with a dereferenced pointer use brackets, because . has higher priority than * (*p).grade; This is so important that an equivalent syntax is provided (saving two keystrokes) p->grade;

Updating structures in functions: method 1


Send structure e down to the function, modify it, and return the modified structure for use in the calling routine: e = update1(e); .....
Within calling routine, e.g. function main()

employee_data update1(employee_data e) { .... printf (Input the department number: ); scanf(%d, &n); /* now access member of struct-within-struct... */ e.department.dept_no = n; ..... return e; } This involves a lot of copying of structure members down to the function and back again. Theres a better way...

Updating structures in functions: method 2


Passing a pointer to a structure is more efficient: update2(&e);
Within calling routine (e.g. function main() ), to pass address to update function

void update2(employee_data *p) { .... printf(Input the department number: scanf(%d, &n); p->department.dept_no = n; ..... }

);

Use -> instead of . to access structure member, because p is a pointer to the structure

Self Referential Structures:


It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type. In general terms, this can be expressed as struct tag { member 1; member 2; . struct tag *name; }; Where name refers to the name of a pointer variable. Thus the structure of type tag will contain a member that points another structure of type tag. Such structure are known as self referential structures. Struct list_element { char item[40]; struct list_element *next; }; This is a structure of type list element. The structure contains two members: a 40 element character array, called item, and pointer to a structure of the same type called next. Therefore this is a self referential structure.

Exercise No1:
Create a structure to specify data on students given below:

Roll number, Name, Department, Course, Year of joining Assume that there are not more than 250 students in the college. (a) Write a function to print names of all students who joined in a particular year. (b) Write a function to print data of a student whose roll number is given.

Exercise No2:
Create a structure to specify data of customers in a bank. The data to be stored is : Account number, Balance in account. Assume maximum of 200 customers in the bank.. (a) Write a function to print the account number and name of each customer with balance below Rs. 100. (b) If a customer requests for withdrawal or deposit, it is given in the form: Account number, amount, code(1 for deposit, 0 for withdrawal) Write a program to give a message, the balance is insufficient for the specified withdrawal.

Exercise No3:
Create a structure named employee that hold information like empcode, name and date of joining. Write a program to create an array of structures and enter some data into it. Then ask the user to enter current date. Display the name of those employee whose tenure is 3 or more than 3 years according to the current date.

Exercise No4:
Write a menu driven program that depicts the working of a library. The menu option would be: 1. Add book information 2. Display book information 3. List all book of given author 4. List the title of specified book 5. List the count of book in the library 6. list the books in the order of accession number 7. exit Create a structure called library to hold accession number, title of the book, author name, price of the book and flag indicating whether book is issued or not.

Practical #21: Getting acquainted with File (data file) handling.


Objective
The goal of this lab is to help you become acquainted with the data file which include creation, opening modifying and closing of file.

File Operations:
a. b. c. d. e. f. Creation of a new file Opening an existing Reading from a file Writing to a file Moving to a specific location in a file Closing a file

Read a file, display its contents on the screen:


/*display contents of a file on screen */ #include<stdio.h> Void main() { FILE *fp; Char ch; Fp=fopen(pr1.c,r); While(1) { Ch=fgetc(fp); If(ch==EOF) Break; Printf(%c,ch); } Fclose(fp); }

Opening a file:
fopen() performs three important tasks then: a. It searches on the disk the file to be opened. b. Then it loads the file from the disk into a place in memory called buffer. c. It sets up character pointer that points to the first character of the buffer. d.

Reading from file:


To read files contents from memory, there existing a function called fgetc() Ch=fgetc(fp); Fgetc() do: reads the character from the current pointer position Advances the pointer position so it points to the next character. Return the character that it reads, which we collected in the variable ch. We have used fgetc() inside indefinite while loop, we use break statement to come out of it as we reaches end of the file at the end of the file special character EOF is inserted beyond the last character of the file.

Closing a file:
when we have finished reading from the file,we need to close it. This is done using the function fclose() through the statement fclose(fp); When we close the file using fclose(): a. The characters in the buffer would be written to the file on the disk. b. At the end of the file a character with ASCII value 26 (EOF) would get written c. The buffer would be eliminated from memory

Counting characters, tabs, spaces

#include<stdio.h> Void main() { FILE *fp; Char ch; Int nol=0,not=0,nob=0,noc=0; Fp=fopen(pr.c,r); While(1) { Ch=fgetc(fp); If(ch==EOF) Break; Noc++; If(ch== ) Nob++; If(ch==\n) Nol++; If(ch==\t) Not++; } Fclose(fp); Printf(\n number of characters=%d,noc); Printf(\n number of blanks=%d,nob); Printf(\n number of tabs=%d,not); Printf(\n number of lines=%d,nol); }

A file copy program


#include<stdio.h> Void main() { FILE *fp *ft; Char ch; Fp=fopen(pr.c,r); If(fs==NULL) { puts(cannot open source file); exit(1); } Ft=fopen(pr1.c,w); If(ft==NULL) { puts(cannot open target file); fclose(fs); Exit(2); } While(1)

{ Ch=fgetc(fs); If(ch==EOF) Break; Else Fputc(ch,ft); } Fclose(fs); Fclose(ft); }

Writing into a file:


Fputc() function is similar to putchar(), However putch() always write to the VDU but fputc() write to the file.

File opening modes:


Mode r w a r+ Function Reading from the file Writing to the file Adding new content at the end of the file Reading existing contents, writing new contents, modifying existing contents of the file.

w+

Writing new contents, reading them back and modifying existing contents of the file. Reading existing contents, appending new contents to the end of file. Cannot modify existing contents.

a+

String (line) I/O in files:


/*receives strings from keyboard and write them to file*/ #include<stdio.h> Void main() { FILE *fp; Char s[80];

Fp=fopen(poem.txt,w); If(fp==NULL) { puts(cannot open file); exit(1); } Printf(\nenter a few line of text); While(strlen(get(s))>0) { fputs(s,fp); fputs(\n,fp); } Fclose(fp); }

Record I/O in files:


/*writes records to a file using structures*/ #include<stdio.h> Void main() { FILE *fp; Char another=Y; Struct emp { char name[40]; int age; float bs; }; Struct emp e; Fp=fopen(EMPLOYEE.DAT,w); If(fp=NULL) { puts(cannot open file); exit(1); } While(another==Y); { printf(\n enter name ,age,salary); scanf(%s,%d,%f,e.name,&e.age,&e.bs); fprintf(fp,%s,%d,%f\n,e.name,e.age,e.bs); printf(add another record(Y/N); fflush(stdin); another=getche(); } Fclose(fp);

A menu driven program for elementary database management:


#includwe<stdio.h> Void main() { FILE *fp,*ft; Char another, choice; Struct emp { char name[40]; int age; float bs; }; Struct emp e; Char empname[40]; Long int recize; fp=fopen(EMP.DAT,rb+); If(fp=NULL) { fp=fopen(EMP.DAT,wb+); if(fp==NULL) { puts(cannot open file); exit(); } } recize=sizeof(e); While(1) { clrscr(); gotoxy(30,10); printf(1. Add Records); gotoxy(30,12); printf(2. List Records); gotoxy(30,14); printf(3. Modify Records); gotoxy(30,16); printf(4. Delete Records); gotoxy(30,18); printf(0. Exit); gotoxy(30,20); printf(Your Choice); fflush(stdin); choice=getche();

Switch(choice) { case 1: fseek(fp,0,SEEK_END); another=Y; while(another==Y) { printf(\n enter name ,age,salary); scanf(%s,%d,%f,e.name,&e.age,&e.bs); fwrite(&e,sizeof(e),1,fp); printf(add another record(Y/N); fflush(stdin); another=getche(); } break Case 2: rewind(fp); while(fread(&e,resize,1,fp)==1) printf(\n%s%d%f,e.name,e.age,e.bs); Break; Case 3: Another=Y; While(another==Y) { printf(\nenter name of employee to modify); scanf(%s,empname); rewind(fp); while(fread(&e,resize,1,fp)==1) { if(strcmp(e.name,empname)==0) { printf(\nenter new name age , bs); scanf(%s%d%f,e.name,&e,age,&e.bs); fsee(fp,-resize,SEEK_CUR); fwrite(&e,resize,1,fp); break; } } printf(MODIFY another record(Y/N); fflush(stdin); another=getche(); } Break; Case 4: Another=Y;

While(another==Y) { printf(\nenter name of employee to delete); scanf(%s,empname); rewind(fp); while(fread(&e,resize,1,fp)==1) { if(strcmp(e.name,empname)!=0) { fwrite(&e,resize,1,ft); } fclose(fp); fclose(ft); remove(EMP.DAT); rename(TEMP>DAT,EMP.DAT); fp=fopen(EMP.DAT,rb+); printf(Delete another record(Y/N); fflush(stdin); another=getche(); } break; Case 0: fclose(fp); exit(); } } }

Few important functions:


rewind(): this palces the pointer to the beginning of file, irrespective of where it is present right now. fseek():this moves the pointer from one record to another fseek(fp,-resize,SEEK_CUR); resize moves the pointer back by resize bytes from the current position SEEK_CUR is macro defined in stdio.h, moves the pointer with reference to its current position. SEE_END moves the pointer from the end of the file. Ftell(): if we wish to know where pointer is positioned right now, we can use the function ftell() position=ftell(fp);

Exercise No1:
Write a program to read a file and display its contents along with line numbers before each line.

Exercise No2:
Write a program to find the size of a text file with/without traversing it character by character.

Exercise No3:
Write a program to append the contents of one file at the end of other file.

Exercise No4:

Suppose file contains students records with each record containing name and age of a student. Write a program to read these records and display them in sorted order by name.

Exercise No5:
Write a program to copy one file to another file. While doing so replace all lower case characters to their equivalent uppercase characters.

Exercise No6:
Write a program that merges lines alternately from two files and write the result to new file. If one file has less number of lines then the other, the remaining lines from the larger file should be simply copied into the target file.

Practical #22: Getting acquainted with command line argument.


Objective
The goal of this lab is to help you become acquainted with the command line argument, argc and argv.

What is command line argument?


It is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process. If we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE then we may use a command line like C>PROGRAM X_FILE Y_FILE Where PROGRAM is the file name where the executable code of the program is stored. This eliminate the need for the program to request the user to enter the file names during execution Main(). These parentheses may contain special arguments that allow parameters to be passed to main from the operating system. Most version of C permits two such arguments, which are traditionally called argc and argv, respectively. argc must be an integer variable argv is an array of pointers to characters i.e. an array of strings. Each string in this array will represent a parameter that is passed to main. The value of argc will indicate the number of parameters passed.

How argc and argv defined in main()


void main(int argc, char *argv[]) { }

Example:

#include<stdio.h> void main(int argc, char *argv[]) { int count; printf(argc=%d\n,argc); for(count=0;count<argc;++count) printf(argv[%d]=%s\n,count,argv[count]); } This program allows an unspecified number of parameters to be entered from the command line. When the program is executed, the current value of argc and the elements of argv will be displayed as separate line of output. Suppose for example, that the program name is sample, and the command line initiating the program execution is sample red white blue Then the program will be executed, resulting in the following output. argc=4 argv[0]= sample.exe argv[1]= red argv[2]= white argv[3]= blue

Using argc and argv:


To execute the file copy programs that we saw earlier, we are required to first type the program, compile it and then execute it. This program can be improved in two ways; (a) There should be no need to compile the program every time to use the file copy utility. It means the file must be executable at command prompt (A>,C>,$) (b) Instead of the program prompting us to enter the source and target filenames, we must be able to supply them at command prompt, in the form: filecopy pr1.c pr2.c Where pr1.c is the source file name and pr2.c is the target filename.

Passing source filename and target filename to the function main()


#include stdio.h main(int argc, char *argv[]) { FILE *fs,*ft; char ch; if(arg!=3) { puts(improper no of arguments); exit(); } fs=fopen(argv[1],r); if(fs==NULL) { puts(cannot open the source file); exit();

} ft=fopen(argv[2],w); if(ft==NULL) { puts(cannot open the target file); fclose(fs); exit(); } while(1) { ch=fgetc(fs); if(ch==EOF) break; else fputc(ch,ft); } fclose(fs); fclose(ft); }

ExerciseNo.1:
Write a program using command line arguments to search for a word in a file and replace it with the specified word. The usage of the program is shown below, c>change<old word><new word><filename>

ExerciseNo.2:
Write a program that can be used at command prompt as a calculating utility. The usage of program is shown below, c> calc<switch><n><m> where n and m are two integer operands, switch can be any one of the arithmetic or comparison operators. If arithmetic operator is supplied, the output should be the result of the operation. If comparison operator is supplied then the output should be true or false.

You might also like