Beruflich Dokumente
Kultur Dokumente
Title: Course Code: Course Credits: Branch and Semester: Session: Faculty Coordinator(s): Course Outline: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. Topics Introduction to Computers, the Internet and the World Web Wide Bits, Data Types and Operations The von Neumann Model Introduction to C programming Structured Program Development in C Flowchart and Algorithm C Program Control C Functions C Arrays C Pointers C Characters and Strings C Formatted Input/Output C Structures, Unions, Bit Manipulations and Enumerations C File Processing Total Hours: No. of Lab Hours 2 4
2
Computer Programming Lab 10B17CI171 5 (L=3, T=1, P=4) 1ST Semester [ECE, CSE, ICT, BIO, CIV] Jul Dec, 2013 Dr. Hemraj Saini, Dr. Nitin Rakesh, Dr. Pooja & Mr.Shailesh Tiwatri
2 2 4 4 4 4 6 6 2 4 4 50
Evaluation Scheme: 1. 2. 3. 4. Mid Term Exam (Viva and Written Exam) End term Exam (Viva and Written Exam) Lab Records Regular Assessment (Quality and quantity of experiment performed, Learning laboratory skills) 5. Attendance and discipline in lab 20 20 15
30 15
Total
100
1|Page
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.
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.
3|Page
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 4|Page
%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
5|Page
%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? 6|Page
2. Input and output your Rollno., marks, and percentage to an appropriate format.
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; }
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;
7|Page
Atoms = 2500000; }
Modifiers
The three data types above have the following modifiers.
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
8|Page
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. Assume that all integer will be read in as decimal quantities. (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
9|Page
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
Priority Operators 1st */% nd 2 +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 10 | P a g e Description Multiplication, division,modulas Addition, subtraction assignment
K=2+8-2+0 K=10-2+0 K=8+0 K=8 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.
11 | P a g e
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).
12 | P a g e
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; }
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.
14 | P a g e
Sample program:
/*Print digits 0 to 9*/ #include<stdio.h> void main() { int i; for(i=0;i<10;i++) { printf(%d,i); } }
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; } }
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. 16 | P a g e
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.
17 | P a g e
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:
18 | P a g e
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); } } 19 | P a g e
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 20 | P a g e
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 .
21 | P a g e
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
22 | P a g e
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 nonzero && && && && || || || || ! zero zero nonzero nonzero zero zero nonzero nonzero zero nonzero 0 0 0 1 0 1 1 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 Equivalent Expression (j) && (m) (j < m) && (n < m) (m + n) || (!j) ((x * 5) && 5) || (m / n) Result 0 1 1 1
j <= 10 && x >= 1 && m ((j <= 10) && (x >= 1)) && m 1 23 | P a g e
Given the following declarations: int j = 0, m = 1, n = -1; float x = 2.5, y = 0.0; Expression !x || !n || m+n x * y < j + m || n (x > y) + !j || n++ (j || m) + (x || ++n) Equivalent Expression ((!x) || (!n)) || (m+n) ((x * y) < (j + m)) || n ((x > y) + (!j)) || (n++) (j || m) + (x || (++n)) Result 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); 24 | P a g e
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:
25 | P a g e
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 26 | P a g e
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
27 | P a g e
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 28 | P a g e
(b)
55555 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
29 | P a g e
} 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); void print_message (void) { /* ANSI C function prototype */ /* the function code */
Sample program:
/* Simple multiply program using argument passing */ #include <stdio.h> int calc_result (int, int) // ANSI function prototype {
30 | P a g e
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
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); }
32 | P a g e
/* 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
33 | P a g e
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:
Write a C function that takes three integers as arguments and
Exercise 3:
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!
35 | P a g e
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().
37 | P a g e
/*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) 38 | P a g e
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.
39 | P a g e
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++) { 40 | P a g e
myArray[i]=0; }
/* 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 41 | P a g e
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
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};
/*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); 43 | P a g e
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.
44 | P a g e
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 45 | P a g e
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.
46 | P a g e
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.
47 | P a g e
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 48 | P a g e Qty 25 25 Rate(Rs.) 25000 30000 Total value 625000 600000
Pentium3 Pentium4
25 25
35000 40000
525000 800000
Initializing strings:
Char name[]=HAESLER; /*printing of string*/ Main() { char name[]=klinsman; int i=0; while(i<=7) { printf(%c,name[i]); i++; } }
char name[]=klinsman; char *ptr; ptr=name; /*store the base address of string*/ while(*ptr!=\0) { printf(%c,*ptr); ptr++; } }
/*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
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*/ }
strupr
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)
52 | P a g e
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
53 | P a g e
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
54 | P a g e
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),
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); }
56 | P a g e
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);
57 | P a g e
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...
58 | P a g e
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
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: 59 | P a g e
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.
60 | P a g e
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
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.
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
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); }
63 | P a g e
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+
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); }
65 | P a g 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) 66 | P a g e
{ 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(); } } }
67 | P a g e
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.
68 | P a g e
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. 69 | P a g e
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
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.
71 | P a g e