Computer Programming
Computer Programming
Computer Programming
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.
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.
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;
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
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
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.
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).
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; }
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); }
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 .
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
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
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 */
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
#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
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:
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!
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().
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.
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; }
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
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]); }
/*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.
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.
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.
An array is linear data structure, which is used to store similar type of data items.
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
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
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++; } }
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)
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
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
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),
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;
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...
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
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.
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.
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
#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); }
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+
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); }
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(); } } }
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.
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
} 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.