You are on page 1of 10

National College of Computer Studies Mid Term Exam 2005 BIM/Second Semester/ITC 213: Structured Programming Full Marks:

40 Pass Marks: 18 Time: 2 hours Candidates are required to give their answers in their own words as far as possible Attempt all the questions The figure in the margin indicates full marks

[NOTE to the students: Im written this solution in hurry. If you find any typographical or others errors, please mail me at bhaskar@nccs.edu.np] Group A
Answer Briefly (1 10 = 10) 1. When are operator precedence and associativity rules used while evaluating expressions When different operators are used in an expression, C uses operator precedence rules to determine which operator action is to be performed first. The C operators are grouped hierarchically according to their precedence. Operations with a higher precedence operator are carried out before operations having a lower precedence operator. Consider the following expression a+b*c Here the operation of *, i.e. multiplication, is performed first before the operator of the operator +. Because * has higher precedence than +. When operators having equal precedence are used in an expression, C uses associativity rules to determine the evaluation order. If the operator has left-to-right associativity then the operation of the operator on the left is performed first before the operation of the operator on the right. If the operator has right-to-left associativity then the operation of the operator on the right is performed first before the operation of the operator on the left. Consider the following expression a*b/c Here * and / have equal precedence and their associativity is left-to-right. Hence the operation of * is performed before the operation of /. 2. How can you perform input and output operations in a C program Input and output operations in a C program can be done using the input/output library functions prototyped under the header file <stdio.h>. The following six functions are generally used to perform input/output i) getchar - reads a single character ii) gets - reads a line of text iii) scanf - performs formatted input. Can be used for reading all the built-in types iv) putchar - outputs a single character v) puts - outputs a line of text vi) printf - performs formatted output. Can be used for printing all the built-in types. The first three functions are used for input and the next three are used for output. All input operations are carried on the standard input device, which by default is the keyboard. All output operations are carried on the standard output device, which by default is the screen. 3. Explain how the if-else ladder differs from a switch statement

Both if-else ladder and switch statement can be used to write muti-way decision structure. Switch is more restricted than if-else. The conditional expression for a if can be any valid expression that evaluates to a scalar type, where as for switch the conditional expression must evaluate to an integral type. switch can be used only for testing equality of the expression, but if can test for any complex expression (such as relational or logical). 4. What is the difference between pass by value and pass by reference? Pass by value Pass by reference When a variable is passed to function by When a variable is passed to a function by value, the changes made to the reference, any changes made to the formal corresponding formal parameter variable parameter will immediately change the in the function will not change the value of value of the actual variable passed in the the actual variable passed function call The value of the argument is passed to the The address of the argument is passed to the function function To pass a variable by value, we simply To pass a variable by reference, we specify specify its name in the function call the address of the variables by placing an ampersand before the variable name in the function call 5. Suppose i, j, k are integer variables and initialized to 1, 2 and 3 respectively, after executing the following module, what will be the value of i and k?
i = ++k + ++j - --i ; k = j-- - i--; i = 6, j = 2, k = -4

6. What the following code fragment prints


int k = 5; do printf("%d ", ++k); while (k++ < 10); 6 8 10

7. What is the value of the integer variable x after the following code is executed?
x = 1; for (i = 2; i < 10; i++) { if (i%3 == 0) continue; x += i; }

27 8. What are the jump statements available in C? The jump statements available in C are a) goto Makes unconditional jump to statements following the specified label within the same function b) break: Causes immediate exit from a while, for, do-while or switch structure c) continue: Skips the remaining statements in the body of a while, for or do-while structure 9. What are the advantages of using functions? Manageable program development/Modular design: Functions break large computing tasks into smaller ones. Program becomes more manageable, easier to understand and debug.

Code Reuse/Avoids code repetition: By calling a function multiple times, the code inside the function is reused. To do the task performed by a function, we dont have to start from scratch. Code hiding / Abstraction: Functions hide details of operation from parts of the program that don't need to know about them, thus clarifying the whole 10. Differentiate between static and automatic variables in C. Static Variables Automatic Variables Variables declared with static storage Variables declared inside functions, class specifier including formal parameters, without any storage class specifier specified or with the auto storage class specifier specified If not explicitly initialized, value is Have unknown values, when the automatically initialized to zero variable is not initialized Storage created when the declaration is Created each time the block, in which first encountered and remains in they are declared, is entered and is memory till program runs destroyed upon from the block.

Group B
1. Differentiate between formal and actual arguments. [2] Formal arguments (parameters) are variables declared in the function header of a function definition. Actual arguments are expressions that are specified inside parenthesis in a function call. When a function is called, the value of the actual argument in the function call is transferred to the corresponding formal parameter variable in the function call. Consider the following function void test(int a, int b, int c) { int s s = a + b + c; printf(%d\n, s); } Here the variables a, b and c are formal arguments. The following is a sample call to the function just defined above int a, b; b = test(a, a + 10, 20); Here the variable a, the expression a + 10 and the literal constant 20 are all actual arguments. 2. Write a function that reads a line of text and returns the no of characters entered. Write a program that calls this function repeatedly to read several lines of text. Your program should stop reading when a blank line is encountered. Find the average number of characters entered per line. [3 + 2 + 3]
#include <stdio.h> /* Reads a line of text and returns the no of characters entered */ int readline(void) { int count = 0; char ch; ch = getchar(); while (ch != '\n') { count++; ch = getchar(); } /* end while */ return count; } /* end readline */ int main() { int numlines; /* The total no. of lines read till now */ int numchars; /* No. of characters in current line */ int totalchars; /* Total no. of characters read till now */ numlines = 0; totalchars = 0; /* read a line */ numchars = readline(); while (numchars > 0) /* check for empty line */ { totalchars += numchars; numlines++; numchars = readline(); /* read next line */ } /* end while */

if (numlines > 0) { float avg = (float) totalchars/numlines; printf("Average no. of characters in %d lines is %.2f\n", numlines, avg); } else printf("No characters entered\n"); } /* end main */

Group C
Attempt any four (4 5 = 20) 1. Explain the given program and write the result when the program is run.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <stdio.h> int funct1(int count); main() { int a, count; for (count = 1; count <= 5; ++count) { a = funct1(count); printf("%d ", a); } } int func1(int x) { int y; y = x*x; return y; }

[3+2]

This program demonstrates usage of a simple function named funct1. This function is called more than one time, justifying one of the advantage of using functions. The required header file stdio.h is included in Line 1. Line 3 is a prototype of the function funct1, which is called within main. This prototype is necessary to make the compiler aware of its existence. Since the function is called in Line 10 before it has been defined. The prototype at Line 3 int funct1(int count); tells the compiler that a function named funct1 exists, taking only one int parameter and returning an integer value. The main function starts at Line 5. It first declares two int variables a and count in Line 7. The variable a is used to hold the return value of the function call of funct1. The for loop in Line 8 runs for 5 times, starting with the value 1 for count and incrementing it in each step of the iteration. Line 8 makes a call to the function funct1, passing it the current value of count. Hence for the first call the value 1 is passed to funct1, since count has value 1 at first iteration of the loop. The returned value of the function call is stored in a which is printed in Line 11. The function definition of funct1 starts at Line 15. It calculates the square of the parameter x and returns the calculated result. A temporary variable y is declared in Line 17, which is used to hold the calculated square in Line 18. Line 19 returns the square stored in y. Hence in main when the function funct1 is called at Line 10, a will contain the square of current value of count. So the output of the program will be the squares of the numbers from 1 to 5. 1 4 9 16 25

2. What do you mean by function prototype? Write a function that given a positive integer, prints its prime factors. (Hint: The prime factors of 60 is 2 2 3 5, i.e., 60 = 2235) Write a main function to test the above function. [1 + 3 + 1] A function prototype is a declaration of a function that specifies its name, the number and type of parameters it takes (if any) and the return type. For e.g., the following statement is a function prototype of function named add that takes two integer values as arguments and return their sums int add(int x, int y); A function prototype is needed when a function is called before it is defined. By seeing the function prototype the compiler will have enough information to make correct calls of it. It can check if the no of arguments and their types, specified in the function call, is correct or not. If some other type of argument is specified in the function call, the compiler can make correct type conversion.
#include <stdio.h> /* Prints all prime factors of the given positive integer n */ void PrintFactors(int n) { int f; f = 2; /* factor starts with 2 */ while (n > 1) { if (n % f == 0) /* is n divisible by f? */ { /* then f is a prime factor of n, so print it */ printf(" %d", f); n = n/f; } else { /* no, try next integer */ f++; } /* end if-else */ } /* end while */ } /* end PrintFactors */

int main() { int num; printf("Enter a positive integer: "); scanf("%d", &num); printf("The prime factors of %d are", num); PrintFactors(num); printf("\n"); }

3. Explain how different control statements can be nested. Write a program to calculate the value of the following series up to n terms (Value of n should be read) [2 + 3] One type of control statement can be (embedded) nested within another type of control statement as required by the program logic.
x+ x3 x5 x7 + + + ... 3! 5! 7!

For example, the following code fragment prints all integers, between 1 and 100, that are either divisible by 3 or 5 for (i = 1; i <= 100; i++) if (i%3 == 0 || i%5 == 0) printf("%d ", i); Here the if statement is nested within the for statement. We can create nested loops, by embedding a loop statement within another. for (i = 1; i <= 10; i++ { prod = 1; for (j = 2; j <= i; j++) prod *= j; printf("%ld ", prod); } This prints the factorials of all integers from 1 to 10. When using nesting loop, the loop control variable for each loop should be different. In the example above, the loop control variable for outer for loop is i and for inner for loop is j. When nesting control statements, we must completely embed one structure within another. In other words, we can't overlap control statements. For example, The following code is wrong for (i = 1; i <= 100; i++) { if (i%2 == 0) evensum += 2; } else oddsum += 2;

#include <stdio.h> #include <math.h> /* for pow() */ /* Function Prototypes */ long int factorial(int n); double CalcSeries(double x, int nterms); int main() { double x, val; int n; printf("Enter value of x: "); scanf("%lf", &x); printf("Enter no. of terms: "); scanf("%d", &n); val = CalcSeries(x, n); printf("The sum of the series is %f\n", val); return 0; } /* Calculates and returns the factorial of the given integer n */ long int factorial(int n) { int i; long int prod = 1;

for (i = 2; i <= n; i++) prod *= i; return prod; } /* end factorial */ /* Calculates and returns the sum of given series in question x is the value of x in series nterms is the no. of terms to sum up */ double CalcSeries(double x, int nterms) { int i, e; double sum = 0; /* the cumulative sum of the series */ double term; /* the value of current term */ /* loop nterms times */ for (i = 1, e = 1; i <= nterms; i++, e+=2) { term = pow(x, e)/factorial(e); sum += term; } /* end for */ return sum; } /* end CalcSeries */

4. What is the use of switch statement? Write a menu driven to perform the following operations: a. Determine if a given number is even or not b. Determine the absolute value of a given number c. Determine if the largest of two numbers
d. Exit [1 + 1 + 3] The switch statement is used when a variable or expression is to be tested for all the values it can assume and different actions need to be taken.
#include <stdio.h> int main() { char choice; int a, b, n; do { /* print the menu */ printf("MENU\n"); printf("[a] - Determine if a given number is even or not\n"); printf("[b] - Determine the absolute value of a given number\n"); printf("[c] - Determine the largest of two numbers\n"); printf("[d] - Exit\n"); /* read a menu choice */ printf("\nPlease enter your choice: "); scanf(" %c", &choice); switch (choice) { case 'a': /* Determine if a given number is even or not */ case 'A': printf("Enter a number: "); scanf("%d", &n); printf("%d is ", n); if (n%2 == 0) printf("even\n"); else printf("odd\n");

break; case 'b': /* Determine the absolute value of a given number */ case 'B': printf("Enter a number: "); scanf("%d", &n); printf("Absolute value of %d is %d\n", n, n > 0 ? n : -n); break; case 'c': /* Determine the largest of two numbers */ case 'C': printf("Enter two numbers: "); scanf("%d %d", &a, &b); printf("The largest one is "); printf("%d\n", a > b ? a : b); break; case 'd': /* Exit */ case 'D': break; default: printf("Illegal choice entered\nPlease try again ...\n"); } /* end switch */ } while (choice != 'd' && choice !='D'); return 0; } /* end main */

5. Explain how a do-while loop differs from while loop? Write a program to calculate the sum of first n odd integers (When n = 10, sum =1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19). Write the loop in three different ways a. Using a for loop b. Using a while loop c. Using a do-while loop [1 + 1 + 3] In a do-while loop, the conditional expression is evaluated at the end of the pass of the loop. In a while loop, the conditional expression is evaluated at the beginning of the pass of the loop. The body of a dowhile loop is executed at least once.
#include <stdio.h> int main() { int i, n; int sum; printf("How many odd numbers you want to sum up? "); scanf("%d", &n); sum = 0; for (i = 1; i <= 2*n-1; i += 2) { sum += i; } printf("The sum of first %d odd numbers is %d\n", n, sum); return 0;

Using while loop


sum = 0;

i = 1; while (i <= 2*n-1) { sum += i; i += 2; }

Using do-while loop


sum = 0; i = 1; do { sum += i; i += 2; }while (i <= 2*n-1);

You might also like