CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in...

64
CPU Unit Wise IMP Questions Answers for GTU UNIT: 1 (Introduction to Computer Programming) 1) Draw block diagram of computer system. Explain each part of it. The computer performs basically five major operations of functions irrespective of their size and make. These are 1) it accepts data or instruction by way of input, 2) it stores data, 3) it can process data as required by the user, 4) it gives results in the form of output, and 5) it controls all operations inside a computer. We discuss below each of these operations. 1. Input: this is the process of entering data and programs into the computer system.e.g Keyboard,Mouse,Digital Pen.etc.. 2. Control Unit (CU): The process of input, output, processing and storage is performed under the supervision of a unit called 'Control Unit'. It decides when to start receiving data, when to stop it, where to store data, etc. It takes care of step -by-step processing of all operations in side the computer. 3. Memory Unit: Computer is used to store data and instructions. 4. Arithmetic Logic Unit (ALU): The major operations performed by the ALU are addition, subtraction, multiplication, division, logic and comparison. 5. Output: This is the process of producing results from the data for getting useful information. E.g Monitor,Speaker.

Transcript of CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in...

Page 1: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

CPU Unit Wise IMP Questions Answers for GTU

UNIT: 1 (Introduction to Computer Programming)

1) Draw block diagram of computer system. Explain each part of it.

The computer performs basically five major operations of functions irrespective of their size and make. These are 1) it accepts data or instruction by way of input, 2) it stores data, 3) it can process data as required by the user, 4) it gives results in the form of output, and 5) it controls all operations inside a computer. We discuss below each of these operations. 1. Input: this is the process of entering data and programs into the computer system.e.g Keyboard,Mouse,Digital Pen.etc.. 2. Control Unit (CU): The process of input, output, processing and storage is performed under the supervision of a unit called 'Control Unit'. It decides when to start receiving data, when to stop it, where to store data, etc. It takes care of step -by-step processing of all operations in side the computer. 3. Memory Unit: Computer is used to store data and instructions. 4. Arithmetic Logic Unit (ALU): The major operations performed by the ALU are addition, subtraction, multiplication, division, logic and comparison. 5. Output: This is the process of producing results from the data for getting useful information. E.g Monitor,Speaker.

Page 2: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

The ALU and the CU of a computer system are jointly known as the central processing unit (CPU). You may call CPU as the brain of any computer system.

2) What is Software and Hardware? Explain different types of Software. Hardware:- The term hardware describes the physical parts of your computer which you can physically touch or see such as your monitor, case, disk drives, microprocessor and other physical parts. Software:- The term software describes the programs that run on your system. This includes your computer operating system and other computer programs which run. Software is written in a computer language (such as Basic, C, Java, or others) by programmers.. Writing these text files and converting them to computer readable files is the way operating systems and most application programs are created. System software and application programs are the two main types of computer software.

Application software Unlike system software, an application program (often just called an application or app) performs a particular function for the user. Examples (among many possibilities) include browsers, email clients, word processors and spreadsheets.

System software System software is a type of computer program that is designed to run a computer’s hardware and application programs. If we think of the computer system as a layered model, the system software is the interface between the hardware and user applications. The operating system (OS) is the best-known example of system software. The OS manages all the other programs in a computer. 3) Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number given by user. Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows show the sequence of the steps, and the relationships among them. These are known as flowchart symbols.

Page 3: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

The connector symbol connects separate elements across one page. It’s usually used within complex charts.

The process symbol represents a process, action, or function. It’s the most widely-used symbol in flowcharting. The decision symbol indicates a question to be answered—usually yes/no or true/false. The flowchart path may splinter into different branches depending on the answer.

The data symbol (also called the input/output symbol) represents data that is available for input or output. It may also represent resources used or generated. The paper tape symbol also represents input/output, but is outdated and no longer in common usage. Another symbol used to represent data is the circle shape. Finding Factorial of a number given by user.

Page 4: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

4) Define algorithm and explain different symbols used in flowchart. Step by step procedure designed to perform an operation. Algorithms have a definite beginning and a definite end, and a finite number of steps. An algorithm produces the same output information given the same input information. For flowchart symbol please refer Q.3 Ans. 5) Explain different type of operators used in C language with their precedence and associativity. An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Increment/Decrement Operators

Special Operator

Conditional Operator Arithmetic Operators

C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators.

Page 5: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Operator Description

+ adds two operands

- subtract second operands from first

\* multiply two operand

/ divide numerator by denumerator

% remainder of division

++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one

Relational Operators The following table shows all relation operators supported by C.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical Operators C language supports following 3 logical operators. Suppose a=1 and b=0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Bitwise Operators

Page 6: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bitsfrom right to left. Bitwise operators are not applied to float or double.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise & , | and ^

A B a & b a | b a ^ b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence. Example : a = 0001000 b= 2 a << b = 0100000 a >> b = 0000010 Assignment operators Assignment operators supported by C language are as follows.

Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b

Page 7: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

-= subtracts right operand from the left operand and assign the result to left operand

a-=b is same as a=a-b

*= mutiply left operand with the right operand and assign the result to left operand

a*=b is same as a=a*b

/= divides left operand with the right operand and assign the result to left operand

a/=b is same as a=a/b

%= calculate modulus using two operands and assign the result to left operand

a%=b is same as a=a%b

Conditional Operator It is also known as ternary operator and used to evaluate conditional expression. epr1 ? expr2 : expr3 If epr1 Condition is true ? Then value expr2 : Otherwise value expr3 Special Operators

Operator Description Example

Sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of an variable &x ; return address of the variable x

* Pointer to a variable *x ; will be pointer to a variable x

Increment/Decrement Operators

Increment operators are used to increase the value of the variable by one and decrement operators are used to decrease the value of the variable by one in C programs. Syntax: Increment operator: ++var_name; (or) var_name++; Decrement operator: – -var_name; (or) var_name – -; Example: Increment operator : ++ i ; i ++ ; Decrement operator : – – i ; i – – ; C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator Description Associativity

Page 8: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

( ) [ ] . -> ++ --

Parentheses (function call) (see Note 1) Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement (see Note 2)

left-to-right

++ -- + - ! ~ (type) * & sizeof

Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (convert value to temporary value of type) Dereference Address (of operand) Determine size in bytes on this implementation

right-to-left

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= > >=

Relational less than/less than or equal to Relational greater than/greater than or equal to

left-to-right

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

| | Logical OR left-to-right

? : Ternary conditional right-to-left

= += -= *= /= %= &= ^= |= <<= >>=

Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment

right-to-left

, Comma (separate expressions) left-to-right

Note 1:Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to outer. Note 2:Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done.

Page 9: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

UNIT : 2 Fundamentals of C

1) State the syntax of Switch-case statement. Explain it with appropriate example. Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. If a programmer has to choose one block of statement among many alternatives, nested if...else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch statement. Syntax of switch...case switch (n) { case constant1: code/s to be executed if n equals to constant1; break; case constant2: code/s to be executed if n equals to constant2; break; . . . default: code/s to be executed if n doesn't match to any cases; } The value of n is either an integer or a character in above syntax. If the value of n matches constant in case, the relevant codes are executed and control moves out of the switch statement. If the ndoesn't matches any of the constant in case, then the default codes are executed and control moves out of switch statement.

Page 10: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Example of switch...case statement Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands

and perform the corresponding calculation on the operands.

/* C program to demonstrate the working of switch...case statement */

/* C Program to create a simple calculator for addition, subtraction,

multiplication and division */

# include <stdio.h>

int main() {

char o;

float num1,num2;

printf("Select an operator either + or - or * or / \n");

scanf("%c",&o);

printf("Enter two operands: ");

scanf("%f%f",&num1,&num2);

switch(o) {

case '+':

printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);

break;

case '-':

printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);

break;

Page 11: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

case '*':

printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);

break;

case '/':

printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);

break;

default:

/* If operator is other than +, -, * or /, error message is shown */

printf("Error! operator is not correct");

break;

}

return 0;

} Output Enter operator either + or - or * or /

*

Enter two operands: 2.3

4.5

2.3 * 4.5 = 10.3 The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed. 2) What do you understand by looping? Explain different types of loops in C with example. You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −

Page 12: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

C programming language provides the following types of loops to handle looping requirements. while loop: A while loop in C programming repeatedly executes a target statement as long as a given condition is true. Syntax The syntax of a while loop in C programming language is − while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. Flow Diagram

Page 13: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example #include <stdio.h>

int main () {

/* local variable definition */

int a = 10;

/* while loop execution */

while( a < 20 ) {

printf("value of a: %d\n", a);

a++;

}

return 0;

} When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13

Page 14: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 for loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax The syntax of a for loop in C programming language is − for ( init; condition; increment ) { statement(s); } Here is the flow of control in a 'for' loop − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.

Page 15: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Flow Diagram:

Example #include <stdio.h>

int main () {

int a;

/* for loop execution */

for( a = 10; a < 20; a = a + 1 ){

printf("value of a: %d\n", a);

}

return 0;

} When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17

Page 16: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

value of a: 18 value of a: 19 do...while loop: Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. Syntax The syntax of a do...while loop in C programming language is − do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false. Flow Diagram

Example #include <stdio.h>

int main () {

/* local variable definition */

int a = 10;

/* do loop execution */

Page 17: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

} When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19

3) What is array? Explain single and multidimensional with examples. Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Single-dimensional Arrays: Declaring Arrays: To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ];

Page 18: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array calledbalance of type double, use this statement − double balance[10]; Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays: You can initialize an array in C either one by one or using a single statement as follows − double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array − balance[4] = 50.0; The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Accessing Array Elements: An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − double salary = balance[9]; The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays − #include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n to 0 */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100; /* set element at location i to i + 100 */

}

Page 19: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

printf("Element[%d] = %d\n", j, n[j] );

}

return 0;

} When the above code is compiled and executed, it produces the following result − Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109

Multidimensional Arrays: C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration − type name[size1][size2]...[sizeN]; For example, the following declaration creates a three dimensional integer array − int threedim[5][10][4];

Two-dimensional Arrays: The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows − type arrayName [ x ][ y ]; Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −

Page 20: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.

Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

}; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the previous example − int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example − int val = a[2][3]; The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above figure. Let us check the following program where we have used a nested loop to handle a two-dimensional array − #include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/

int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

int i, j;

/* output each array element's value */

for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {

printf("a[%d][%d] = %d\n", i,j, a[i][j] );

}

}

return 0;

} When the above code is compiled and executed, it produces the following result − a[0][0]: 0 a[0][1]: 0 a[1][0]: 1

Page 21: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

4) Explain break and continue with example. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C supports the following control statements.

break statement: The break statement in C programming has the following two usages − When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switchstatement (covered in the next chapter). If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax The syntax for a break statement in C is as follows − break; Flow Diagram

Page 22: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Example #include <stdio.h>

int main () {

/* local variable definition */

int a = 10;

/* while loop execution */

while( a < 20 ) {

printf("value of a: %d\n", a);

a++;

if( a > 15) {

/* terminate the loop using break statement */

break;

}

}

return 0;

} When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15

continue statement: The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while anddo...while loops, continue statement causes the program control to pass to the conditional tests.

Syntax The syntax for a continue statement in C is as follows − continue; Flow Diagram

Page 23: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Example #include <stdio.h>

int main () {

/* local variable definition */

int a = 10;

/* do loop execution */

do {

if( a == 15) {

/* skip the iteration */

a = a + 1;

continue;

}

printf("value of a: %d\n", a);

a++;

} while( a < 20 );

return 0;

} When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12

Page 24: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 5) Explain if...else if ..ladder with flowchart. Suppose we need to specify multiple conditions then we need to use multiple if statements like this – void main ( ) { int num = 10 ; if ( num > 0 ) printf ("\n Number is Positive"); if ( num < 0 ) printf ("\n Number is Negative"); if ( num == 0 ) printf ("\n Number is Zero"); } which is not a right or feasible way to write program. Instead of this above syntax we use if-else-if statement. Consider the Following Program – void main ( ) { int num = 10 ; if ( num > 0 ) printf ("\n Number is Positive"); else if ( num < 0 ) printf ("\n Number is Negative"); else printf ("\n Number is Zero"); }

Explanation : In the above program firstly condition is tested i.e number is checked with zero. If it is greater than zero then only first if statement will be executed and after the execution of if statement control will be outside the complete if-else statement. else if ( num < 0 ) printf ("\n Number is Negative"); Suppose in first if condition is false then the second condition will be tested i.e if number is not positive then and then only it is tested for the negative. else

Page 25: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

printf ("\n Number is Zero"); and if number is neither positive nor negative then it will be considered as zero. Which is faster and feasible way for Writing If ? Point Example 1 Example 2 No of If Statements 3 2 No of times Condition Tested (Positive No.)

3 1

No of times Condition Tested (Negative No.)

3 2

No of times Condition Tested (Zero No.)

3 2

6) What is type conversion? Explain implicit type conversion and explicit type conversion with example. Type Casting and Type Conversions : Because C is statically-typed at compile time, after a variable is declared, it cannot be declared again or used to store values of another type unless that type is convertible to the variable's type. For example, there is no conversion from an integer to any arbitrary string. Therefore, after you declare i as an integer, you cannot assign the string "Hello" to it, as is shown in the following code.

Page 26: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

int i; i = "Hello"; // Error: "Cannot implicitly convert type 'string' to 'int'" However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions.

In C#, you can perform the following kinds of conversions: Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

Implicit Conversions: For built-in numeric types, an implicit conversion can be made when the value to be stored can fit into the variable without being truncated or rounded off. For example, a variable of type long (8 byte integer) can store any value that an int (4 bytes on a 32-bit computer) can store. In the following example, the compiler implicitly converts the value on the right to a type long before assigning it to bigNum. C // Implicit conversion. num long can // hold any value an int can hold, and more! int num = 2147483647; long bigNum = num; For a complete list of all implicit numeric conversions, see For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class. Derived d = new Derived(); Base b = d; // Always OK.

Explicit Conversions: However, if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted. The following program casts a doubleto an int. The program will not compile without the cast. class Test { void Main()

Page 27: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

{ double x = 1234.7; int a; // Cast double to int. a = (int)x; PRINTF(a); } } // Output: 1234 7) Define (1) Token (2) Identifier (3) Constant (4) Type casting (5) Storage class (6) Scope and life time of variable. (1) Token: A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens − printf("Hello, World! \n"); The individual tokens are − printf ( "Hello, World! \n" ) ; (2) Identifier: A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal (3) Constant: Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition.

Page 28: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

(4) Type casting: Refer Que. 6. (5) Storage class: A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program − auto register static extern (6) Scope and life time of variable:

Life Time – Life time of any variable is the time for which the particular variable outlives in memory during running of the program.

Scope – The scope of any variable is actually a subset of life time. A variable may be in the memory but may not be accessible though. So, the area of our program where we can actually access our entity (variable in this case) is the scope of that variable.

The scope of any variable can be broadly categorized into three categories :

Global scope : When variable is defined outside all functions. It is then available to all the functions of the program and all the blocks program contains.

Local scope : When variable is defined inside a function or a block, then it is locally accessible within the block and hence it is a local variable.

Function scope : When variable is passed as formal arguments, it is said to have function scope.

8) Explain operator precedence and associativity.

Precedence of operators: If more than one operators are involved in an expression then, C language has predefined rule of priority of operators. This rule of priority of operators is called operator precedence. In C, precedence of arithmetic operators(*,%,/,+,-) is higher than relational operators(==,!=,>,<,>=,<=) and precedence of relational operator is higher than logical operators(&&, || and !). Suppose an expression: (a>b+c&&d) This expression is equivalent to: ((a>(b+c))&&d) i.e, (b+c) executes first then, (a>(b+c)) executes

Page 29: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

then, (a>(b+c))&&d) executes

Associativity of operators: Associativity indicates in which order two operators of same precedence(pri ority) executes. Let us suppose an expression: a==b!=c Here, operators == and != have same precedence. The associativity of both == and != is left to right, i.e, the expression in left is executed first and execution take pale towards right. Thus, a==b!=cequivalent to : (a==b)!=c The table below shows all the operators in C with precedence and associativity. Note: Precedence of operators decreases from top to bottom in the given table.

Summary of C operators with precedence and associativity

Operator Meaning of operator Associativity

() [] -> .

Functional call Array element reference Indirect member selection Direct member selection Left to right

! ~ + - ++ -- & * sizeof (type)

Logical negation Bitwise(1 's) complement Unary plus Unary minus Increment Decrement Dereference Operator(Address) Pointer reference Returns the size of an object Type cast(conversion) Right to left

* / %

Multiply Divide Remainder Left to right

+ -

Binary plus(Addition) Binary minus(subtraction) Left to right

<< >>

Left shift Right shift Left to right

Page 30: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Summary of C operators with precedence and associativity

Operator Meaning of operator Associativity

< <= > >=

Less than Less than or equal Greater than Greater than or equal Left to right

== !=

Equal to Not equal to Left to right

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Left to right

= *= /= %= -= &= ^= |= <<= >>=

Simple assignment Assign product Assign quotient Assign remainder Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift Right to left

, Separator of expressions Left to right

Page 31: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

UNIT: 3 ( Control Structure in C)

1) Explain the multiple (ladder) if-else with syntax and proper example. ORExplain “if ...else...if” ladder of C with neat diagram and a brief program code. If statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if...else if..else statements, there are few points to keep in mind − An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax

The syntax of an if...else if...else statement in C programming language is − if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ }

Example #include <stdio.h> #include<conio.h> int main () { int a = 100; if( a == 10 ) { printf("Value of a is 10\n" ); } else if( a == 20 ) { printf("Value of a is 20\n" ); } else if( a == 30 ) { printf("Value of a is 30\n" ); } else {

Page 32: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

printf("None of the values is matching\n" ); } printf("Exact value of a is: %d\n", a ); return 0; } Output: None of the values is matching Exact value of a is: 100

2) Which among the following is a unconditional control structure.a) goto b) for c) do-while d) if-else a)Goto 3) Write a C Program to check whether the given number is prime or not. #include<stdio.h> #include<conio.h> int main() { int num,i,count=0; printf("Enter a number: "); scanf("%d",&num); for(i=2;i<=num/2;i++){ if(num%i==0){ count++; break; } } if(count==0 && num!= 1) printf("%d is a prime number",num); else printf("%d is not a prime number",num); return 0; } output: Enter a number: 5 5 is a prime number

Page 33: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

4) What is looping? Explain different types of loops in C and compare them.Show how to sum 1 to 10 using each of these loops. A loop statement allows us to execute a statement or group of statements multiple times. The general form of a loop statement is shown below.

a)while loop : A while loop in C programming repeatedly executes a target statement as long as a given condition is true. Syntax The syntax of a while loop in C programming language is − while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. Flow Diagram

Page 34: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example #include <stdio.h>

int main () {

int a = 10;

while( a < 20 ) {

printf("value of a: %d\n", a);

a++;

}

return 0;

} Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19

Page 35: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

b)do while loop A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. Syntax The syntax of a do...while loop in C programming language is − do { statement(s); } while( condition ); The conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false. Flow Diagram

Example #include <stdio.h>

int main () {

int a = 10;

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

Page 36: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

} Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 c) for loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax The syntax of a for loop in C programming language is − for ( init; condition; increment ) { statement(s); } Here is the flow of control in a 'for' loop − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates. Flow Diagram

Page 37: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Example #include <stdio.h>

int main () {

int a;

for( a = 10; a < 20; a = a + 1 ){

printf("value of a: %d\n", a);

}

return 0;

} Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19

Page 38: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

C Program to sum 1 to 10 Numbers

Using For Loop #include<stdio.h> #include<conio.h> void main() { int i = 1,sum=0; for (i = 1; i <= 10; i++) { sum=sum+i; } printf("%d", sum); getch(); } Using While Loop #include<stdio.h> #include<conio.h> void main() { int i = 1,sum=0; while (i <= 10) { sum=sum+i; i++; } printf("%d", sum); getch(); }

Using Do While Loop #include<stdio.h> #include<conio.h> void main() { int i = 1,sum=0; do { sum=sum+i; i++; } while (i <= 10); printf("%d",sum); getch();

Page 39: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

UNIT:4 (Array and String) 1) What is array? What are the advantages to use array? Explain single and multi-dimensional array with example. Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Advantages: 1. It is used to represent multiple data items of same type by using only single name. 2. It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc. 3. 2D arrays are used to represent matrices.

Single Dimensional Array:

The declaration form of one-dimensional array is Data_type array_name [size]; The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is numbers[0] and the last is numbers[4]. int numbers [5]; numbers [0] = 1; // set first element numbers [4] = 5; // set last element This array contains 5 elements. Any one of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([]). The first element in every array is the zeroth element.Thus, the first element of

Page 40: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

array ‘numbers’is referred to as numbers[ 0 ], the second element of array ‘numbers’is referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred to as numbers[ 4 ], and, in general, the n-th element of array ‘numbers’is referred to as numbers[ n - 1 ].

Example:

#include<stdio.h> #include<conio.h> void main() { int arr[10]; int i,sum=0,avg=0; clrscr(); for(i=0;i<10;i++) { scanf("%d",&arr[i]); sum = sum + arr[i]; } printf("\n Sum of array elements = %d",sum); avg = sum/10; printf("\n Average = %d",avg); getch(); }

Multi dimensional array: The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows − type arrayName [ x ][ y ]; Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −

Page 41: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Thus, every element in the array a is identified by an element name of the forma[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.

Example:

#include<stdio.h> int main() { int m,n,c,d,first[10][10],second[10][10],sum[10][10]; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrix\n"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the elements of second matrix\n"); for (c = 0; c < m; c++) for (d = 0 ; d < n; d++) scanf("%d", &second[c][d]); printf("Sum of entered matrices:-\n"); for (c = 0; c < m; c++) { for (d = 0 ; d < n; d++) { sum[c][d] = first[c][d] + second[c][d]; printf("%d\t", sum[c][d]); } printf("\n"); } return 0; }

2) Describe various string handling operation using sample ‘C’ codes. (1)strlen():

Page 42: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

strlen() function returns the length of the string. strlen() function returns integer value.

Syntax: strlen(s) Example: #include <stdio.h>

#include <string.h>

int main(){

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m','\0'};

char c[20];

printf("Enter string: ");

gets(c);

printf("Length of string a=%d \n",strlen(a));

//calculates the length of string before null charcter.

printf("Length of string b=%d \n",strlen(b));

printf("Length of string c=%d \n",strlen(c));

return 0;

}

(2)strcpy(): strcpy() function is used to copy one string to another. The Destination_String should be a variable and Source_String can either be a string constant or a variable. Syntax: strcpy(Destination_String,Source_String);

Example:

#include <stdio.h>

#include <string.h>

int main(){

char a[10],b[10];

printf("Enter string: ");

gets(a);

strcpy(b,a); //Content of string a is copied to string b.

printf("Copied string: ");

puts(b);

return 0;

} (3)strcat(): strcat() is used to concatenate two strings. The Destination_String should be a variable and Source_String can either be a string constant or a variable.

Page 43: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Syntax: strcat(Destination_String, Source_String);

Example:

#include <stdio.h>

#include <string.h>

int main(){

char str1[]="This is ",

str2[]="programiz.com";

strcat(str1,str2);

//concatenates str1 and

str2 and resultant string is

stored in str1.

puts(str1);

puts(str2);

return 0;

}

(4)strcmp(): strcmp() function is use two compare two strings. strcmp() function does a case sensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.

Syntax: int strcmp(string1, string2); This function returns integer value after comparison. Value returned is 0 if two strings are equal. If the first string is alphabetically greater than the second string then, it returns a positive value. If the first string is alphabetically less than the second string then, it returns a negative value

Example: #include <stdio.h>

#include <string.h>

int main(){

char str1[30],str2[30];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

if(strcmp(str1,str2)==0)

printf("Both strings are equal");

Page 44: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

else

printf("Strings are unequal");

return 0;

}

(5)strcmpi(): strcmpi() function is use two compare two strings. strcmp() function does a case insensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.

Syntax: int strcmpi(string1, string2); This function returns integer value after comparison. Example:

char *string1 = “Learn C Online”; char *string2 = “LEARN C ONLINE”; int ret ret=strcmpi(string1, string2); printf("%d",ret); (6) strlwr(): In C programming, strlwr() function converts all the uppercase characters in that string to lowercase characters. The resultant from strlwr() is stored in the same string.

Syntax: strlwr(string_name); Example: #include <stdio.h> #include <string.h> int main(){ char str1[]="LOWer Case"; puts(strlwr(str1)); //converts to lowercase and displays it. return 0; } (7) strupr():

Page 45: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

In C programming, strupr() function converts all the lowercase characters in that string to uppercase characters. The resultant from strupr() is stored in the same string.

Syntax: strupr(string_name); Example: #include <stdio.h>

#include <string.h>

int main(){

char str1[]="UppEr Case";

puts(strupr(str1)); //Converts to uppercase and displays it.

return 0;

}

3) What is a string? How string is stored in C? Give the various functions with their use for string processing. A string in C is merely an array of characters. The length of a string is determined by a terminating null character: '\0' . So, a string with the contents, say, "abc" has four characters: 'a' , 'b' , 'c' , and the terminatingnull character. The terminating null character has the value zero. A string stored is “COMPUTER”,which is having only 8 characters,but actually 9 characters are Stored because of NULL character at the end. Char name[20]; This line declares an array name of characters of size 20.we can store any string up to maximum lengh 19. String is basically an array of characters,so we can initialize the string by using the method of initializing the method of initializing the single dimensional array as shown below. Char name[] = {‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’}; OR Char name[] =”COMPUTER”; When the string is written in double quotes,the NULL character is not required,it is automatically taken. (1)strlen(): strlen() function returns the length of the string. strlen() function returns integer value.

Syntax: strlen(s)

Page 46: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Example: #include <stdio.h>

#include <string.h>

int main(){

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m','\0'};

char c[20];

printf("Enter string: ");

gets(c);

printf("Length of string a=%d \n",strlen(a));

//calculates the length of string before null charcter.

printf("Length of string b=%d \n",strlen(b));

printf("Length of string c=%d \n",strlen(c));

return 0;

}

(2)strcpy(): strcpy() function is used to copy one string to another. The Destination_String should be a variable and Source_String can either be a string constant or a variable. Syntax: strcpy(Destination_String,Source_String); Example:

#include <stdio.h>

#include <string.h>

int main(){

char a[10],b[10];

printf("Enter string: ");

gets(a);

strcpy(b,a); //Content of string a is copied to string b.

printf("Copied string: ");

puts(b);

return 0;

} (3)strcat(): strcat() is used to concatenate two strings. The Destination_String should be a variable and Source_String can either be a string constant or a variable.

Page 47: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Syntax: strcat(Destination_String, Source_String); Example:

#include <stdio.h>

#include <string.h>

int main(){

char str1[]="This is ",

str2[]="programiz.com";

strcat(str1,str2);

//concatenates str1 and

str2 and resultant string is

stored in str1.

puts(str1);

puts(str2);

return 0;

}

(4)strcmp(): strcmp() function is use two compare two strings. strcmp() function does a case sensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable. Syntax: int strcmp(string1, string2); This function returns integer value after comparison. Value returned is 0 if two strings are equal. If the first string is alphabetically greater than the second string then, it returns a positive value. If the first string is alphabetically less than the second string then, it returns a negative value Example: #include <stdio.h>

#include <string.h>

int main(){

char str1[30],str2[30];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

if(strcmp(str1,str2)==0)

printf("Both strings are equal");

else

printf("Strings are unequal");

return 0;

}

Page 48: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

(5)strcmpi(): strcmpi() function is use two compare two strings. strcmp() function does a case insensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable. Syntax: int strcmpi(string1, string2); This function returns integer value after comparison. Example:

char *string1 = “Learn C Online”; char *string2 = “LEARN C ONLINE”; int ret ret=strcmpi(string1, string2); printf("%d",ret); (6) strlwr(): In C programming, strlwr() function converts all the uppercase characters in that string to lowercase characters. The resultant from strlwr() is stored in the same string. Syntax: strlwr(string_name); Example: #include <stdio.h> #include <string.h> int main(){ char str1[]="LOWer Case"; puts(strlwr(str1)); //converts to lowercase and displays it. return 0; } (7) strupr(): In C programming, strupr() function converts all the lowercase characters in that string to uppercase characters. The resultant from strupr() is stored in the same string. Syntax: strupr(string_name);

Page 49: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Example: #include <stdio.h>

#include <string.h>

int main(){

char str1[]="UppEr Case";

puts(strupr(str1)); //Converts to uppercase and displays it.

return 0;

}

Page 50: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

UNIT:5 (Function)

1) What is function? Explain “Pass by value “and “Pass by reference”. Give one-one example of User Defined Function and Library Function. Function is a group of statements as a single unit known by some name which is performing some well defined task.

The syntax for function declaration is : type function_name(argument(s)); Here,type specifies the type of value returned,function_name specifies name of user defined function, and argument(s) specifies the arguments supplied to the function as comma separated list of variables. The declaration of function is terminated by semicolon (;) symbol. When a function is called from other function,the parameters can be passed in two ways.

Call By Value

Call By Reference In call By Value,argument values are passed to the function,the contents of actual parameters are copied into the formal parameters.The function called function can not change the values of variables which are passed.Even if a function tries to change the values of passed parameters,those changes will occur in formal parameters,not in actual parameters.

Example: #include<conio.h> void sum(int a , int b); main() { int i,j; clrscr(); printf(“Give two integer numbers\n”); scanf(“%d %d”,&I,&j); sum(i,j); } void sum(int a,int b) { int c; c=a+b; printf(“Sum of %d and %d=%d\n”,a,b,c); } Output:

Page 51: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Give two integer numbers 2 3 Sum of 2 and 3=5 Void sum(int a,int b); declaration says that sum function takes two values but does not return any value.Program shows function with arguments but no return value. Sum(I,j); indicates that function calls by value.

In Call By Reference,as the name suggests,the reference of the parameter i.e. address(pointer) is passed to the function and not the value.Because pointer is passed,the called function can change the content of the actual parameter passed.Call by reference is used whenever we want to change the value of local variables declared in one function to be changed by other function.

#include<conio.h> int add(int*,int*); //Function prototyping void main() { int num1, num2, result; clrscr(); //This inbuilt function clears the screen /*Accept the numbers from the user*/ printf("\nEnter the two number: "); scanf("%d %d", &num1, &num2); /* Pass the value of num1 and num2 as parameter to function add. The value returned is stored in the variable result */ result = add(&num1, &num2); printf("\nAddition of %d and %d is %d", num1, num2, result); getch(); } /*Defining the function add()*/ int add(int *no1, int *no2) { int res; res = *no1 + *no2;

Page 52: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

return res; } 2) Write short note on Categories of Functions. Following are thetype in functions:

Function with no arguments and no return value

Function with no arguments and return value

Function with arguments but no return value

Function with arguments and return value. Let's take an example to find whether a number is prime or not using above 4 categories of user defined functions.

Function with no arguments and no return value. /*C program to check whether a number entered by user is prime or not using function with no arguments and no return value*/ #include <stdio.h> void prime(); int main(){ prime(); //No argument is passed to prime(). return 0; } void prime(){ /* There is no return value to calling function main(). Hence, return type of prime() is void */ int num,i,flag=0; printf("Enter positive integer enter to check:\n"); scanf("%d",&num); for(i=2;i<=num/2;++i){ if(num%i==0){ flag=1; } } if (flag==1) printf("%d is not prime",num); else printf("%d is prime",num); } Function prime() is used for asking user a input, check for whether it is prime of not and display it accordingly. No argument is passed and returned form prime() function. Function with no arguments but return value /*C program to check whether a number entered by user is prime or not using function with no arguments but having return value */

Page 53: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

#include <stdio.h> int input(); int main(){ int num,i,flag = 0; num=input(); /* No argument is passed to input() */ for(i=2; i<=num/2; ++i){ if(num%i==0){ flag = 1; break; } } if(flag == 1) printf("%d is not prime",num); else printf("%d is prime", num); return 0; } int input(){ /* Integer value is returned from input() to calling function */ int n; printf("Enter positive integer to check:\n"); scanf("%d",&n); return n; } There is no argument passed to input() function But, the value of n is returned from input() tomain() function.

Function with arguments and no return value /*Program to check whether a number entered by user is prime or not using function with arguments and no return value */ #include <stdio.h> void check_display(int n); int main(){ int num; printf("Enter positive enter to check:\n"); scanf("%d",&num); check_display(num); /* Argument num is passed to function. */ return 0; } void check_display(int n){ /* There is no return value to calling function. Hence, return type of function is void. */ int i, flag = 0; for(i=2; i<=n/2; ++i){ if(n%i==0){

Page 54: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

flag = 1; break; } } if(flag == 1) printf("%d is not prime",n); else printf("%d is prime", n); } Here, check_display() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to user-defined function but, value is not returned from it to calling function.

Function with argument and a return value /* Program to check whether a number entered by user is prime or not using function with argument and return value */ #include <stdio.h> int check(int n); int main(){ int num,num_check=0; printf("Enter positive enter to check:\n"); scanf("%d",&num); num_check=check(num); /* Argument num is passed to check() function. */ if(num_check==1) printf("%d is not prime",num); else printf("%d is prime",num); return 0; } int check(int n){ /* Integer value is returned from function check() */ int i; for(i=2;i<=n/2;++i){ if(n%i==0) return 1; } return 0; }

Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned.

Page 55: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

#include <stdio.h> #include <conio.h> max(int [],int); void main() { int a[]={10,5,45,12,19}; int n=5,m; clrscr(); m=max(a,n); printf("\nMAXIMUM NUMBER IS %d",m); getch(); } max(int x[],int k) { int t,i; t=x[0]; for(i=1;i<k;i++) { if(x[i]>t) t=x[i]; } return(t); } Output : MAXIMUM NUMBER IS 45 3) What do you mean by recursive function? Explain with example. Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. The standard recursive function for factorial is factorial=n*fact(n-1). factorial of number denoted by '!', means product of all non negative integers from 1 to number. example: 5!=5*4*3*2*1=120.

Advantages:

Easy solution for recursively defined problems.

Complex programs can be easily written in less code.

Disadvantages:

Recursive code is difficult to understand and debug.

Terminating condition is must,otherwise it will go in infinite loop.

Execution speed decreases because of function call and return activity many times.

#include<stdio.h>

Page 56: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

int factorial(int); void main() { int num; printf("Enter the number to calculate Factorial :"); scanf("%d",&num); printf("\nFactorial : %d", factorial (num)); } int factorial (int i) { int f; if(i==1) return 1; else f = i* factorial (i-1); return f; } 4 ) What is user-defined function? Explain Actual argument and formal argument User defined functions are created for doing some specific task in a program.The code is written as one unit having a name.As the size of program increases,it becomes difficult to understand,debug and maintain it.If we write the code in main() function only. When some portion of the code is repeated in the program and when there is a definite purpose of the code,we can write that part of the code as a function.So,use of function reduces the size and compklexity of the program.The code of the function is written only once in the program and called for any number of times from whenever required. Formal arguments are the arguments which are used in the definition of a function,while actual parameters are the arguments which are used while calling a function.

Following example explains formal and actual arguments using user defined max function.

#include<stdio.h> #include<conio.h> Int max(int x,int y) { If(x>y) Return x; else return y; }

Page 57: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

main() { int a=5,b=3; int ans; ans=max(a,b); printf(“Maximum =%d\n”,ans); } In above program,x and y are formal parameters,while a and b are actual parameters.

Page 58: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

UNIT 6 & 7 : (Pointer & structure)

1 ) What is pointer? How Pointer is initialized? How it is different to array? A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.

The general form of a pointer variable declaration is:

type *variable_name; Here, type is the pointer's base type; it must be a valid C data type and variable_name is the name of the pointer variable. Here, the asterisk is used to designate a variable as a pointer variable.

Initialization of pointers: Pointer Initialization is the process of assigning address of a variable to pointer variable. First of all declare a Pointer Variable. Declare another Variable with Same Data Type as that of Pointer Variable. Now Initialize pointer by assigning the address of ordinary variable to pointer variable.

For example: #include<stdio.h> void main() { int a; int *ptr; a = 10; ptr = &a; }

Difference between array and pointer:

Array is a collection of variables; whereas pointer is a variable which stores the address of other variable. At the same time, we can have a pointer pointing to an array and an array of pointer variables. In arrays of C programming, name of the array always points to the first element of an array. 2 ) Write short note on Pointer. A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.

Page 59: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

The general form of a pointer variable declaration is: type *variable_name; Here, type is the pointer's base type; it must be a valid C data type and variable_name is the name of the pointer variable. Here, the asterisk is used to designate a variable as a pointer.

Initialization of a pointer variable can be done by by assigning the address of ordinary variable to pointer variable. e.g. int i =5; int *p; //declares p as pointer to integer p = &i; // p is assigned the address of int variable i.

Advantages of pointer:

It is the only way to express some computations.

It produces compact and efficient code.

It provides a very powerful tool.

C uses pointers explicitly with Arrays,structures and functions. 3) What is structure? Define the structure and explain how to access the structure members.

C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds. Declaration of structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this Struct books { char title[50]; char author[50] char subject[100]; int book_id[10]; }book;

Accessing a structure variable: To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type.

Page 60: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

For example to access variable of structure Books we can access it using dot operator. book.title=”Computer programming” 4) Give one example for Array of structure explain the meaning. Define an array of structure with integer, string and float as members.

C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas, array of structures is nothing but collection of structures. This is also called as structure array in C. Example of array of structure: #include <stdio.h> struct student{ char name[50]; int roll; float marks; }; int main() { struct student s[10]; int i; printf("Enter information of students:\n"); for(i=0;i<10;++i) { s[i].roll=i+1; printf("\nFor roll number %d\n",s[i].roll); printf("Enter name: "); scanf("%s",s[i].name); printf("Enter marks: "); scanf("%f",&s[i].marks); printf("\n"); } printf("Displaying information of students:\n\n"); for(i=0;i<10;++i) { printf("\nInformation for roll number %d:\n",i+1); printf("Name: "); puts(s[i].name); printf("Marks: %.1f",s[i].marks); } return 0; } Here,a structure(student) is created which contains name, roll and marks as its data member. Then, an array of structure of 10 elements is created. Then, data(name, roll and marks) for 10 elements is asked to user and stored in array of structure. Finally, the data entered by user is displayed.

Page 61: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

UNIT 8 & 9 : (DYNAMIC MEMORY ALLOCATION AND FILE MANAGEMENT)

1). What is dynamic memory allocation? Show the use of the malloc() and calloc() function. What is the difference between malloc() and calloc() function. Answer: Dynamic memory allocation refers to the memory allocation at runtime but static allocation declaration is done at compile time.

Static memory allocation is the one in which the memory requirement is known in advance. So the compiler will allocate the required memory space for a declared variable. But this method will fail when we don’t know the memory requirements at the time of writing the program. For example, if exact size of array is unknown until the compile time, i.e., time when a compiler compiles code written in a programming language into a executable form. The size of array you have declared initially can be sometimes insufficient and sometimes more than required.

Hence, C provides a method of memory allocation known as Dynamic Memory allocation where the memory allocation is done at run time. Whenever memory is required to store the data it is directly allocated by operating system and not by compiler. It allows a program to obtain more memory space, while running or to release space when no space is required.

Advantages of Dynamic memory Allocation over Static memory allocation:

Memory Allocation at Run time

No wastage of space

The memory blocks which are no longer required can be made free

Faster Speed

Data can be rearranged efficiently.

The important library functions under "stdlib.h" library for dynamic memory allocation are explained in following table:

Function Use of Function

malloc()

Allocates requested size of bytes and returns a pointer to first byte of allocated space

calloc()

Allocates space for an array elements, initializes to zero and then returns a pointer to memory

free() Deallocate the previously allocated space

realloc() Change the size of previously allocated space

sizeof() Returns the number of bytes required to store a specified data type of variable.

malloc()

Page 62: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. The prototype of malloc is void *malloc(int);

Syntax of malloc(): ptr=(cast-type*)malloc(size) Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of size. If the space is insufficient, allocation fails and returns NULL pointer. Example (for storing integer): int *ptr; ptr=(int *)malloc(sizeof(int)); This statement will allocate space for storing a integer in memory and the pointer ptr points to the address of first byte of memory.

calloc() The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.

Syntax of calloc(): ptr=(cast-type *)calloc(n,element-size); This statement will allocate contiguous space in memory for an array of n elements. Example: int *ptr; ptr=(float*)calloc(25,sizeof(float)); This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. 2). Explain the use of malloc and calloc function with their syntax. Answer:

malloc() The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. The prototype of malloc is void *malloc(int); Syntax of malloc(): ptr=(cast-type*)malloc(size) Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of size. If the space is insufficient, allocation fails and returns NULL pointer. Example (for storing integer): int *ptr;

Page 63: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

ptr=(int *)malloc(sizeof(int)); This statement will allocate space for storing a integer in memory and the pointer ptr points to the address of first byte of memory.

calloc() The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. Syntax of calloc(): ptr=(cast-type *)calloc(n,element-size); This statement will allocate contiguous space in memory for an array of n elements. Example: int *ptr; ptr=(float*)calloc(25,sizeof(float)); This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. 3). What is file management? List different file management functions and explain the various file modes. Write Short note on File operations in C. Answer: C language provides facility of file input-output operations. The standard library in C has many file I/O functions. File management functions

Function Name Operation

fopen() Creates a new file for use.Opens a new existing file for use

fclose Closes a file which has been opened for use

fgetc() Reads a character from a file

fputc() Writes a character to a file

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

fgets() Reads a integer from a file

fputs() Writes an integer to the file

fseek() Sets the position to a desired point in the file

ftell() Gives the current position in the file

rewind() Sets the position to the begining of the file

Following is the sequence of steps for operating file:

Naming a file

Open file

Read or Write to file

Close file

Page 64: CPU Unit Wise IMP Questions Answers for GTU · PDF file... Explain various symbols used in Flowchart and draw the flowchart for finding Factorial of a number ... to increase the value

Defining and opening a file: File is a collection of data known by some name. A file has name possibly with extension. If file doesn’t exist we have to create it. Every file has a name. e.g. rajkot.doc, student.txt. In C, file is defined of type FILE(like int for storing integer numbers). Hence, all files should be declared as type FILE before they are used. The general format of the function used for declaring and opening a file is FILE *fp; fp=fopen(“filename”,”mode”); The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program. The second statement also specifies the purpose of opening the file. The mode does this job.

The “mode” in fopen function can contain any of the following modes:

r - open for reading

w - open for writing (file need not exist)

a - open for appending (file need not exist)

r+ - open for reading and writing, start at beginning

w+ - open for reading and writing (overwrite file)

a+ - open for reading and writing (append if file exists)

Closing a file: The input output library supports the function to close a file; it is in the following format. fclose(file_pointer); A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. Observe the following program. …. FILE *p1 *p2; p1=fopen (“Input”,”w”); p2=fopen (“Output”,”r”); …. … fclose(p1); fclose(p2) The above program opens two files and closes them after all operations on them are completed.