Sunteți pe pagina 1din 37

LAB MANUAL

COMPUTER PROGRAMMING -1 B.E. SEM I (EC/CL)

Prepared By, Ms. A.V.Vora, Mr. R.V. Mehta LECTURER, EC DEPT.

ELECTRONICS & COMMUNICATION DEPARTMENT FACULTY OF TECHNOLOGY DHARMSINH DESAI UNIVERSITY, NADIAD

INDEX

1. Study Of DOS Commands, Computer Hardware And Operating System 2. Simple C Programs For Error Detection And Correction 3. To Study Constant, Variable And Data Types In C 4. Basic Understanding Of Operators And Expressions-I 5. Basic Understanding Of Operators And Expressions-II. 6. Basic Understanding of Formetted Input / Output. 7. To Study Decision Making And Branching Using IFElse.. 8. To Study Decision Making And Branching Using Switch Case 9. To Study Branching Using Continue And GoTo 10.To Study Looping Using While DOWhile 11.To Study Single Dimensional Array 12.Multidimensional Array. 13.Handling of character array as a string 14.Macro as Preprocessor directive 15.User defined functions.

LAB-1 Aim: Study of DOS commands , Computer hardware and Operating System Objective:
Brief Concept Of: Serial / Parallel Device Block Diagram of a Digital Computer Operating System Command - Internal / External Booting Concept / POST DOS Environment (DOS Editor) Concept of Primary Memory & Secondary Memory

DOS Commands:
COPY Copies and combines files. SYNTAX: COPY source:\path\file(s) target:\path\file(s) / switches ->This command copies content of the source file to the target file. COPY source file(s) + source file(s)+ target:\path\file(s) / switches ->This commandcopies content of source files (in sequence) to the target file. EXAMPLE: G:\> copy st5\doc\hello.txt st6\ddit\ec.txt

->This command will copy the content of file hello.txt in doc directory to the file ec.txt in st6\ddit directory. G:\>copy star.txt + moon.txt + sun.txtuniverse.txt

-> This command will combine the content of files star.txt, moon.txt, sun.txt to the file universe.txt. # If TARGET is not specified COPY will try to copy the source files onto the currently logged drive and subdirectory. # If TARGET is a drive or directory but does not include a file name, a copy with the same name as source file is made in the target location.

SWITCHES: /Y Forces overwriting of existing files with the same name, without prompting you to confirm each overwrite. /-Y Forces DOS to prompt for confirmation for each overwriting existing file with duplicate name.

Assignments:
Make similar notes for following commands MD, RD, CD, CLS, DIR, EDIT, TYPE, DEL, UNDELETE, REN, DATE, TIME, PROMPT, COPY CON, VER, MOVE, REPLACE, XCOPY, FORMAT, MEM.

LAB-2
Aim: Simple C Programs For Error Detection And Correction
Objective: Basic Understanding of C Programing How to Enter the Program. How to Save the Program. How to Run and debug the Program.
GENERAL INSTRUCTIONS

Do the following. 1. Make a new file named FILENAME.C 2. Enter the program given below. 3. Save the file. 4. Understand the logic of the program. 5.Compile the program (Alt + F9). Check for the errors. Remove the errors (if any). And compile again. (See the message about linking process in the message window.) 6. Run the program (Ctrl + F9). 7. See the output (Alt + F5) 8. Write your comments on the program as well as errors and output PROGRAM 1 \* Program to print given message on the screen. #include <stdio.h> void main () { printf(Welcome to DDIT); getch(); } PROGRAM 2 \* Program to calculate the area of a circle. Input - Radius of the circle. Output Area of the circle. *\ *\

\* Preprocessor Directive*\ \* Main Function*\ \*Function Defination*\

#include<stdio.h>
#define pi 3.14159 void main() { int radius; float area;

\*Declaration*\
5

printf(Radius = ? ); scanf(%f, &radius); area = pi * radius * radius printf(\nArea of the circle = %f, area); } PROGRAM 3 \* Program to calculate the Net Salary. Input - Gross Salary Output - Net Salary. *\ #include <stdio.h> #include<conio.h>

\* Output to the Screen*\

void main() {
float tax, net,gross; printf(Gross Salary: ); scanf(%d, &gross); tax = 0.1415 * gross; net = gross tax; printf(/nNet Salary: %f, net); getch(); } \* Decleration *\ \*Input Prompt*\

\* Data Manipulation*\

\* Output *\

LAB-3
Aim: To Study Constant, Variable and Data Types in C Objective:

Basic Understanding of the Constant ,Variables And Data Types in C Programming. How to use efficiently Constant, Variables and Data types in C Programming.

PROGRAM 1 #include<stdio.h> #include<conio.h> main() { int m,a = 10; float sum,b = 10.5; sum = a + b; printf(The sum is %f,sum); sum += a; printf(The sum is %f,sum); sum++; printf(The sum is %f,sum); --a; printf(The value of a %d,a); m = sizeof(sum); printf(The size of sum is %d,m); } PROGRAM 2 Program to find out solution of Quadratic Equation. #include<stdio.h> #include<math.h> void main() { int a,b; float discriminant,root1,root2; printf(Input values of a, b, and c\n); scanf(%f %f %f, &a,&b,&c); discriminant = b*b-4*a*c; if(discriminant<0) printf(\n\n ROOTS ARE IMAGINARY\n); else { root1 = (-b+sqrt(discriminant))/(2.0*a); root2 = (-b-sqrt(discriminant))/(2.0*a);
7

printf(\n\nRoot1=%5.2f\n\nRoot2 = %5.2f\n,root1,root2); } } QUESTIONS 1. Explain the logic of the program. 2. Add comments in the the program. 3. Explain function of printf() and scanf() with the syntax. 4. Study the logic flow and syntax of if - else 5. Why void is needed in the declaration of main()

Assignments:
A) Explain: 1) Which are the types of C constants ? 2) What are the four classes of Data Types ? 3) What are the size and range of integer and double data types ? B) Justify(True/False) the statement and give the reasons. 1) 2) 3) 4) 5) 6) 7) An integer constants must have at least one digit. Default sign in real constants is positive. An integer constants must have a decimal sign. The maximum length of a character constants can be 1 character. Int to float causes truncation of fractional part. Long int to int causes dropping of the excess higher order bits. Operation between a real and real always yields a real result. /=, >>, ^, ~.

C) Identify the type of Operators and Specify use of that. * ,%, <=, !=, &&, ||, --, d)Find out the Result.

a) X = (int)7.5; X = ? b) Y = (int)(a+b); a = 10.5 ,b = 4.5 , Y = ? c) a = int(21.3)/int(4.5) ; a = ? d) b = (double)1000/16; b = ? e) p = cos((double)50); p = ? ________________________________________________________

LAB 4 Aim: Basic Understanding of Operators and Expressions-I Objective:


Basic Understanding of the conditional operators in C Programming. Basic Understanding of the mathematical expressions in C Programming. Program to study conditional operator in C. #include<stdio.h> #include<conio.h> void main() { int a,b; float c = 0; clrscr(); printf(Enter value of a & b); scanf(\t %d \t %d,&a,&b); c+=(a>0 && a<=10)?++a:a/b; printf(value of a b c is %d \t %d \t %f,a,b,c); getch(); } QUESTIONS Explain the logic of the program. Add comments in the the program. Explain the logic flow and syntax of Conditional Operator find out logical operators, shorthand assignment operator and increment operator in the program and explain them in detail MODIFICATION TO BE DONE IN THE PROGRAM

1. 2. 3. 4.

1. Enter two integer values a and b. Check if a>b. If yes then c = decrement a by 1 or c = multiply a with b and add to c. 2. Enter a and b. b as float. Check if a<=b. If yes then do c=a/b (do type casting casting) else do c= a*b-c+a+(b*c) QUESTION: What is type casting? When it is required to be done? 3. Enter a character from the input terminal. Check whether it is in upper or lower case. If in lower case then print 0 else print 1 on the screen.

Program to study mathematical expressions of C. #include<stdio.h> #include<conio.h> void main() { float a,b,c,x,y,z; a = 9; b = 12; c = 3; x = a-b / 3+c*2-1; y = a-b / (3+c)*(2-1); z = a- (b / (3+c)*2)-1; printf(x=%f\n,x); printf(y=%f\n,y); printf(z=%f\n,z); }

10

LAB 5 Aim: Basic Understanding of Operators and Expressions-II Objective:


Basic Understanding of the conditional operators in C Programming. Basic Understanding of the mathematical expressions in C Programming.

1.. A C program contain following expressions. int i = 8, j = 5; float x = 0.005, y = -0.001; char a, b, c = c, d = d; Determine the value of each expression given below and then verify them writing appropriate C program for them. (Use the value initially assigned to variable for each new statement.) 1. 2* ( (i/5) + (4 * ( j 3 )) % ( i + j 2)) 2. (i-3*j) % (c+2*d) / (x-y) 3. i <= j 4. c > d 5. x >= 0 6. c = 99 7. c == 99 8. !(c == 99) 9. c != 99 10. 5* ( i + j ) > c 11. (2 * x + y) == 0 12. 2 * x + (y == 0) 13. 2 * x + y == 0 14. !( i <= j) 15. (i > 0) && (j < 5) 16. (i > 0) || (j < 5) 17. (x > y) && (i > 0) || (j < 5) 18. (x > y) && (i > 0) && (j < 5) 19. y -+ x 20. i /= j 21. a = b = d 22. b = c = d 23. k = (j == 5) ? i : j 24. i -= (j>0) ? j :0 25. x = pow (i , j) 26. x = pow (j , i) 27. j = sizeof (x) + sizeof (a) + sizeof (i)

11

2. Write a program to find value of one number raised to power of the another where the user enters both the numbers. 3. Study the program given below and make your comments regarding logic and output of the program void main() { int a,b; printf(Enter value of a & b); scanf(%d %d, &a, &b); printf(\n the to numbers are %c equal, ((a= =b) ? }

: N));

4. Write a program that will take three sides of the triangle ABCas input and determine whether the triangle is right angled or not. 5. Write a program to find some of all the digits of a five-digit number entered by the user. e.g. n = 12345 sum = 15. 6. Study the program given below and make your comments regarding logic and output of the program #include <conio.h> #include <stdio.h> #include <ctype.h> void main ( ) { char ch; printf("\n%d %d\n",'a','A'); ch=islower(ch=getchar())?ch-32:ch; putchar(ch); ch=getch(); } Modification: 1. Modify the program to produce same results without using islower() 2. Modify the program to change case of the i/p character using library function.

12

LAB 6 Aim: Basic Understanding of FORMETTED INPUT / OUTPUT


1. Execute the following programs & comment on the output. Program: 1 #include<stdio.h> #include<conio.h> void main( ) { HINT char ch; clrscr( ); // give input as wwf < press enter > ch = getchar( ); // give input as < press enter > printf("\n ch = %c",ch); // give input as w < press enter > ch = getchar( ); printf("\n ch = %c",ch); } Program: 2 # include <stdio.h> # include <conio.h> void main ( ) { HINT char ch; clrscr ( ); // give input as wwf < press enter > ch = getchar ( ); // give input as < press enter > putchar ( ch ); // give input as w < press enter > ch = getche ( ); putchar ( ch ); } 1. Interchange getchar & getche in the above program & check the output. 2. Also use getch ( ) in place of getche ( ). 2. Write a program in C to convert an uppercase character ( input through keyboard ) into a lowercase format. ( use library function(s) of <conio.h> file ) 3. Write a program in C for checking validity of an entered character as a first character of a C variable. Display appropriate message. 4. Write the following program on your terminal , apply the given inputs & comment on the output. #include < stdio.h > #include < conio.h > void main ( ) {
13

int a,b,c,d,e,f,g; clrscr ( ); printf (" Enter an integer number .. "); scanf ("%d",&a); // enter number as 11 22 33 < press enter > printf (" Entered number is accepted as %d \n",a); printf (" Now enter three integer numbers ..."); scanf ("%d %d %d",&b,&c,&d ); // enter number as 44 55 66 < press enter > printf (" Accepted values are b = %d \n c = %d \n d = %d \n",b,c,d); printf (" Now enter three values more ..." ); scanf ("%d %d %*d",&e,&f,&g); // enter number as 77 88 99 < press enter > printf (" %d %d %d ", e,f,g); } Also make use of width specifier in the above program & check the output. 5. Justify the following statements. 1. "Any unread data items will be considered as a part of the data input line to the next scanf ( ) call" . 2. "Width Specifier w should be large enough to contain the input data size". 3. "Whenever data mismatch founds scanf ( ) will terminate the program execution". 4. "Value returned by the scanf ( ) can be assigned to a float variable". 6. What would be the values stored in the variables a & ch when the data 2002, DDIT is entered in as a response to the following statement(s). 1. 2. 3. 4. scanf ("%d %c",&a,&ch); scanf ("%c %d",&a,&ch); scanf ("%c %d",&ch &a); scanf ("%s %c",&a &ch);

7. Show the exact output of the following program(s). void main( ) { int count=1234 , m ,a ,b,c; float price = - 567.89; char city[6] = "Nadiad" /* data stored in is Nadiad - an array of six characters */ m = scanf (" %d , %*d , %d " , &a , &b , &c); printf ("%d\ n", m); m = scanf (" %d , %* , %d " , &a , &b , &c); printf ("%d\ n", m);

14

printf (" %d %f \n", count , price ); printf (" %2d \n %f \n ", count , price ); printf (" %d %f \n", price , count ); printf (" %10dxxxxx %5.2f \n ", count , price ); printf (" %s \n ", city ); printf (" %-10d %-15s ", count , city ); } 8. Why one should include <math.h> file ? 9."The contents of the header file become part of the source code when it is compiled" Justify. 10.Explain the different statements by which one can read a character from the keyboard.

15

LAB -7 Aim: To study Decision Making and Branching using IFelse.. Objective:

Basic Understanding of the use If else .. in the Branching. Basic Understanding about the fundamantel concept of branching. #include < stdio.h > #include < conio.h > void main ( ) { char value0; clrscr(); printf(enter Y on N); value0 = getch(); if(value0==Y) printf( Yes); if(value0==N) printf(No); getch(); }

Program 1.

Modification:
1. Modify the sample prog. Such that it prints NO if you enter character other then Y using else. 2. Modify the sample program such that it prints YES for Y, NO for N and Invalid for others.

Assignments:
1. Write a Program to find Factorial of a Given no using If. else.. 2. write a program to find out the solution of a quadratic equations usin If .. Else. Explain logic of the program and write comments 3.Write a program to print apporipriate message depending on time which is given by user using nested if.. else 0-12 Good Moarning 12-18 Good AfterNoon 18- 21 Good Evening 21-24 Good Night Else Invalid 4. Write a prog that will read the value of X and evaluate following Y=1 for X>0 Y=0 for X=0 Y=-1 for x<0 Using If.. else. 5. Write a programe to find greast of four no entered by user .

16

LAB -8 Aim: To study Decision Making and Branching using Switch Case. Objective:

Basic Understanding of the use Switch Case in the Branching. #include < stdio.h > #include < conio.h > void main ( ) { char value0; clrscr(); printf(enter Y on N); value0 = getch(); { case=Y printf( \n Yes); break; case N; printf(\n No); break; }

Program 1.

Modification:
1. Modify the sample prog. Such that it prints NO if you enter character other then Y using default. 2. Modify the sample program such that it prints YES for Y or y, NO for N or n and Invalid for others using default.

Assignment:
1. Write a prog that will read the value of X and evaluate following Y=1 for X>0 Y=0 for X=0 Y=-1 for x<0 Using Switch Case. 2. Write a prog for calculator which will carry out basic four arithmetic operation for two nos. using Switch Case. 3. Write a program for assigning Grades to the students based upon the marks input by user. Using switch case 4. Write a prog to enter the students mark and print massage whether he/she is pass or not. Using switch case 5. Write down a program to check whether enter character is vowel or not. Display appropriate message on the screen.(Also modify the program to calculate the frequency of entered string) 6. Write a prog to calculate root of quadratic equitation .(a*X*X+b*X+c=0) Using switch case for values of Dalta. If a= 1,b=1,c=1

17

a =1,b=-4,c=4

LAB-9 Aim: To study Branching using Continue and GoTo Objective:


Basic Understanding of Continue Basic Understanding about the GoTo.

Lab activity:
Run the given program. Solve the error if any. Modify the program. Find the answer of Questions. Solve the Assignment and tutorials.

Program 1.
#include < stdio.h > #include < conio.h > void main ( ) { char ch; printf(\n %d %d ,a,A); c!= islower(ch=getchar())?ch-32:ch; putchar(ch); ch=getchar(); }

Modification:
Modify the program to produce same responses without using islower().

Assignment:
A).Write a program that will read a value x and evaluate the following 1 for x>0 Y= 0 for x=0 -1 for x<0 Using 1) ifelse 2)switch statement. B) Write a prog that find the factorial of a no. using go to C) Write a prog to calculate Fibonacci series of m numbers using DO While loop

Program 2
#include < stdio.h > #include < conio.h > void main ( ) { int i=1,num,sum=0; for (i= 0;i<5;i++) {

18

printf(enter integer) scanf (%i, &num); if (num<0) { printf (Negative Num); continue; } sum+=num; } printf(The Sum 0f Positive integer is: %i \n ,sum); }

Question:
Explain Logic and write output of the program.

Assignment:
1. Write a prog to print all prime no from 1 to 300.(use nested loop ,brack and continue) 2. Find Out put: Void main() { Char ch; Do { Ch= getchar() If(ch>= 48 && ch =57) { Printf(%d,ch); Continue; } Else brack; } While(1) }

19

LAB-10 Aim: To study Looping using While DOWhile Objective:

Basic Understanding of While DOWhile

Program 1.
The Program display the message Hello.and reads a character from the keyboard if the character not A it prints the message again .the prog continues while the characters is not A and terminates while it is a #include < stdio.h > #include < conio.h > void main ( ) { char ch; ch=getchar(); while(ch!=a) { printf(Hello..); ch=getchar(); } } MODIFICATION Modify the program to print the message 25 times and terminate then after. (A) Write a program using while loop to reverse the digit of number. Example: the number 12345; (B) Write a program to generate Pascals triangle 1 1 1 1 1 4 3 6 2 3 4 1 1 1 1

20

Program: main() { Char ch; Do { Printf(Hello!); Ch=getch(); } While(ch!=A); } MODIFICATION: Modify the program to continuously print the message until a key is pressed from the key board. ASSIGNMENT: Main() { Int i=1; While(i<=10); Printf(%d\n,i); } What is the output of the program? If some errors, modify the program appropriately.

21

LAB-11 Aim: To Study Single Dimensional Array Program


void main ( ) { int a[10]; printf (Enter ten numbers); for ( i=0 ; i<10 ; i++ ) { printf (Enter the No. %d, i ): scanf (%d, &a[i] ); } printf (Saved ten numbers ); } Write Output of the Program. Modification: 1. Modify the program to append one data array to another. (e.g. add contents of b[10] to the end of a[10]) 2. Modify the program to add all the numbers entered by the user and display sum of those numbers. ASSIGNMENT: 1 Write a program to sort given 10 numbers in ascending order. Modify the program for descending order sorting 2 Write a program to enter & store char array into memory until e is entered. 3. 4. 5 6. 7. What does array mean? State advantage of array. Can an array contain different data types? Explain the memory allocation for one dimensional array. Why it is necessary to specify the size of an array at the time of declaration? int array1[10] a) Here what does array1 represent? A) address B) value b) What is the difference between scanf ( %d, &a[0] ); and scanf (%d, a);? 8 From which element array will be started?

22

EXPERIMENT 12
AIM: Multidimensional Array Familiarization to multidimensional array approach. To make efficient programs using multidimensional array.

Sample program :
void main( ) { int i , j , row , col , A[10][10] , B[10][10] , C[10][10]; clrscr( ); printf( Enter number of rows for both the matrices : ); scanf( %d , &row ); printf( \nEnter number of columns for both the matrices : ); scanf( %d , &col); printf( \nPlease enter values for matrix A . ); for( i = 0 ; i < row ; i++ ) { printf( \nEnter row[%d] elements ); for( j = 0 ; j < col ; j++ ) scanf( %d , &A[i][j] ); } printf(\n Please enter values for matrix B . ); for( i = 0 ; i < row ; i++ ) { printf( \nEnter row[%d] elements ); for( j = 0 ; j < col ; j++ ) scanf( %d , &B[i][j] ); } printf(\nGenerating resultant matrix C); for( i = 0 ; i < row ; i++ ) for( j = 0 ; j < col ; j++ ) C[i][j] = A[i][j] + B[i][j] ; Printf( \nDisplaying Resultant Matrix C : ); For( i = 0 ; i < row ; i++ ) { for( j = 0 ; j < col ; j++ ) printf( %d , C[i][j] ); printf( \n ); } getch( ); }

23

Modifications: Modify the above program so that 1. It sorts all the elements of the resultant matrix into ascending order. 2. Finds the transpose of the resultant matrix. 3. Finds the determinant of the resultant matrix. Exercise: 1. Write a program to multiply matrix A[n][m] and B[m][p]. Display resultant matrix as C[n][p]. 2. Write a program to calculate the elements of the Pascal triangle for n rows entered by user and print the result as shown below. Pascal triangle for n = 5 : 1 1 1 1 1 4 3 6 2 3 4 1 1 1 1

3. Write a program to display the contents of the 5th element of the following array declared as int var[2][3][4]. For the same element, what should be its memory address if the base address is 20 ? 4. Write a program to generate a N * N magic square and make sure that N is an odd number supplied by user. 5. Write a program to store a record of the students of a given class. For each student your program should store internal marks for five different subjects. Assume that the maximum number of students in a class is 100 & that there are three internal examinations. ( Use three dimensional array ) 6. Write a program in C to print a multiplication table as shown below: | 1 2 3 . . (input from user) ------------|---------------------------------------------------------------------1 | 1 2 3 2 | 2 4 6

24

9 Tutorial Questions

1. Explain the declaration and initialization of 2-d array. 2. Are any of the following initialization statements invalid ? Why ? a. int arr[2][3]={ { 12,34,23},{45,56,45} }; b. int arr[2][3]={ {12,34}, {23,45}, {56,45} }; c. int arr[2][3]={12,34,23,45,56,45}; d. int arr[ ][3]={12,34,23,45,6,45}; e. int arr[2][ ]={12,34,23,45,56,45}; f. int arr[ ][ ]={12,34,23,45,56,45}; g. float value[10],[23]; 3. What will be the output of the following program: void main( ) { int n[3][3]={2,4,3,6,8,5,3,5,1}; printf(\n %d %d,n[3][3],n[2][2]); } 4. Assume that the arrays A and B are declared as follows: int A[5][4]; float B[4]; Find the errors (if any) in the following program segments: a) for(i=1;i<=5;i++) for(j=1;j<=4;j++) A[i][j] = 0; c) for(i=0;i<=4;i++) B[i]=B[i]+i; b) for(i=1;i<4;i++) scanf(%f,B[i]); d) for(i=4;i>=0;i--) for(j=0;j<4;j++) A[i][j]=B[j]+1;

5. Point out errors, if any, in the following program: void main( ) { int three[3][ ] = {2,4,3,6,8,2,2,3,1}; printf(\n %d,three[1][1]); } 6. How will you initialize a three dimensional array three[3][2][3]? How will you refer to the 1st and last element in this array? 7. Explain how memory is allocated for a 2-d and 3-d array.

25

26

EXPERIMENT 13
AIM: Understanding the difference between character arrays & Strings. To become familiar with the string handling functions and their usage.

Sample program:
void main( ) { int i = 0; char ch , name[20]; printf( Enter characters, terminate the input by pressing spacebar \n); while( ( ch = getchar( ) ) != ) name[i++] = ch ; name[i] = \0 ; printf(Thanks for entering a string\n); printf(Total Number of characters Entered by user = %d\n,i+1); printf(Number of informative characters are %d \n,strlen(name)); printf(Number of bytes allocated for name = %d\n,sizeof(name)); }

Modification : 1. Modify the above program so that it reads a line of text from keyboard (including white spaces) and counts the no. of characters & words. Assume that the words are separated by one blank space only. 2. Differentiate between strlen( ) and sizeof( ) with respect to the above program. Exercise : 1. Write a program, which reads a string from the keyboard and generates the alphabetical order of characters that represents the string. Eg. PROGRAM should be written as AGMOPRR. 2. Write a program that will read a line of text and count all occurrences of a particular word. It should also replace the particular word by another specified word in the given line. 3. Write a program to check whether the string is a palindrome or not. 4. Write a program to delete a repetitive character from a string after retaining only the first entry of that character.

27

5. Write a main( ) to compare two strings entered by user. Your program should display an appropriate output message along with the difference of ASCII values of the first non matching characters in both the strings. (Similar to the function strcmp( )). You are not allowed to use strcmp( ) directly. 6. Write a program to display an entered string in the following format: Assume input string : HELLO Output on monitor : H H E H E L H E L L H E L L O 7. Write a program that will print out all the rotations of a string input by the user. Eg. The rotations of word space are : space paces acesp cespa espac

28

Tutorial Questions 1. What is a string ? Explain different methods of declaration and initialization of a string with suitable examples. 2. Why the & sign is not required before the variable name in scanf( ) while reading a string? 3. Which library functions are available to read and print a string ? 4. Which function is used to convert a string into its integer value ? 5. How will you initialize and display an array of strings ? 6. What happens if the total size of a string after strcat( ) becomes greater than the array size of the string used to hold the concatenated string ? Does the compiler report an error? 7. What is a null character and when is it used, in the context of strings ? 8. Write a C function using which we can convert a string to its equivalent integer number. 9. Which C library function converts a string of digits into their integer values? Illustrate with an example. 10. What does strcmp( ) function do? Does it return any value? Illustrate with an example. 11. How can we concatenate three strings? 12. What is the difference between gets( ) and scanf( ) with respect to reading of a string. 13. What will be the output of the following programs: a) void main( ) { char s[ ]=Get going; printf(\n %s,&s[2]); printf(\n %s,s); printf(\n%s,&s); printf( \n %c,s[2]); } b) void main() {

29

char c[2] = A; printf(\n %c,c[0]; printf(\n %s,c); }

30

EXPERIMENT14
AIM: To become aware of the benefits of using preprocessor directives. Increase understanding of different ways of including files in a program. To use preprocessor directives for efficient programming.

Sample Program :

#define M 5 #define square(x) ((x)*(x)) void main( ) { int p = M; p++; printf(Square of p = %d\n,square(p)); }

Modification : 1. Modify the program to find the cube of a given number using the macro definition. 2. Is it necessary to use a parenthesis around x for the above macro definition ? 3. How many bytes of memory will be allocated for M in the above program ? Why ? Exercise : 1. What will be the output of the following programs: a) void main() { int i=2; #ifdef DEF i*=i; printf(\n %d,i) #else printf(\n %d,i); #endif } #define MUL(x) (x*x) main()
31

b)

{ int i = 3,j; j = MUL(i+1); printf(\n %d,j); } c) #define ADD(x) ((x)+(x)) main( ) { int i=3,j,k; j = ADD(i++); k = ADD(++i) ; printf(\n %d %d,j,k); }

2.

Write down macro definitions for the following: a. To test whether a character entered is a small case letter. b. To obtain the largest number among three entered numbers. c. To find the circumference of circle.

32

Tutorial Questions 1. Explain the role of the C- Preprocessor. 2. What is a macro and how is it different from a C variable ? 3. What do you mean by macro definition ? Illustrate with an example. Also mention the reasons for using it. 4. What precautions are to be taken while using macros with arguments ? Illustrate with an example. 5. List the advantages of using macros in a program. 6. The value of macro name cannot be changed during the running of a program, True/False. 7. What is conditional compilation? How does it help a programmer? 8. Explain Stringizing Operators & Token Pasting Operator. 9. What is the difference between a macro call and a function call? 10. Differentiate between: a) #include <syntax.c> b) #include syntax.c 11. Explain the following directives: a) #elif b) #error

33

EXPERIMENT 15
AIM: To clearly distinguish between library functions & user defined functions. To understand the need of user defined functions as an efficient programming technique. Adopting suitable method for passing arguments to a function. Understand the concept of nested functions & recursive functions.

Sample Program :
void main( ) { int odd(int); int i,k,a[10]; for(i=0;i<10;i++) { printf(Enter a[%d],i); scanf(%d,&a[i]); } for(i=0;i<10;i++) printf(a%d = %di,a[i]); k=0; for(i=0;i<10;i++) { if(!odd(a[i])) { k++; printf(\n%d %d,a[i],k); } } printf(%d,k); } int odd(int j) { if(j%2) return (1); else return (0); }

Modifications : 1. Modify the above program to print all odd and even elements featuring in the array using the same function. 2. Modify the above program to count all elements, which are divisible by 5 defining and using a function scale5( ) and print all the numbers.

34

Exercise : 1. Write a function to compute the distance between 2 points and use it to develop another function that will compute the area of the triangle whose vertices are A(x1,y1), B(x2,y2) and C(x3,y3). Demonstrate the usage of the above functions in main().

2. Write a program to display first n elements of a Fibonacci series using a recursive function. 3. Write a program to find factorial of a given number using recursive function. 4. Define a function search( ) which accepts an array of student records, min_marks & max_marks as the arguments. Assume that the array of student records stores information of total marks obtained by all students based on their id. search( ) will display student id & their marks , if it falls between the specified range. It also returns total no of students in that range. Make appropriate main( ) routine for demonstrating the use of search( ).

35

Tutorial Questions

1. Give the general syntax of declaring functions. 2. What are the two ways of declaring function parameters ? 3. What are dummy and actual parameters ? Can the order of these parameters differ in function calls and definitions ? 4. What is the difference in global and local parameters ? 5. What is the use of return statement ? Should it always be present in a function ? Why ? 6. What do you mean by function prototype ? Is it required to be used always ? 7. What is the significance of function type in function prototype ? 8. What would be the default data type of a function ? 9. How many return statements can there be in a function ? How many of them will be executed at run time, if they are more than one ? 10.Too many function calls may degrade the performance of a program. Justify. 11.Why recursive functions are less efficient ? What is their main advantage? 12.main( ) { int a; void increment(int); a = 5; printf(a = %d\n,a); increment(a); printf(a = %d\n,a); getch( );
36

} void increment( int a) { a++; printf(a = %d\n,a); } What will be the output of the above program? 13. What will the following return statement return to main( ): return;

37

S-ar putea să vă placă și