Programming and Data Structures

Size: px
Start display at page:

Download "Programming and Data Structures"

Transcription

1 Programming and Data Structures Document Prepared By: Dr. Subhankar Joardar (H.O.D.) Mrs. Gitika Maity (Asst.Prof.) Mrs. Patrali Pradhan (Asst.Prof.) Mrs. Sunanda Jana (Asst.Prof.) Mrs. Rajrupa Metia (Asst.Prof.) COMPUTER SCIENCE & ENGINEERING DEPARTMENT

2 Programming and Data Structures: Content: 1. Programming in C. 2. Recursion. 3. Arrays. 4. Stacks. 5. Queues. 6. Linked lists. 7. Trees. 8. Binary search trees. 9. Graphs.

3 Programming in C. INTRODUCTION C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973.It was mainly developed as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. Many later languages have borrowed syntax/features directly or indirectly from C language. Like syntax of Java, PHP, JavaScript and many other languages is mainly based on C language. C++ is nearly a superset of C language (There are few programs that may compile in C, but not in C++). Beginning with C programming: Finding a Compiler: Before we start C programming, we need to have a compiler to compile and run our programs. Windows: There are many compilers available freely for compilation of C programs like Code Blocks, Turbo C++. We strongly recommend Code Blocks. Linux: For Linux, gcc comes bundled with the linux, Code Blocks can also be used with Linux. For the C program: All C programs must have a function in it called main Execution starts in function main C is case sensitive Comments start with /* and end with */. Comments may span over many lines. C is a free format language All C statements must end in a semicolon (;). The #include <stdio.h> statement instructs the C compiler to insert the entire contents of file stdio.h in its place and compile the resulting file. Writing first program: Following is first program in C #include <stdio.h>

4 int main(void) printf( hello ); return 0; Output: Let us analyze the program line by line. Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by preporcessor which is a program invoked by the compiler. In a very basic term, preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, preprocessor copies the preprocessed code of stdio.h to our file. The.h files are called header files in C. These header files generally contain declaration of functions. We need stdio.h for the function printf() used in the program. Line 2 [ int main(void) ] There must to be starting point from where execution of compiled C program begins. In C, the execution typically begins with first line of main(). The void written in brackets indicates that the main doesn t take any parameter. main() can be written to take parameters also. We will be covering that in future posts. The int written before main indicates return type of main(). The value returned by main indicates status of program termination Line 3 and 6: [ and ] In C language, a pair of curly brackets define a scope and mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets. Line 4 [ printf( hello ); ] printf() is a standard library function to print something on standard output. The semiolon at the end of printf indicates line termination. In C, semicolon is always used to indicate end of statement. Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by operating system to know termination status of your program. The value 0 typically means successful termination.

5 KEYWORDS: Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one! There are a total of 32 keywords in C: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Most of these keywords have already been discussed in the various sub-sections of the C language, like Data Types, Storage Classes, Control Statements, Functions etc. Let us discuss some of the other keywords which allow us to use the basic functionality of C: const: const can be used to declare constant variables. Constant variables are variables which when initialized, can t change their value. Or in other words, the value assigned to them is unmodifiable. Syntax: const data_type var_name = var_value; Note: Constant variables need to be compulsorily be initialized during their declaration itself. const keyword is also used with pointers. extern: extern simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can me made extern as well by placing the extern keyword before its declaration/definition in any function/block. This basically signifies that we are not

6 initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. Syntax: extern data_type var_name = var_value; static: static keyword is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler. Syntax: static data_type var_name = var_value; void: void is a special data type only. But what makes it so special? void, as it literally means an empty data type. It means it has nothing or it holds no value. For example, when it is used as the return data type for a function, it simply represents that the function returns no value. Similarly, when it is added to a function heading, it represents that the function takes no arguments. Note: void also has a significant use with pointers. typedef: typedef is used to give a new name to an already existing or even a custom data type (like a structure). It comes in very handy at times, for example in a case when the name of the structure defined by you is very long or you just need a short-hand notation of a per-existing data type. VARIABLE A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable s memory. The range of values that can be stored within that memory and the set of operations that can be applied to the variable.

7 C Variable Type A variable is just a named area of storage that can hold a single value. There are two main variable types: Local variable and Global variable. Local Variable: Scope of a local variable is confined within the block or function, where it is defined. Global Variable: Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initialized automatically by the system when we define them. If same variable name is being used for global and local variables, then local variable takes preference in its scope. Storage Classes in C A variable name identifies some physical location within the computer, where the string of bits representing the variable s value, is stored. There are basically two kinds of locations in a computer, where such a value maybe kept: Memory and CPU registers. It is the variable s storage class that determines in which of the above two types of locations, the value should be stored. We have four types of storage classes in C: Auto, Register, Static and Extern. 1. Auto Storage Class: Features of this class are given below. Storage Location Memory Default Initial Value Garbage value Scope Local to the block in which the variable is defined. Life Till the control remains within the block in which variable is defined. Auto is the default storage class for all local variables. int mount; auto int month;

8 2. Register Storage Class: Register is used to define local variables that should be stored in a register instead of RAM. Register should only be used for variables that require quick access such as counters. Features of register storage class are given below. Storage Location CPU register Default Initial Value Garbage value Scope Local to the block In which variable is defined. Life Till the control remains within the block in which the variable is defined. register int miles; 3. Static Storage Class: Static is the default storage class for global variables. Features of static storage class are given below. Storage Location Memory Default Initial Value Zero Scope Local to the block in which the variable is defined. In case of global variable, the scope will be through out the program. Life Value of variable persists between different function calls. #include <stdio.h> /* function declaration */ void func(void); static int count = 5; /* global variable */

9 main() while(count--) func(); return 0; Whe the a o e ode is o piled a d e e uted, it p odu es the follo i g esult i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0 4. Extern Storage Class: Extern is used of give a reference of a global variable that is variable to all the program files. When we use extern, the variable can t be initialized as all it does, is to point the variable name at a storage location that has been previously defined. Storage Location: Memory Default Initial Value: Zero Scope: Global Life: As long as the program s execution does not come to an end. #include <stdio.h> int count ; extern void write_extern();

10 main() count = 5; write_extern(); #include <stdio.h> extern int count; void write_extern(void) printf( count is %d\n, count); count is 5 Data Types A data type in a programming language is a set of data with values having predefined characteristics such as integers and characters. Different Types of Modifier with their Range: Type Conversions Implicit Type Conversion: There are certain cases in which data will get automatically converted from one type to another.when data is being stored in a variable, if the data being stored does not match the type of the variable.the data being stored will be converted to match the type of the storage variable.

11 When an operation is being performed on data of two different types. The smaller data type will be converted to match the larger type.the following example converts the value of x to a double precision value before performing the division. Note that if the 3.0 were changed to a simple 3, then integer division would be performed, losing any fractional values in the result. average = x / 3.0;When data is passed to or returned from functions. Explicit Type Conversion: Data may also be expressly converted, using the typecast operator. The following example converts the value of x to a double precision value before performing the division. ( y will then be implicitly promoted, following the guidelines listed above. average = ( double ) x / y; Note that x itself is unaffected by this conversion. Expression: lvalue: Expressions that refer to a memory location are called lvalue expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment. Variables are lvalues and so they may appear on the left-hand side of an assignment rvalue: The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Types of Operators: Arithmetic operators (+, -, *, /, %, ++, ) Assignment operator (=, +=, -=, *=, etc) Relational operators (<, <=, >, >=,!=, ==) Logical operators (&&,,!) Bitwise operators (&,, ~, ^, <<, >>)

12 Special operators (sizeof(), ternary operators) Pointer operators (* Value at address (indirection), & Address Operator) Example Try the following example to understand all the arithmetic operators available in C: #include main() int a = 21; int b = 10; int c ; c = a + b; printf( Line 1 - Value of c is %d\n, c ); c = a - b; printf( Line 2 - Value of c is %d\n, c ); c = a * b; printf( Line 3 - Value of c is %d\n, c ); c = a / b; printf( Line 4 - Value of c is %d\n, c ); c = a % b; printf( Line 5 - Value of c is %d\n, c ); c = a++; printf( Line 6 - Value of c is %d\n, c ); c = a--; printf( Line 7 - Value of c is %d\n, c ); When you compile and execute the above program, it produces the following result: Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 Line 6 - Value of c is 21

13 Line 7 - Value of c is 22 Example Try the following example to understand all the relational operators available in C: #include main() int a = 21; int b = 10; int c ; if( a == b ) rintf( Line 1 - a is equal to b\n ); Else printf( Line 1 - a is not equal to b\n ); if ( a < b ) printf( Line 2 - a is less than b\n ); else printf( Line 2 - a is not less than b\n ); if ( a > b ) printf( Line 3 - a is greater than b\n ); else

14 printf( Line 3 - a is not greater than b\n ); /* Lets change value of a and b */ a = 5; b = 20; if ( a <= b ) printf( Line 4 - a is either less than or equal to b\n ); if ( b >= a ) printf( Line 5 - b is either greater than or equal to b\n ); When you compile and execute the above program, it produces the following result: Line 1 - a is not equal to b Line 2 - a is not less than b Line 3 - a is greater than b Line 4 - a is either less than or equal to b Line 5 - b is either greater than or equal to b Example Try the following example to understand all the logical operators available in C: #include main() int a = 5; nt b = 20;

15 int c ; if ( a && b ) printf( Line 1 - Condition is true\n ); if ( a b ) printf( Line 2 - Condition is true\n ); /* lets change the value of a and b */ a = 0; b = 10; if ( a && b ) printf( Line 3 - Condition is true\n ); else printf( Line 3 - Condition is not true\n ); if (!(a && b) ) printf( Line 4 - Condition is true\n ); When you compile and execute the above program, it produces the following result:

16 Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true Bitwise Operators Bitwise operators work on bits and perform bit-by-bit operation. Assume A = 60 and B = 13; in binary format, they will be as follows: A = B = C. A&B = A B = A^B = ~A = Assume variable A holds 60 and variable B holds 13, AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.e., Binary OR Operator copies a bit if it exists in either operand. (A B) = 61, i.e., ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., ~ Binary Ones Complement Operator is unary and has the effect of flipping bits. (~A ) = -61, i.e., in 2 s complement form. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 = 240, i.e., >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 = 15, i.e., Example Try the following example to understand all the bitwise operators available in C: #include main() unsigned int a = 60; /* 60 = */ unsigned int b = 13; /* 13 = */ int c = 0; c = a & b; /* 12 = */ printf( Line 1 - Value of c is %d\n, c ); c = a b; /* 61 = */ printf( Line 2 - Value of c is %d\n, c ); c = a ^ b; /* 49 = */

17 printf( Line 3 - Value of c is %d\n, c ); c = ~a; /*-61 = */ printf( Line 4 - Value of c is %d\n, c ); c = a << 2; /* 240 = */ printf( Line 5 - Value of c is %d\n, c ); c = a >> 2; /* 15 = */ printf( Line 6 - Value of c is %d\n, c ); When you compile and execute the above program, it produces the following result: Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15 Example Try the following example to understand all the assignment operators available in C: #include main() int a = 21; int c ; c = a; printf( Line 1 - = Operator Example, Value of c = %d\n, c );

18 c += a; printf( Line 2 - += Operator Example, Value of c = %d\n, c ); c -= a; printf( Line 3 - -= Operator Example, Value of c = %d\n, c ); c *= a; printf( Line 4 - *= Operator Example, Value of c = %d\n, c ); c /= a; printf( Line 5 - /= Operator Example, Value of c = %d\n, c ); c = 200; c %= a; printf( Line 6 - %= Operator Example, Value of c = %d\n, c ); c <<= 2; printf( Line 7 - <<= Operator Example, Value of c = %d\n, c ); c >>= 2; printf( Line 8 - >>= Operator Example, Value of c = %d\n, c ); c &= 2; printf( Line 9 - &= Operator Example, Value of c = %d\n, c ); c ^= 2; printf( Line 10 - ^= Operator Example, Value of c = %d\n, c ); c = 2; printf( Line 11 - = Operator Example, Value of c = %d\n, c ); When you compile and execute the above program, it produces the following result: Line 1 - = Operator Example, Value of c = 21 Line 2 - += Operator Example, Value of c = 42 Line 3 - -= Operator Example, Value of c = 21

19 Line 4 - *= Operator Example, Value of c = 441 Line 5 - /= Operator Example, Value of c = 21 Line 6 - %= Operator Example, Value of c = 11 Line 7 - <<= Operator Example, Value of c = 44 Line 8 - >>= Operator Example, Value of c = 11 Line 9 - &= Operator Example, Value of c = 2 Line 10 - ^= Operator Example, Value of c = 0 Line 11 - = Operator Example, Value of c = 2 Example Try following example to understand all the miscellaneous operators available in C: #include main() int a = 4; s hort b; double c; int* ptr; /* example of sizeof operator */ printf( Line 1 - Size of variable a = %d\n, sizeof(a) ); printf( Line 2 - Size of variable b = %d\n, sizeof(b) ); printf( Line 3 - Size of variable c= %d\n, sizeof ); /* example of & and * operators */ ptr = &a; /* ptr now contains the address of a */ printf( value of a is %d\n, a); printf( *ptr is %d.\n, ptr); / example of ternary operator */ a = 10;

20 b = (a == 1)? 20: 30; printf( Value of b is %d\n, b ); b = (a == 10)? 20: 30; printf( Value of b is %d\n, b ); When you compile and execute the above program, it produces the following result: value of a is 4 *ptr is 4. Value of b is 30 Value of b is 20 Operators Precedence Operators Precedence in C Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Category Operator Associativity Postfix () -> Left to right Unary + -! ~ (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality ==!= Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR Left to right Logical AND && Left to right Logical OR Left to right Conditional?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= = Right to left Comma, Left to right Example Try the following example to understand operator precedence in C: #include main()

21 int a = 20; int b = 10; int c = 15; int d = 5; nt e; e = (a + b) * c / d; // ( 30 * 15 ) / 5 printf( Value of (a + b) * c / d is : %d\n, e ); e = ((a + b) * c) / d; // (30 * 15 ) / 5 printf( Value of ((a + b) * c) / d is : %d\n, e ); e = (a + b) * (c / d); // (30) * (15/5) printf( Value of (a + b) * (c / d) is : %d\n, e ); e = a + (b * c) / d; // 20 + (150/5) printf( Value of a + (b * c) / d is : %d\n, e ); return 0; When you compile and execute the above program, it produces the following result: Value of (a + b) * c / d is : 90 Value of ((a + b) * c) / d is : 90 Value of (a + b) * (c / d) is : 90 Value of a + (b * c) / d is : 50 DECISION MAKING Decision-making structures require that the programmer specifies one or more

22 conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Shown below is the general form of a typical decision-making structure found in most of the programming languages:

23 C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. C programming language provides the following types of decision-making statements. Statement Description if statement An if statement consists of a boolean expression followed by one or more statements. if...else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. nested if statements You can use one if or else if statement inside another if or else if statement(s). switch statement A switch statement allows a variable to be tested for equality against a list of values. nested switch statements You can use one switch statement inside another switch statement(s). if Statement An if statement consists of a Boolean expression followed by one or more statements.

24 Syntax The syntax of an if statement in C programming language is: if(boolean_expression) /* statement(s) will execute if the boolean expression is true */ If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. C programming language assumes any non-zero and non-null values as true and if it is either zero or null, then it is assumed as false value. Flow Diagram

25 Example #include <stdio.h> int main () /* local variable definition */ int a = 10; /* check the boolean condition using if statement */ if( a < 20 ) /* if condition is true then print the following */ printf( a is less than 20\n ); printf( value of a is : %d\n, a); return 0;

26 When the above code is compiled and executed, it produces the following result: a is less than 20; value of a is : 10 if else State e t An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax The syntax of an if...else statement in C programming language is: if(boolean_expression) /* statement(s) will execute if the boolean expression is true */ else /* statement(s) will execute if the boolean expression is false */ If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed. C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. Flow Diagram

27 Example #include <stdio.h> int main () /* local variable definition */ int a = 100;

28 /* check the boolean condition */ if( a < 20 ) /* if condition is true then print the following */ printf( a is less than 20\n ); else /* if condition is false then print the following */ printf( a is not less than 20\n ); printf( value of a is : %d\n, a); return 0; When the above code is compiled and executed, it produces the following result: a is not less than 20; value of a is : 100

29 if...else if...else Statement An 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. Whe usi g if else if else state e ts, the e a e fe poi ts to keep i i d: 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 */

30 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> int main () /* local variable definition */ int a = 100;

31 /* check the boolean condition */ if( a == 10 ) /* if condition is true then print the following */ printf( Value of a is 10\n ); else if( a == 20 ) /* if else if condition is true */ printf( Value of a is 20\n ); else if( a == 30 ) /* if else if condition is true */ printf( Value of a is 30\n );

32 else /* if none of the conditions is true */ printf( None of the values is matching\n ); printf( Exact value of a is: %d\n, a ); return 0; When the above code is compiled and executed, it produces the following result: None of the values is matching Exact value of a is: 100 Nested if Statements It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Syntax The syntax for a nested if statement is as follows: if( boolean_expression 1)

33 /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) /* Executes when the boolean expression 2 is true */ You can nest else if...else in the similar way as you have nested if statements. Example #include <stdio.h> int main () /* local variable definition */ int a = 100; int b = 200; /* check the boolean condition */ if( a == 100 )

34 /* if condition is true then check the following */ if( b == 200 ) /* if condition is true then print the following */ printf( Value of a is 100 and b is 200\n ); printf( Exact value of a is : %d\n, a ); printf( Exact value of b is : %d\n, b ); return 0; When the above code is compiled and executed, it produces the following result: Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 switch Statement

35 A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Syntax The syntax for a switch statement in C programming language is as follows: switch(expression) case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements / default : / Optional */ statement(s); The following rules apply to a switch statement: The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

36 A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Flow Diagram

37 Example #include <stdio.h> int main () /* local variable definition */ char grade = B ; switch(grade) case A : printf( Excellent!\n ); break; case B : case C : printf( Well done\n ); break; case D : printf( You passed\n ); break; case F : printf( Better try again\n ); break; default :

38 printf( Invalid grade\n ); printf( Your grade is %c\n, grade ); return 0; When the above code is compiled and executed, it produces the following result: Well done Your grade is B Nested switch Statements It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. Syntax The syntax for a nested switch statement is as follows: switch(ch1) case A : printf( This A is part of outer switch ); switch(ch2) ase A : printf( This A is part of inner switch ); break; case B : /* case code */ break; case B : /* case code */

39 Example #include <stdio.h> int main () /* local variable definition */ int a = 100; int b = 200; switch(a) case 100: printf( This is part of outer switch\n, a ); switch(b) case 200: printf( This is part of inner switch\n, a ); printf( Exact value of a is : %d\n, a ); printf( Exact value of b is : %d\n, b ); return 0; When the above code is compiled and executed, it produces the following result: This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200

40 The? : Operator: We have covered conditional operator? : in the previous chapter which can be used to replace if...else statements. It has the following general form: Exp1? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. LOOPS 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:

41 C programming language provides the following types of loops to handle looping requirements. Loop Type Description while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

42 do...while loop It is more like a while statement, except nested loops.you can use one or more loops inside any other while,for, or do..while loop. 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

43 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 )

44 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 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 )

45 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

46 Example #include <stdio.h> int main () /* for loop execution */ for( int a = 10; a < 20; a = a + 1 ) printf( value of a: %d\n, a);

47 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 do hile 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

48 Example #include <stdio.h> int main () /* local variable definition */ int a = 10; /* do loop execution */ do

49 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 Nested Loops C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. Syntax

50 The syntax for a nested for loop statement in C is as follows: for ( init; condition; increment ) for ( init; condition; increment ) statement(s); statement(s); The syntax for a nested while loop statement in C programming language is as follows: while(condition) while(condition) statement(s); statement(s); The syntax for a nested do...while loop statement in C programming language is as follows: do statement(s); do

51 statement(s); while( condition ); while( condition ); A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a for loop can be inside a while loop or vice versa. Example The following program uses a nested for loop to find the prime numbers from 2 to 100: #include <stdio.h> int main () /* local variable definition */ int i, j; for(i=2; i<100; i++) for(j=2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf( %d is prime\n, i); return 0; When the above code is compiled and executed, it produces the following result: 2 is prime 3 is prime 5 is prime 7 is prime

52 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime C supports the following control statements Control Statement Description

53 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. goto statement Transfers control to the labeled statement. 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. re 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

54 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;

55 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 and do...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

56 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;

57 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: 16 value of a: 17 value of a: 18 value of a: 19 goto Statement A goto statement in C programming provides an unconditional jump from the goto to a labeled statement in the same function. NOTE: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them. Syntax The syntax for a goto statement in C is as follows: goto label; label: statement; Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement. Flow Diagram

58 Example #include <stdio.h> int main () /* local variable definition */ int a = 10; /* do loop execution */ LOOP:do if( a == 15)

59 /* skip the iteration */ a = a + 1; goto LOOP; 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 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 The Infinite Loop A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. #include <stdio.h> int main () for( ; ; )

60 printf( This loop will run forever.\n ); return 0; When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. FUNCTIONS A function in C can perform a particular task, and supports the concept of modularity. A function is a self-contained block of statements that perform a coherent task of some kind. Making function is a way of isolating one block of code from other independent blocks of code. Syntax of Function Definition: etu _data_t pe fu tio _ a e data_t pe a ia le, data_t pe a ia le, function_body A function definition in C programming consists of a function header and a function body. Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions may perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

61 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. Function Body: The function body contains a collection of statements that define what the function does. Syntax of Function Declaration: return_type function_name( parameter list ); A function declaration tells the compiler about a function name and how to call the function. Example-1: Multiplication of two numbers using function #include <stdio.h> int multiplication(int, int); //function declaration (prototype) int multiplication(int x, int y) x = x * y; return x; //function definition int main() int i, j, k; scanf( %d%d,&i, &j); k = multiplication(i, j); // function call printf( %d\n, k); return 0; Example-2: Program to calculate factorial of given number #include <stdio.h> void factorial( int ); /* ANSI function prototype */ void factorial( int n ) int i, factorial_number = 1;

62 for( i = 1; i <= n; ++i ) factorial_number *= i; printf( The factorial of %d is %d\n, n, factorial_number ); main() int number = 0; printf( Enter a number\n ); scanf( %d, &number ); factorial( number ); There are 4 types of functions based on return type: Function with arguments but no return value Function with arguments and return value Function without arguments and no return value Function without arguments but return value. While calling a function in C program, there are two ways in which arguments can be passed to a function. Call by Value: If we pass values of variables to the function as parameters, such kind of function calling is known as call by value. Call by Reference: Variables are stored somewhere in memory. So, instead of passing the value of a variable, if we pass the location number / address of the variable to the function, then it would become a call by reference. A function can call itself such a process is called recursion. Functions can be of two types: (i) Library functions, and (ii) User-defined functions

63 POINTERS A pointer is a variable that stores memory address. Like all other variables, it also has a name, has to be declared and occupies some spaces in memory. It is called pointerbecause it points to a particular location. & =Address of operator * = Value at address operator or indirection operator &i returns the address of the variable i. *(&i) return the value stored at a particular address printing the value of *(&i) is same as printing the value of i. Pointers are useful due to following reasons: They enable us to access a variable that is defined outside a function. Pointers are more efficient in handling data tables and sometimes even arrays. Pointers tend to reduce the length and complexity of a program. They increase the execution speed. Use of pointers allows easy access to character strings. NOTE: int p; / p is going to store address of integer value (size of memory is 2 bytes) */ float q; / q is going to store address of floating value (size of memory is 2 bytes) */ char *ch; /*ch is going to store address of character variable (size of memory is 2 bytes) */ Pointer Declaration: data-type *pointer-name;

64 NULL Pointers: Uninitilized pointers start out with random unknown values, just like any other variable type. Accidentally using a pointer containing a random address is one of the most common errors encountered when using pointers, and potentially one of the hardest to diagnose, since the errors encountered are generally not repeatable. Example: Program to swap two integer numbers using pointers. #include <stdio.h> void swap(int *a,int *b); int main() int a,b; a = 5; b = 10; printf( \nbefore swapping a= %d: b= %d, a, b); swap(&a, &b); //call function printf( \nafter swapping a= %d: b= %d, a, b); return 0; void swap(int *a, int *b) int x; x = *b; *b = *a; *a = x; Pointers and Strings:

65 An array of characters is called a string. Strings in C are handled differently than most other languages. A pointer is used to keep track of a text string stored in memory. It will point to the first character of the string. By knowing the beginning address and the length of the string, the program can locate it. Example: char *a; a = Hello World! ; Constant pointer: A pointer is said to be constant pointer when the address its pointing to cannot be changed. Syntax: <type-of-pointer> *const <name-of-pointer> Example: int * const p; C Pointer to Constant: This type of pointer cannot change the value at the address pointed by it. Syntax: const <type-of-pointer> *<name-of-pointer>; Example: const int * p; Pointer to Pointer: It is a special pointer variable that can store the address of an other pointer variable. This means that its perfectly legal for a pointer to be pointing to another pointer. Syntax: <type-of-pointer> ** <name-of-pointer>; Example: int **p; Array of Pointers: An array of pointers can be declared as follows. Declaration Syntax: <type> *<name>[<number-of-elements]; Example: int *p[3]; Pointer to an Array: Pointer to an array can be declared as follows. Declaration Syntax: <type> (*<name>) [<number-of-elements]; Example: int (*p)[3]; Function Pointers: Function pointer is same as pointer to a function.

66 Syntax: <return type of function> (*<name of pointer>) (type of function arguments); Example: int (*f)(int, int); //declaration. Combinations of * and ++ *p++ accesses the thing pointed to by p and increments p (*p)++ accesses the thing pointed to by p and increments the thing pointed to by p *++p increments p first, and then accesses the thing pointed to by p ++*p increments the thing pointed to by p first, and then uses it in a larger expression. Pointer Operations: Assignment: You can assign an address to a pointer. Typically, you do this by using an array name or by using the address operator (&). Value finding (dereferencing): The * operator gives the value stored in the pointed-to location. Taking a pointer address: Like all variables, pointer variables have an address and a value. The & operator tells you where the pointer itself is stored. Adding an integer to a pointer: You can use the + operator to add an integer to a pointer or a pointer to an integer. In either case, the integer is multiplied by the number of bytes in the pointed-to type, and the result is added to the original address. Incrementing a pointer: Incrementing a pointer to an array element makes it move to the next element of the array. Subtracting an integer from a pointer: You can use the operator to subtract an integer from a pointer; the pointer has to be the first operand or a pointer to an integer. The integer is multiplied by the number of bytes in the pointed-to type, and the result is subtracted from the original address.

67 Note that there are two forms of subtraction. You can subtract one pointer from another to get an integer, and you can subtract an integer from a pointer and get a pointer. Decrementing a pointer: You can also decrement a pointer. In this example, decrementing ptr2 makes it point to the second array element instead of the third. Note that you can use both the prefix and postfix forms of the increment and decrement operators. Subtraction: You can find the difference of two pointers. Normally, you do this for two pointers to elements that are in the same array to find out how far apart the elements are. The result is in the same units as the type size. Comparisons: You can use the relational operators to compare the values of two pointers, provided the pointers are of the same type. Problems with Pointers: Assigning Value to Pointer Variable Assigning Value to Uninitialized Pointer Not de-referencing Pointer Variable (forgetting to use * before vaiable) Assigning Address of Un-initialized Variable Comparing Pointers that point to different objects Dangling pointers (Using free or de-allocating memory or out of scope)

68 OBJECTIVE QUESTIONS & ANSWERS 1. All keywords in C are in a) LowerCase letters b) UpperCase letters c) CamelCase letters d) None View Answer Answer:a Explanation:None. 2. Variable name resolving (number of significant characters for uniqueness of variable) depends on a) Compiler and linker implementations b) Assemblers and loaders implementations c) C language d) None View Answer Answer:a Explanation:It depends on the standard to which compiler and linkers are adhering to. 3. Which of the following is not a valid C variable name? a) int number; b) float rate; c) int variable_count; d) int $main;

69 View Answer Answer: d Explanation: Since only underscore and no other special character is allowed in a variable name, it results in an error. 4. What is the output of this C code? #include <stdio.h> int main() signed char chr; chr = 128; printf( %d\n, chr); return 0; a) 128 b) -128 c) Depends on the compiler d) None of the mentioned View Answer Answer: b Explanation: signed char will be a negative number. Output: $ cc pgm2.c $ a.out -128

70 5. Comment on the output of this C code? #include <stdio.h> int main() char c; int i = 0; FILE *file; file = fopen( test.txt, w+ ); fprintf(file, %c, a ); fprintf(file, %c, -1); fprintf(file, %c, b ); fclose(file); file = fopen( test.txt, r ); while ((c = fgetc(file))!= -1) printf( %c, c); return 0; a) a b) Infinite loop c) Depends on what fgetc returns d) Depends on the compiler Answer:a Explanation:None. Output: $ cc pgm3.c

71 $ a.out a 6. Comment on the output of this C code? #include <stdio.h> int main() float f1 = 0.1; if (f1 == 0.1f) printf( equal\n ); else printf( not equal\n ); a) equal b) not equal c) Output depends on compiler d) None of the mentioned Answer: a Explanation:0.1f results in 0.1 to be stored in floating point representations. 7. Which of the data types have size that is variable? a) int b) struct c) float d) double

72 Answer: b Explanation: Since the size of the structure depends on its fields, it has a variable size. 8. What is the output of this C code? #include <stdio.h> int main() float x = a ; printf( %f, x); return 0; a) a b) run time error c) a d) Answer: d Explanation:Since the ASCII value of a is 97, the same is assigned to the float variable and printed. 9. What is the output of this C code? #include <stdio.h> int main() int a = 1, b = 1, d = 1; printf( %d, %d, %d, ++a + ++a+a++, a b, ++d + d++ + a++);

73 a) 15, 4, 5 b) 9, 6, 9 c) 9, 3, 5 d) Undefined (Compiler Dependent) View Answer Answer: d 10. For which of the following, PI++; code will fail? a) #define PI 3.14 b) char *PI = A ; c) float PI = 3.14; d) None of the Mentioned View Answer Answer:a

74 Recursion 1. Recursion is a technique that solves a problem by solving a smaller problem of the same type. 2. A recursive function is a function invoking itself, either directly or indirectly. 3. Recursion can be used as an alternative to iteration. 4. Recursion is an important and powerful tool in problem solving and programming. 5. Recursion is a programming technique that naturally implements the divide-and-conquer problem solving methodology. Nature of recursion 1. One or more simple cases of the problem (called the stopping cases or base case) have a simple non-recursive solution. 2. The other cases of the problem can be reduced (using recursion) to problems that are closer to stopping cases. 3. Eventually the problem can be reduced to stopping cases only, which are relatively easy to solve. Four Criteria of A Recursive Solution 1. A recursive function calls itself. This action is what makes the solution recursive. 2. Each recursive call solves an identical, but smaller, problem. A recursive function solves a problem by solving another problem that is identical in nature but smaller in size. 3. A test for the base case enables the recursive calls to stop. There must be a case of the problem (known as base case or stopping case) that is handled differently from the other cases (without recursively calling itself.) In the base case, the recursive calls stop and the problem is solved directly. 4. Eventually, one of the smaller problems must be the base case.

75 The manner in which the size of the problem diminishes ensures that the base case is eventually is reached. Visualization Recursion trace A box for each recursive call An arrow from each caller to callee An arrow from each callee to caller showing return value Example: 1

76 Example : 2 We can express most of the problems in the following program by using recursion. We represent the function add by using recursion. Program #include <stdio.h> int add(int pk,int pm); main() int k,i,m; m=2; k=3; i=add(k,m);. printf("the value of addition is %d\n",i); int add(int pk,int pm) if(pm==0) return(pk); \\ A else return(1+add(pk,pm-1)); \\ B Explanation 1. The add function is recursive as follows: 2. add (x, y) = 1 + add(x, y-1) y > 0 3. = x y = 0 4. for example, 5. add(3, 2) = 1 + add(3, 4)

77 6. add(3, 1) = 1 + add(3, 0) 7. add(3, 0) = 3 8. add(3, 1) = 1+3 = 4 9. add(3, 2) = 1+4 = The recursive expression is 1+add(pk, pm-1). The terminating condition is pm = 0 and the recursive condition is pm > 0. Introduction If you analyze the address of local variables of the recursive function, you will get two important results: the depth of recursion and the stack overheads in recursion. Since local variables of the function are pushed into the stack when the function calls another function, by knowing the address of the variable in repetitive recursive call, you will determine how much information is pushed into the stack. For example, the stack could grow from top to bottom, and the local variable j gets the address 100 in the stack in the first column. Suppose stack overheads are 16 bytes; in the next call j will have the address 84, in the call after that it will get the address 16. That is a difference of 16 bytes. The following program uses the same principle: the difference of the address in consecutive calls is the stack overhead. Program #include <stdio.h> int fact(int n); long old=0; \\E long current=0; \\F main() int k = 4,i; long diff; i =fact(k); printf("the value of i is %d\n",i); diff = old-current; printf("stack overheads are %16lu\n",diff); int fact(int n) int j; static int m=0; if(m==0) old =(long) &j; \\A if(m==1) current =(long) &j; \\B m++; \\C printf("the address of j and m is %16lu %16lu\n",&j,&m); \\D if(n<=0) return(1); else return(n*fact(n-1));

78 Explanation 1. The program calculates factorials just as the previous program. 2. The variable to be analyzed is the local variable j, which is the automatic variable. It gets its location in the stack. 3. The static variable m is used to track the number of recursive calls. Note that the static variables are stored in memory locations known as data segments, and are not stored in stack. Global variables such as old and current are also stored in data segments. 4. The program usually has a three-segment text: first, storing program instructions or program code, then the data segment for storing global and static variables, and then the stack segment for storing automatic variables. 5. During the first call, m is 0 and the value of j is assigned to the global varable old. The value of m is incremented. 6. In the next call, m is 1 and the value of j is stored in current. 7. Note that the addresses of j are stored in long variables of type castings. 8. old and current store the address of j in consecutive calls, and the difference between them gives the stack overheads. 9. You can also check the address of j and check how the allocation is done in the stack and how the stack grows. Note You can also check whether the address of m is constant. Points to Remember 1. The recursive program has a stack overhead. 2. You can calculate stack overheads by analyzing the addresses of local variables. Explanation A recursive function is a function that calls itself. Some problems can be easily solved by using recursion, such as when you are dividing a problem into sub- problems with similar natures. Note that recursion is a time-consuming solution that decreases the speed of execution because of stack overheads. In recursion, there is a function call and the number of such calls is large. In each call, data is pushed into the stack and when the call is over, the data is popped from the stack. These push and pop operations are time-consuming operations. If you have the choice of iteration or recursion, it is better to choose iteration because it does not involve stack overheads. You can use recursion only for programming convenience. A sample recursive program for calculating factorials follows. Program #include <stdio.h> int fact(int n); main() int k = 4,i; i =fact(k); \\ A

79 printf("the value of i is %d\n",i); int fact(int n) if(n<=0) \\ B return(1); \\ C else return(n*fact(n-1)); \\ D Explanation You can express factorials by using recursion as shown: 1. fact (5) = 5 * fact (4) 2. In general, 3. fact (N) = N * fact (N-1) 4. fact 5 is calculated as follows: 5. fact (5) = 5 * fact (4) i.e. there is call to fact (4) \\ A 6. fact (4) = 4 * fact (3) 7. fact (3) = 3 * fact (2) 8. fact (2) = 2 * fact (1) 9. fact (1) = 1 * fact (0) 10. fact (0) = 1 \\ B 11. fact (1) = 1 * 1, the value of the fact(0) is substituted in fact (2) = 2 * 1 = fact (3) = 3 * 2 = fact (4) = 4 * 6 = fact (5) = 5 * 24 = 120 \\ C The operations from statements B to A are collectively called the winding phase, while the operations from B to C are called the unwinding phase. The winding phase should be the terminating point at some time because there is no call to function that is given by statement B; the value of the argument that equals 0 is the terminating condition. After the winding phase is over, the unwinding phase starts and finally the unwinding phase ends at statement C. In recursion, three entities are important: recursive expressions, recursive condition, and terminating condition. For example, fact ( N) = N * fact (N-1) N > 0 = 1 N = 0 o N * fact (N-1) indicates a recursive expression. o N > 0 indicates a recursive condition. o N = 0 indicates a terminating condition. 16. You should note that the recursive expression is such that you will get a terminating condition after some time. Otherwise, the program enters into an infinite recursion and you will get a stack overflow error. Statement B indicates the terminating condition, that is, N = The condition N > 0 indicates a recursive condition that is specified by the else statement. The recursive expression is n * fact(n-1), as given by statement D.

80 Points to Remember 1. Recursion enables us to write a program in a natural way. The speed of a recursive program is slower because of stack overheads. 2. In a recursive program you have to specify recursive conditions, terminating conditions, and recursive expressions. 1. Which Data Structure is used to perform Recursion? a) Queue b) Stack c) Linked List D) Tree Ans : b 2. What s the output of the following code? int dosomething(int a, int b) if (b==1) return a; else return a + dosomething(a,b-1); dosomething(2,3); Ans: 6 a) 4 b)2 c)3 d)6 3. What s happen if base condition is not defined in recursion? Ans : b a) Stack underflow b) Stack Overflow c) None of these d) Both a and b

81 4. What s the output of the following code? Ans : c int rec(int num) return (num)? num%10 + rec(num/10):0; main() printf("%d",rec(4567)); a) 4 b) 12 c) 22 d) What s the output of the following code? Ans : b int something(int number) if(number <= 0) return 1; else return number * something(number-1); something(4); a) 12 b) 24 c) 1 d) 0 6. What will be the output of func(3,8) int func(int a, int b) if(b==0) return 0; if(b==1) return a;

82 return a + func(a,b-1); Ans : b a) 11 b) 24 c) 22 d) What will be the output of print(12). void print(int n) if (n == 0) return; printf("%d", n%2); print(n/2); Ans : a a) 0011 b) 1100 c) 1001 d) What will be the output of sum(8) int sum(int n) if (n==0) return n; else return n + sum(n-1); Ans : b a) 40 b) 36 c) 8 d) 15

83 Arrays Array is a collection of similar elements having same data type, accessed using a common name. Array elements occupy contiguous memory locations. Array indices start at zero in C, and go to one less than the size of the array. Declaration of an Array: Example: int A[100]; type variable[num_elements]; It creates an array A with 100 integer elements. The size of an array A can t be changed. The number between the brackets must be a constant. Initialization of an Array: int A[5]= 1,2,3,4,5; /*Array can be initialized during declaration*/ int A[5]=1,2,3; /* Remaining elements are automatically initialized to zero*/ int A[5]=1,[1]=2, 3,4,[4]=0;/* Array element can be initialized by specifying its index location*/ Problems with Arrays: There is no checking at run-time or compile-time to see whether reference is within array bounds. Size of array must be known at compile time. Example-1: Read the 10 values into an array of size 10. void main() int A[10], i; for (i=0; i<10; i++) printf( Enter the number %d, i+1); scanf( %d, &a[i]);

84 Example-2: Print the 10 values of an Array A. void main() int A[10], i; for (i=0; i<10; i++) printf( %d, A[i]); Pointers & Arrays: Let a[10] be an array with 10 elements. The name a of the array is a constant expression, whose value is the address of the 0th location. An array variable is actually just a pointer to the first element in the array. You can access array elements using array notation or pointers. a[0] is the same as *a a[1] is the same as *(a + 1) a[2] is the same as *(a + 2) a = a+0 = &a[0] a+1 = &a[1] a+i = &a[i] &(*(a+i)) = &a[i] = a+i *(&a[i]) = *(a+i) = a[i] Address of an element i of array a = a + i * sizeof(element) Multi-Dimensional Array In C language, one can have arrays of any dimensions. Let us consider a 3 3 matrix

85 3 3 matrix for multi-dimensional array To access the particular element from the array, we have to use two subscripts; one for row number and other for column number. The notation is of the form a [i] [j], where i stands for row subscripts and j stands for column subscripts. We can also define and initialize the array as follows Note: Two Dimensional Array b[i][j] For Row Major Order: Size of b[i][j] = b + ( Number of rows * i + j )*size of(element) For Column Major Order: Size of b[i][j] = b + ( Number of Columns * j + i )*size of(element) *(*(b + i) + j) is equivalent to b[i][j] *(b + i) + j is equivalent to &b[i][j] *(b[i] + j) is equivalent to b[i][j] [i] + j is e ui ale t to & [i][j] (*(b+i))[j] is equivalent to b[i][j]

86 Strings In C language, strings are stored in an array of character (char) type along with the null terminating character \ at the e d. Printf and scanf use %s format character for string. Printf print characters up to terminating zero. Scanf read characters until whitespace, store result in string, and terminate with zero. Example: char name[ ] = G, A, T, E, T, O, P, \O ; OR char name[ ] = GATETOP ; \ = Null ha a te hose ASCII alue is O. 0 = ASCII value is 48. In the above declaration \ is ot e essa. C i se ts the ull ha a te automatically. %s is used in printf ( ) as a format specification for printing out a string. All the following notations refer to the same element: name [i], * (name + i), * (i + name), i [name] QUESTION-ANSWER OF ARRAY: 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would report an error. C. The program may crash if some important data gets overwritten. D. The array size would appropriately grow. Answer: Option C

87 2. What does the following declaration mean? int (*ptr)[10]; A. ptr is array of pointers to 10 integers B. ptr is a pointer to an array of 10 integers C. ptr is an array of 10 integers D. ptr is an pointer to array Answer: Option B 3. In C, if you pass an array as an argument to a function, what actually gets passed? A. Value of elements in array B. First element of the array C. Base address of the array D. Address of the last element of array Answer: Option C 4. What will be the output of the program? #include<stdio.h> int main() int a[5] = 5, 1, 15, 20, 25; int i, j, m; i = ++a[1]; j = a[1]++; m = a[i++]; printf("%d, %d, %d", i, j, m); return 0; A. 2, 1, 15 B. 1, 2, 5

88 C. 3, 2, 15 D. 2, 3, 20 Answer: Option C A program P reads in 500 integers in the range [0,100] representing the scores of 500 students. It then prints the frequency of each score above 50. what would be the best way for P to store the frequencies? A. An array of 50 numbers B. An array of 100 numbers C. An array of 500 numbers D. A dynamically allocated array of 550 numbers Ans: Option A 6. An n*n matrix V is defined as follows V[i,j]=i-j for all i,j, 1<=i<=n;1<=j<=n; The sum of the elements of the array V is A. 0 B. n-1 C. n2-3n+2 D. n2(n+1)/2 Ans: option A 7. Which of the following statements mentioning the name of the array begins DOES NOT yield the base address? 1. When array name is used with the sizeof operator. 2. When array name is operand of the & operator. 3. When array name is passed to scanf() function.

89 4. When array name is passed to printf() function. A.1 B. 1,2 C.2 D. 2,4 Answer: Option B 8. Which of the following statements are correct about 6 used in the program? int num[6]; num[6]=21; A. In the first statement 6 specifies a particular element, whereas in the second statement it specifies a type. B. In the first statement 6 specifies a array size, whereas in the second statement it specifies a particular element of array. C. In the first statement 6 specifies a particular element, whereas in the second statement it specifies a array size. D. In both the statement 6 specifies array size. Answer: Option B 9. Which of the following statements are correct about an array? A. The array int num[26]; can store 26 elements. B. The expression num[1] designates the very first element in the array. C. It is necessary to initialize the array at the time of declaration. D. The declaration num[size] is allowed if SIZE is a macro. A.1 B.1,4 C.2,3

90 D.2,4 Answer: Option B 10. Does this mentioning array name gives the base address in all the contexts? A.Yes B.No Answer: Option B 11. Are the expressions arr and &arr same for an array of 10 integers? A. Yes B. No Answer: Option B 12. Suppose you are given an array s[1...n] and a procedure reverse (s,i,j) which reverse the order of elements in s between positions i and j (both inclusive). What does the following sequence do, where 1 < k <= n: reverse (s, 1, k); reverse (s, k + 1, n); reverse (s, 1, n); A. Rotates s left by k positions B. Leaves s unchanged C. Reverses all elements of s D. None of the above Ans: option A 13. What will be the output of following program code? #include <stdio.h> int main(void) char p; char buf[10] = 1, 2, 3, 4, 5, 6, 9, 8;

91 p = (buf + 1)[5]; printf("%d", p); return 0; A. 5 B. 6 C. 9 D. Error Answer: Option C 14. What will be printed after execution of the following code? void main() int arr[10] = 1,2,3,4,5; printf("%d", arr[5]); A. Garbage Value B. 5 C. 6 D. 0 Answer: Option D 15. What will be the output of the following program? void main() char str1[] = "abcd"; char str2[] = "abcd"; if(str1==str2) printf("equal"); else printf("unequal");

92 A. Equal B. Unequal C. Error D. None of these. Answer: Option B 16. What will be the output of the following code? void main() int a[10]; printf("%d %d", a[-1], a[12]); A. 0 0 B. Garbage value 0 C. 0 Garbage Value D. Garbage vlaue Garbage Value Answer: Option D 17. Array passed as an argument to a function is interpreted as A. Address of the array. B. Values of the first elements of the array. C. Address of the first element of the array. D. Number of element of the array. Answer: Option C 18. What will be the output of the program if the array begins at and each integer occupies 2 bytes? #include void main()

93 int a[3][4] = 1, 2, 3, 4, 4, 3, 2, 1, 7, 8, 9, 0; printf("%u, %u", a+1, &a+1); A , B , C , D , Answer: Option C 19. Which of the following is correct way to define the function fun() in the below program? #include<stdio.h> void main() int a[3][4]; fun(a); A. void fun(int p[][4]) B. void fun(int *p[4]) C. void fun(int *p[][4]) D. void fun(int *p[3][4]) Answer: Option A 20. The library function used to find the last occurrence of a character in a string is A. laststr() B. strstr() C. strnstr() D. strrchr() Answer: Option D

94 Stacks A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end, called the TOP of the stack. It is a LIFO (Last In First Out) kind of data structure. Operations on Stack Push: Adds an item onto the stack. PUSH (s, i); Adds the item i to the top of stack. Pop: Removes the most-recently-pushed item from the stack. POP (s); Removes the top element and returns it as a function value. size(): It returns the number of elements in the queue. isempty(): It returns true if queue is empty. Implementation of Stack A stack can be implemented in two ways: Using Array and Using Linked list. But since array sized is defined at compile time, it can t grow dynamically. Therefore, an attempt to insert/push an element into stack (which is implemented through array) can cause a stack overflow situation, if it is already full. Go, to avoid the above mentioned problem we need to use linked list to implement a stack, because linked list can grow dynamically and shrink at runtime.

95 1. Push and Pop Implementation Using Array: void push( ) if(top==max) printf( \noverflow ); else int element; printf( \nenter Element: ); scanf( %d,&element); printf( \nelement(%d) has been pushed at %d, element, top); stack[top++]=element; void pop( ) if(top==-1) printf( \nunderflow ); else top ; printf( \nelement has been popped out! ); 2. Push and Pop Implementation Using Linked List: struct node int data; struct node *prev; *top=null, *temp=null; void push( ) temp = (struct node*)malloc(sizeof(struct node*)); printf( \nenter Data: ); scanf( %d,&temp->data); temp->prev=null; if(top==null) top=temp; else temp->prev=top; top=temp;

96 void pop( ) temp=top->prev; top=temp; printf( \ndeleted: %d,top->prev); Applications of Stack Backtracking: This is a process when you need to access the most recent data element in a series of elements. Depth first Search can be implemented. The function call mechanism. Simulation of Recursive calls: The compiler uses one such data structure called stack for implementing normal as well as recursive function calls. Parsing: Syntax analysis of compiler uses stack in parsing the program. Web browsers store the addresses of recently visited sites on a stack. The undo-mechanism in an editor. Expression Evaluation: How a stack can be used for checking on syntax of an expression. o o o o Infix expression: It is the one, where the binary operator comes between the operands. e. g., A + B * C. Postfix expression: Here, the binary operator comes after the operands. e.g., ABC * + Prefix expression: Here, the binary operator proceeds the operands. e.g.,+ A * BC This prefix expression is equivalent to A + (B * C) infix expression. Prefix notation is also known as Polish notation. Postfix notation is also known as suffix or Reverse Polish notation. Reversing a List: First push all the elements of string in stack and then pop elements.

97 Expression conversion: Infix to Postfix, Infix to Prefix, Postfix to Infix, and Prefix to Infix Implementation of Towers of Hanoi Computation of a cycle in the graph Example-1: Implementation of Towers of Hanoi Let A, B, and C be three stacks. Initially, B and C are empty, but A is not. Job is to move the contents of A onto B without ever putting any object x on top of another object that was above x in the initial setup for A. void TOH (int n, Stack A, Stack B, Stack C) if (n == 1) B.push (A.pop()); else TOH (n 1, A, C, B); // n-1 go from A onto C B.push (A.pop()); TOH (n 1, C, B, A); // n-1 go from C onto B Example-2: Evaluate the following postfix notation of expression: / *

98 QUESTION-ANSWER OF STACK: 1. The postfix form of the expression (A+ B)*(C*D- E)*F / G is? a) AB+ CD*E - FG /** b) AB + CD* E - F **G / c) AB + CD* E - *F *G / d) AB + CDE * - * F *G / ANSWER: a) AB+ CD*E - FG /** 2. The data structure required to check whether an expression contains balanced parenthesis is? a) Stack b) Queue c) Array d) Tree ANSWER: a) Stack 3. What data structure would you mostly likely see in a non recursive implementation of a recursive algorithm? a) LinkList b) Stack c) Queue d) Tree ANSWER: b) Stack 4. The process of accessing data stored in a serial access memory is similar to manipulating data on a ? a) Heap b) Binary Tree c) Array d) Stack ANSWER: d) Stack

99 5. The postfix form of A*B+C/D is? a) *AB/CD+ b) AB*CD/+ c) A*BC+/D d) ABCD+/* ANSWER: b) AB*CD/+ 6. Which data structure is needed to convert infix notation to postfix notation? a) Branch b) Tree c) Queue d) Stack ANSWER: d) Stack 7. The prefix form of A-B/ (C * D E) is? a) -/* ACBDE b) -ABCD* DE c) -A/B*C DE d) -A/BC* DE ANSWER: c) -A/B*C DE 8. What is the result of the following operation Top (Push (S, X)) a) X b) Null c) S d) None ANSWER: a) X 9. The prefix form of an infix expression p + q - r * t is? a) + pq - *rt b) - +pqr * t c) - +pq * rt d) - + * pqrt ANSWER: c) - +pq * rt

100 10. Which data structure is used for implementing recursion? a) Queue b) Stack c) Array d) List ANSWER: b) Stack 11. The result of evaluating the postfix expression 5, 4, 6, +, *, 4, 9, 3, /, +, * is? a) 600 b) 350 c) 650 d) 588 ANSWER: b) Convert the following infix expressions into its equivalent postfix expressions (A + B D)/(E - F)+G a) (A B D + E F - / G +) b) (A B D + E F - / G +) c) (A B D + E F/- G +) d) None ANSWER: a) (A B D + E F - / G +) 13. Convert the following Infix expression to Postfix form using a stack x + y * z + (p * q + r) * s, Follow usual precedence rule and assume that the expression is legal. a) xyz*+pq*r+s*+ b) xyz*+pq*r+s+* c) xyz+*pq*r+s*+ d) none ANSWER: a) xyz*+pq*r+s*+ 14. Which of the following statement(s) about stack data structure is/are NOT correct? a) Stack data structure can be implemented using linked list b) New node can only be added at the top of the stack c) Stack is the FIFO data structure

101 d) The last node at the bottom of the stack has a NULL link ANSWER: c) Stack is the FIFO data structure 15. Consider the linked list implementation of a stack. Which of the following node is considered as Top of the stack? a) First node b) Last node c) Any node d) Middle node ANSWER: a) First node 16. Consider the following operation performed on a stack of size 5. Push(1); Pop(); Push(2); Push(3); Pop(); Push(4); Pop(); Pop(); Push(5); After the completion of all operation, the no of element present on stack are a) 1 b) 2 c) 3 d) 4 ANSWER: a) Which of the following is not an inherent application of stack? a) Reversing a string b) Evaluation of postfix expression c) Implementation of recursion d) Job scheduling ANSWER: d) Job scheduling

102 18. Which of the following operation take worst case linear time in the array implementation of stack? a) Push b) Pop c) IsEmpty d) None ANSWER: d) None 19. The type of expression in which operator succeeds its operands is? a) Infix Expression b) pre fix Expression c) postfix Expression d) None ANSWER: c) postfix Expression 20. Which of the following application generally use a stack? a) Parenthesis balancing program b) Syntax analyzer in compiler c) Keeping track of local variables at run time d) All of the above ANSWER: d) All of the above 21. Consider the following array implementation of stack: #define MAX 10 Struct STACK int arr [MAX]; int top = -1; If the array index starts with 0, the maximum value of top which does not cause stack overflow is? a) 8 b) 9 c) 10

103 d) 11 ANSWER: a) What is the minimum number of stacks of size n required to implement a queue of size n? a) One b) Two c) Three d) Four ANSWER: b) Two 23. Assume that the operators +,-, X are left associative and is right associative. The order of precedence (from highest to lowest) is, X, +, -. The postfix expression corresponding to the infix expression a + b X c d e f is a) abc X+ def - b) abc X+ de f - c) ab+c Xd e f d) -+axbc def ANSWER: a) abc X+ def If the elements A, B, C and D are placed in a stack and are deleted one at a time, in what order will they be removed? a) ABCD b) DCBA c) DCAB d) ABDC ANSWER: b) DCBA

104 Queues It is a non-primitive, linear data structure in which elements are added/inserted at one end (called the REAR) and elements are removed/deleted from the other end (called the FRONT). A queue is logically a FIFO (First in First Out) type of list. Operations on Queue Enqueue: Adds an item onto the end of the queue ENQUEUE(Q, i); Adds the item i onto the end of queue. Dequeue: Removes the item from the front of the queue. DEQUEUE (Q); Removes the first element and returns it as a function value. Queue Implementation: Queue can be implemented in two ways. Static implementation (using arrays) Dynamic implementation (using linked lists) Queue Implementation Using Arrays void enqueue() int element; if(rear==max) printf( \noverflow!! ); else printf( \nenter Element: ); scanf( %d,&element); queue[rear++]=element; printf( \n %d Enqueued at %d,element,rear); void dequeue() if(rear==front) printf( \nunderflow!! ); else

105 front++; printf( \nelement is Dequeued from %d,front); Queue Implementation Using Linked Lists typedef struct qnode int data; struct qnode *link; node; node *front=null; node *rear=null;void enqueue() int item; node *temp; printf( Enter the item\n ); scanf( %d,&item); temp=(node*)malloc(sizeof(node)); temp->data=item; temp->link=null; if(rear==null) front=temp; rear=temp; else rear->link=temp; rear=temp; void dequeue() int item; if(front==null) printf( Queue is empty\n ); else

106 item=front->data; printf( The element deleted = %d\n,item); if(front==rear) front=null; rear=null; else front=front->link; Circular Queue In a circular queue, the first element comes just after the last element or a circular queue is one in which the insertion of a new element is done at the very first location of the queue, if the last location of queue is full and the first location is empty. Note: A circular queue overcomes the problem of unutilised space in linear queues implemented as arrays. We can make following assumptions for circular queue. If : (Rear+1) % n == Front, then queue is Full If Front = Rear, the queue will be empty. Each time a new element is inserted into the queue, the Rear is incremented by 1. Rear = (Rear + 1) ) % n Each time, an element is deleted from the queue, the value of Front is incremented by one. Front = (Front + 1) % n Double Ended Queue (DEQUE): It is a list of elements in which insertion and deletion operations are performed from both the ends. That is why it is called double-ended queue or DEQUE. Priority Queues: This type of queue enables us to retrieve data items on the basis of priority associated with them. Below are the two basic priority queue choices. Sorted Array or List It is very efficient to find and delete the smallest element. Maintaining sorted ness make the insertion of new elements slow.

107 Applications of Queue Breadth first Search can be implemented. CPU Scheduling Handling of interrupts in real-time systems Routing Algorithms Computation of shortest paths Computation a cycle in the graph Example-1: Reversing the Queue Q using the Stack S void reverse( Queue Q) Stack S ; //Assume Empty Stack S is created whil e (! isempty (Q) ) S.push(&S, dequeue (Q ) ) ; whil e (! isempty(&s ) ) enqueue (Q, pop(&s ) ) ; Example-2: Find the effect of the following code with Circular Queue Q having locations from 0 to 6. for (int k = 1; k <= 7; k++) Q.enqueue(k); for (int k = 1; k <= 4; k++) Q.enqueue(Q.dequeue()); Q.dequeue(); Answer: After the above code execution on empty queue will result the following elements. 3 is stored at location 1, 5 is stored at location 2, and 7 is stored at location 3. Implementation of Queue Using Two Stacks Method 1:Let S1 and S2 be the two stacks to be used in the implementation of queue Q. Enqueue(int a) S1.push(a);

108 int Dequeue( ) if (S1 is empty) return(error); while(s1 is not empty) S2.push(S1.pop()); r = S2.pop(); while(s2 is not empty) S1.push(S2.pop()); return(r); Method2: Let S1 and S2 be the two stacks to be used in the implementation of queue Q. Enqueue(int a) S1.push(a); int dequeue( ) if (S1 is empty & S2 is empty) return(error); if (S2 is empty) while(s1 is not empty) S2.push(S1.pop()); return(s2.pop()); Implementation of Stack Using two Queues Method 1: Let Q1 and Q2 be two queues. push: Enqueue in queue1 pop: while size of queue1 is bigger than 1, pipe dequeued items from queue1 into queue2 Dequeue and return the last item of queue1, then switch the names of queue1 and queue2 Push is constant time but Pop operation is O(n) time void push(int data) Enqueue(Q1, data)

109 int pop() int returnvalue =-1; // indicate Stack Empty. while(!isempty(q1)) returnvalue = Dequeue(Q1); // If it was last element of queue1. return it. if(isempty(q1)) break; else Enqueue(Q1, returnvalue); // swap the names of queue1 and queue2. // If swapping is not possible then we will have to move all the elements from queue2 to queue1 // or have another flag to indicate the active queue. Node * temp = Q1; Q1 = Q2; Q2 = temp; return returnvalue; Method 2: push: Enqueue in queue2 Enqueue all items of queue1 in queue2, then switch the names of queue1 and queue2 pop: Deqeue from queue1 Pop is constant time but Push operation is O(n) time void push(int data) Enqueue(Q2, data); while(!isempty(q1)) Enqueue(Q2, Dequeue(Q1)); // swap the names of queue1 and queue2. // If swapping is not possible then we will have to move all the elements from queue2 to queue1 // or have another flag to indicate the active queue.

110 Node * temp = Q1; Q1 = Q2; Q2 = temp; // Put proper check to see if no element in Queues int pop() return Dequeue(Q1); Related Question and Answers 1. Following is C like pseudo code of a function that takes a Queue as an argument, and uses a stack S to do processing. void fun(queue *Q) Stack S; // Say it creates an empty stack S // Run while Q is not empty while (!isempty(q)) // dequeue an item from Q and push the dequeued item to S push(&s, dequeue(q)); // Run while Stack S is not empty while (!isempty(&s)) // Pop an item from S and enqueue the poppped item to Q enqueue(q, pop(&s)); What does the above function do in general? (A) Removes the last from Q (B) Keeps the Q same as it was before the call (C) Makes Q empty (D) Reverses the Q Answer: (D) Explanation: The function takes a queue Q as an argument. It dequeues all items of Q and pushes them to a stack S. Then pops all items of S and enqueues the items back to Q. Since stack is LIFO order, all items of queue are reversed.

111 2. Which one of the following is an application of Queue Data Structure? (A) When a resource is shared among multiple consumers. (B) When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes (C) Load Balancing (D) All of the above Answer: (D) Explanation: Queue is used when things don t have to be processed immediatly, but have to be processed in First In First Out order like Breadth First Search. This property of Queue makes it also useful in following kind of scenarios. 1) When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk Scheduling. 2) When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc. 3. How many stacks are needed to implement a queue. Consider the situation where no other data structure like arrays, linked list is available to you. (A) 1 (B) 2 (C) 3 (D) 4 Answer: (B) Explanation: A queue can be implemented using two stacks. Implement Queue using Stacks A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways: Method 1 (By making enqueue operation costly) This method makes sure that oldest entered element is always at the top of stack 1, so that dequeue operation just pops from stack1. To put the element at top of stack1, stack2 is used. enqueue(q, x) 1) While stack1 is not empty, push everything from satck1 to stack2. 2) Push x to stack1 (assuming size of stacks is unlimited). 3) Push everything back to stack1. dnqueue(q) 1) If stack1 is empty then error 2) Pop an item from stack1 and return it

112 Method 2 (By making dequeue operation costly) In this method, in en-queue operation, the new element is entered at the top of stack1. In dequeue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned. enqueue(q, x) 1) Push x to stack1 (assuming size of stacks is unlimited). dequeue(q) 1) If both stacks are empty then error. 2) If stack2 is empty While stack1 is not empty, push everything from satck1 to stack2. 3) Pop the element from stack2 and return it. Method 2 is definitely better than method 1. Method 1 moves all the elements twice in enqueue operation, while method 2 (in dequeue operation) moves the elements once and moves elements only if stack2 empty. Implementation of method 2: /* Program to implement a queue using two stacks */ #include<stdio.h> #include<stdlib.h> /* structure of a stack node */ struct snode int data; struct snode *next; ; /* Function to push an item to stack*/ void push(struct snode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct snode** top_ref); /* structure of queue having two stacks */ struct queue struct snode *stack1; struct snode *stack2;

113 ; /* Function to enqueue an item to queue */ void enqueue(struct queue *q, int x) push(&q->stack1, x); /* Function to dequeue an item from queue */ int dequeue(struct queue *q) int x; /* If both stacks are empty then error */ if(q->stack1 == NULL && q->stack2 == NULL) printf("q is empty"); getchar(); exit(0); /* Move elements from satck1 to stack 2 only if stack2 is empty */ if(q->stack2 == NULL) while(q->stack1!= NULL) x = pop(&q->stack1); push(&q->stack2, x); x = pop(&q->stack2); return x; /* Function to push an item to stack*/ void push(struct snode** top_ref, int new_data)

114 /* allocate node */ struct snode* new_node = (struct snode*) malloc(sizeof(struct snode)); if(new_node == NULL) printf("stack overflow \n"); getchar(); exit(0); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; /* Function to pop an item from stack*/ int pop(struct snode** top_ref) int res; struct snode *top; /*If stack is empty then error */ if(*top_ref == NULL) printf("stack overflow \n"); getchar(); exit(0); else top = *top_ref;

115 res = top->data; *top_ref = top->next; free(top); return res; /* Driver function to test anove functions */ int main() /* Create a queue with items 1 2 3*/ struct queue *q = (struct queue*)malloc(sizeof(struct queue)); q->stack1 = NULL; q->stack2 = NULL; enqueue(q, 1); enqueue(q, 2); enqueue(q, 3); /* Dequeue items */ printf("%d ", dequeue(q)); printf("%d ", dequeue(q)); printf("%d ", dequeue(q)); getchar(); Queue can also be implemented using one user stack and one Function Call Stack. Below is modified Method 2 where recursion (or Function Call Stack) is used to implement queue using only one user defined stack. enqueue(x) 1) Push x to stack1. dequeue: 1) If stack1 is empty then error. 2) If stack1 has only one element then return it. 3) Recursively pop everything from the stack1, store the popped item in a variable res, push the res back to stack1 and return res

116 The step 3 makes sure that the last popped item is always returned and since the recursion stops when there is only one item in stack1 (step 2), we get the last element of stack1 in dequeue() and all other items are pushed back in step 3. Implementation of method 2 using Function Call Stack: /* Program to implement a queue using one user defined stack and one Function Call Stack */ #include<stdio.h> #include<stdlib.h> /* structure of a stack node */ struct snode int data; struct snode *next; ; /* structure of queue having two stacks */ struct queue struct snode *stack1; ; /* Function to push an item to stack*/ void push(struct snode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct snode** top_ref); /* Function to enqueue an item to queue */ void enqueue(struct queue *q, int x) push(&q->stack1, x); /* Function to dequeue an item from queue */ int dequeue(struct queue *q)

117 int x, res; /* If both stacks are empty then error */ if(q->stack1 == NULL) printf("q is empty"); getchar(); exit(0); else if(q->stack1->next == NULL) return pop(&q->stack1); else /* pop an item from the stack1 */ x = pop(&q->stack1); /* store the last dequeued item */ res = dequeue(q); /* push everything back to stack1 */ push(&q->stack1, x); return res; /* Function to push an item to stack*/ void push(struct snode** top_ref, int new_data) /* allocate node */ struct snode* new_node = (struct snode*) malloc(sizeof(struct snode)); if(new_node == NULL) printf("stack overflow \n");

118 getchar(); exit(0); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; /* Function to pop an item from stack*/ int pop(struct snode** top_ref) int res; struct snode *top; /*If stack is empty then error */ if(*top_ref == NULL) printf("stack overflow \n"); getchar(); exit(0); else top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; /* Driver function to test above functions */

119 int main() /* Create a queue with items 1 2 3*/ struct queue *q = (struct queue*)malloc(sizeof(struct queue)); q->stack1 = NULL; enqueue(q, 1); enqueue(q, 2); enqueue(q, 3); /* Dequeue items */ printf("%d ", dequeue(q)); printf("%d ", dequeue(q)); printf("%d ", dequeue(q)); getchar(); 4. How many queues are needed to implement a stack. Consider the situation where no other data structure like arrays, linked list is available to you. (A) 1 (B) 2 (C) 3 (D) 4 Answer: (B) Explanation: A stack can be implemented using two queues. 5. A priority queue can efficiently implemented using which of the following data structures? Assume that the number of insert and peek (operation to see the current highest priority item) and extraction (remove the highest priority item) operations are almost same. (A) Array (B) Linked List (C) Heap Data Structures like Binary Heap, Fibonacci Heap (D) None of the above Answer: (C)

120 6. Which of the following is true about linked list implementation of queue? (A) In push operation, if new nodes are inserted at the beginning of linked list, then in pop operation, nodes must be removed from end. (B) In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be removed from the beginning. (C) Both of the above (D) None of the above Answer: (C) Explanation: To keep the First In First Out order, a queue can be implemented using linked list in any of the given two ways. 7. Suppose a circular queue of capacity (n 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are (A) Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT (B) Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR (C) Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT (D) Full: (FRONT+1) mod n == REAR, empty: REAR == FRONT Answer: (A) Explanation: Suppose we start filling the queue. Let the maxqueuesize ( Capacity of the Queue) is 4. So the size of the array which is used to implement this circular queue is 5, which is n. In the begining when the queue is empty, FRONT and REAR point to 0 index in the array. REAR represents insertion at the REAR index. FRONT represents deletion from the FRONT index. enqueue("a"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 1) enqueue("b"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 2) enqueue("c"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 3) enqueue("d"); REAR = (REAR+1)%5; ( FRONT = 0, REAR = 4)

121 Now the queue size is 4 which is equal to the maxqueuesize. Hence overflow condition is reached. Now, we can check for the conditions. When Queue Full : ( REAR+1)%n = (4+1)%5 = 0 FRONT is also 0. Hence ( REAR + 1 ) %n is equal to FRONT. When Queue Empty : REAR was equal to FRONT when empty ( because in the starting before filling the queue FRONT = REAR = 0 ) Hence Option A is correct. 8. A Priority-Queue is implemented as a Max-Heap. Initially, it has 5 elements. The level-order traversal of the heap is given below: 10, 8, 5, 3, 2 Two new elements 1 and 7 are inserted in the heap in that order. The level-order traversal of the heap after the insertion of the elements is: (A) 10, 8, 7, 5, 3, 2, 1 (B) 10, 8, 7, 2, 3, 1, 5 (C) 10, 8, 7, 1, 2, 3, 5 (D) 10, 8, 7, 3, 2, 1, 5 Answer: (D) 9. Consider the following pseudo code. Assume that IntQueue is an integer queue. What does the function fun do? void fun(int n) IntQueue q = new IntQueue(); q.enqueue(0);

122 q.enqueue(1); for (int i = 0; i < n; i++) int a = q.dequeue(); int b = q.dequeue(); q.enqueue(b); q.enqueue(a + b); ptint(a); (A) Prints numbers from 0 to n-1 (B) Prints numbers from n-1 to 0 (C) Prints first n Fibonacci numbers (D) Prints first n Fibonacci numbers in reverse order. Answer: (C) Explanation: The function prints first n Fibonacci Numbers. Note that 0 and 1 are initially there in q. In every iteration of loop sum of the two queue items is enqueued and the front item is dequeued.

123 Linked Lists Linked list is a special data structure in which data elements are linked to one another. Here, each element is called a node which has two parts Info part which stores the information. Address or pointer part which holds the address of next element of same type.linked list is also known as self-referential structure. Each element (node) of a list is comprising of two items: the data and a reference to the next node. The last node has a reference to NULL. The entry point into a linked list is called the head of the list. It should be noted that head is not a separate node, but the reference to the first node. If the list is empty then the head is a null reference. Syntax of declaring a node which contains two fields in it one is for storing information and another is for storing address of other node, so that one can traverse the list. Linked List vs Array Both Arrays and Linked List can be used to store linear data of similar types, but they both have some advantages and disadvantages over each other. Following are the points in favour of Linked Lists. (1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage, and in practical uses, upper limit is rarely reached. (2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted. For example, suppose we maintain a sorted list of IDs in an array id[].

124 id[] = [1000, 1010, 1050, 2000, 2040,..]. And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000). Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved. So Linked list provides following two advantages over arrays 1) Dynamic size 2) Ease of insertion/deletion Linked lists have following drawbacks: 1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists. 2) Extra memory space for a pointer is required with each element of the list. 3) Arrays have better cache locality that can make a pretty big difference in performance. Advantages of Linked List: Linked lists are dynamic data structure as they can grow and shrink during the execution time. Efficient memory utilisation because here memory is not pre-allocated. Insertions and deletions can be done very easily at the desired position. Disadvantages of Linked List: More memory is required, if the number of fields are, more. Access to an arbitrary data item is time consuming. Operations on Linked Lists: The following operations involve in linked list are as given below Creation: Used to create a lined list. Insertion: Used to insert a new node in linked list at the specified position. A new node may be inserted o At the beginning of a linked list o At the end of a linked list o At the specified position in a linked list o In case of empty list, a new node is inserted as a first node. Deletion: This operation is basically used to delete as item (a node). A node may be deleted from the o Beginning of a linked list. o End of a linked list. o Specified position in the list. Traversing: It is a process of going through (accessing) all the nodes of a linked list from one end to the other end.

125 Types of Linked Lists Singly Linked List: In this type of linked list, each node has only one address field which points to the next node. So, the main disadvantage of this type of list is that we can t access the predecessor of node from the current node. Doubly Linked List: Each node of linked list is having two address fields (or links) which help in accessing both the successor node (next node) and predecessor node (previous node). Circular Linked List: It has address of first node in the link (or address) field of last node. Circular Doubly Linked List: It has both the previous and next pointer in circular manner. Example-1: Reverse of a Singly Linked List with iterations void reverse_list() node *p, *q, *r; if(head == (mynode *)0) return; p = head; q = p->next; p->next = (mynode *)0; while (q!= (mynode *)0) r = q->next; q->next = p; p = q; q = r; head = p; Example2: Reverse of a Singly Linked List with Recursion node* reverse_list(mynode *root) if(root->next!=(mynode *)0) reverse_list(root->next); root->next->next=root; return(root); else head=root; Example-3: Reverse of a Doubly Linked List void reverse( ) node *cur, *temp, *nextnode; if(head==tail) return; if(head==null tail==null) return; for(cur=head; cur!=null; )

126 temp=cur->next; nextnode=cur->next; cur->next=cur->prev; cur->prev=temp; cur=nextnode; temp=head; head=tail; tail=temp; Example-4: Finding the middle of a Linked List struct node *middle(struct node *head) p=head; q=head; if(q->next->next!=null) p=p->next; q=q->next->next; return p; Time complexity for the following operations on Singly Linked Lists of n nodes: Add a new node to the beginning of list: O(1) Add a new node to the end: O(n) Add a new node after k th node: O(n) Search a node with a given data: O(n) Add a new node after a node with a given data: O(n) Add a new node before a node with a given data: O(n) Traverse all nodes: O(n) Delete a node from the beginning: O(1) Delete a node from the end: O(n) Delete a node with a given data: O(n) Delete the k th node: O(n) Modify the data of all nodes in a linked list: O(n) Time complexity for the following operations on Doubly Linked Lists of n nodes: Add a new node to the beginning of list: O(1) Add a new node to the end: O(n) Add a new node after k th node: O(n) Search a node with a given data: O(n) Add a new node after a node with a given data: O(n) Add a new node before a node with a given data: O(n) Traverse all nodes: O(n) Delete a node from the beginning: O(1) Delete a node from the end: O(n)

127 Delete a node with a given data: O(n) Delete the k th node: O(n) Modify the data of all nodes in a linked list: O(n) Time complexity for the following operations on Circular Singly Linked Lists of n nodes: Add a new node to the beginning of list: O(n) Add a new node to the end: O(n) Add a new node after k th node: O(n) Search a node with a given data: O(n) Add a new node after a node with a given data: O(n) Add a new node before a node with a given data: O(n) Traverse all nodes: O(n) Delete a node from the beginning: O(n) Delete a node from the end: O(n) Delete a node with a given data: O(n) Delete the k th node: O(n) Modify the data of all nodes in a linked list: O(n) Time complexity for the following operations on Circular Doubly Linked Lists of n nodes: Add a new node to the beginning of list: O(1) Add a new node to the end: O(1) Add a new node after k th node: O(n) Search a node with a given data: O(n) Add a new node after a node with a given data: O(n) Add a new node before a node with a given data: O(n) Traverse all nodes: O(n) Delete a node from the beginning: O(1) Delete a node from the end: O(1) Delete a node with a given data: O(n) Delete the k th node: O(n) Modify the data of all nodes in a linked list: O(n) Related Questions and Answers 1. What does the following function do for a given Linked List with first node as head? void fun1(struct node* head) if(head == NULL) return; fun1(head->next); printf("%d ", head->data); A Prints all nodes of linked lists B Prints all nodes of linked list in reverse order

128 C Prints alternate nodes of Linked List D Prints alternate nodes in reverse order Answer: (B) Explanation: fun1() prints the given Linked List in reverse manner. For Linked List 1->2->3- >4->5, fun1() prints 5->4->3->2->1. 2. Which of the following points is/are true about Linked List data structure when it is compared with array A Arrays have better cache locality that can make them better in terms of performance. B It is easy to insert and delete elements in Linked List C Random access is not allowed in a typical implementation of Linked Lists D The size of array has to be pre-decided, linked lists can change their size any time. E All of the above Answer: (E) 3. Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as prev and next pointer as next. void fun(struct node **head_ref) struct node *temp = NULL; struct node *current = *head_ref; while (current!= NULL) temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; if(temp!= NULL ) *head_ref = temp->prev;

129 Assume that reference of head of following doubly linked list is passed to above function 1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6. What should be the modified linked list after the function call? A 2 <--> 1 <--> 4 <--> 3 <--> 6 <-->5 B 5 <--> 4 <--> 3 <--> 2 <--> 1 <-->6. C 6 <--> 5 <--> 4 <--> 3 <--> 2 <--> 1. D 6 <--> 5 <--> 4 <--> 3 <--> 1 <--> 2 Answer: (C) Explanation: The given function reverses the given doubly linked list. See Reverse a Doubly Linked List for details. 4. Which of the following sorting algorithms can be used to sort a random linked list with minimum time complexity? A Insertion Sort B Quick Sort C Heap Sort D Merge Sort Answer: (D) Explanation: Both Merge sort and Insertion sort can be used for linked lists. The slow random-access performance of a linked list makes other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Since worst case time complexity of Merge Sort is O(nLogn) and Insertion sort is O(n^2), merge sort is preferred. 5. The following function reverse() is supposed to reverse a singly linked list. There is one line missing at the end of the function. /* Link list node */ struct node int data; struct node* next; ; /* head_ref is a double pointer which points to head (or start) pointer of linked list */ static void reverse(struct node** head_ref) struct node* prev = NULL;

130 struct node* current = *head_ref; struct node* next; while (current!= NULL) next = current->next; current->next = prev; prev = current; current = next; /*ADD A STATEMENT HERE*/ What should be added in place of /*ADD A STATEMENT HERE*/, so that the function correctly reverses a linked list. (A) *head_ref = prev; (B) *head_ref = current; (C) *head_ref = next; (D) *head_ref = NULL; Answer: (A) Explanation: *head_ref = prev; At the end of while loop, the prev pointer points to the last node of original linked list. We need to change *head_ref so that the head pointer now starts pointing to the last node. See the following complete running program. #include<stdio.h> #include<stdlib.h> /* Link list node */ struct node int data; struct node* next; ; /* Function to reverse the linked list */ static void reverse(struct node** head_ref) struct node* prev = NULL;

131 struct node* current = *head_ref; struct node* next; while (current!= NULL) next = current->next; current->next = prev; prev = current; current = next; *head_ref = prev; /* Function to push a node */ void push(struct node** head_ref, int new_data) /* allocate node */ struct node* new_node = (struct node*) malloc(sizeof(struct node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; /* Function to print linked list */ void printlist(struct node *head) struct node *temp = head; while(temp!= NULL) printf("%d ", temp->data); temp = temp->next;

132 /* Drier program to test above function*/ int main() /* Start with the empty list */ struct node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 85); printlist(head); reverse(&head); printf("\n Reversed Linked list \n"); printlist(head); return 0; 6. What is the output of following function for start pointing to first node of following linked list? 1->2->3->4->5->6 void fun(struct node* start) if(start == NULL) return; printf("%d ", start->data); if(start->next!= NULL ) fun(start->next->next); printf("%d ", start->data); Run on IDE (A) (B) (C) (D) Answer: (D)

133 Explanation: fun() prints alternate nodes of the given Linked List, first from head to end, and then from end to head. If Linked List has even number of nodes, then skips the last node. 7. The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank. Choose the correct alternative to replace the blank line. typedef struct node int value; struct node *next; Node; Node *move_to_front(node *head) Node *p, *q; if ((head == NULL: (head->next == NULL)) return head; q = NULL; p = head; while (p-> next!=null) q = p; p = p->next; return head; Run on IDE (A) q = NULL; p->next = head; head = p; (B) q->next = NULL; head = p; p->next = head; (C) head = p; p->next = q; q->next = NULL; (D) q->next = NULL; p->next = head; head = p; Answer: (D) Explanation: When the while loop ends, q contains address of second last node and p contains address of last node. So we need to do following things after while loop. i) Set next of q as NULL (q->next = NULL). ii) Set next of p as head (p->next = head). iii) Make head as p ( head = p)

134 Step (ii) must be performed before step (iii). If we change head first, then we lose track of head node in the original linked list. 8. The following C function takes a single-linked list of integers as a parameter and rearranges the elements of the list. The function is called with the list containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the function completes execution? struct node int value; struct node *next; ; void rearrange(struct node *list) struct node *p, * q; int temp; if ((!list)!list->next) return; p = list; q = list->next; while(q) temp = p->value; p->value = q->value; q->value = temp; p = q->next; q = p?p->next:0; Run on IDE (A) 1,2,3,4,5,6,7 (B) 2,1,4,3,6,5,7 (C) 1,3,2,5,4,7,6 (D) 2,3,4,5,6,7,1 Answer: (B) Explanation: The function rearrange() exchanges data of every node with its next node. It starts exchanging data from the first node itself.

135 9. In the worst case, the number of comparisons needed to search a singly linked list of length n for a given element is (GATE CS 2002) (A) log 2 n (B) n/2 (C) log 2 n 1 (D) n Answer: (D) Explanation: In the worst case, the element to be searched has to be compared with all elements of linked list. 10. Suppose each set is represented as a linked list with elements in arbitrary order. Which of the operations among union, intersection, membership, cardinality will be the slowest? (GATE CS 2004) (A) union only (B) intersection, membership (C) membership, cardinality (D) union, intersection Answer: (D) Explanation: For getting intersection of L1 and L2, search for each element of L1 in L2 and print the elements we find in L2. There can be many ways for getting union of L1 and L2. One of them is as follows a) Print all the nodes of L1 and print only those which are not present in L2. b) Print nodes of L2. All of these methods will require more operations than intersection as we have to process intersection node plus other nodes. 11. Consider the function f defined below. struct item int data; struct item * next; ; int f(struct item *p)

136 return ( (p == NULL) (p->next == NULL) (( P->data <= p->next->data) && f(p->next)) ); For a given linked list p, the function f returns 1 if and only if (GATE CS 2003) (A) the list is empty or has exactly one element (B) the elements in the list are sorted in non-decreasing order of data value (C) the elements in the list are sorted in non-increasing order of data value (D) not all elements in the list have the same data value. Answer: (B) Explanation: The function f() works as follows 1) If linked list is empty return 1 2) Else If linked list has only one element return 1 3) Else if node->data is smaller than equal to node->next->data and same thing holds for rest of the list then return 1 4) Else return A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations enqueue and dequeue can be performed in constant time? (A) rear node (B) front node (C) not possible with a single pointer (D) node next to front Answer: (A)

137 Explanation: Answer is not (b) front node, as we can not get rear from front in O(1), but if p is rear we can implement both enqueue and dequeue in O(1) because from rear we can get front in O(1). Below are sample functions. Note that these functions are just sample are not working. Code to handle base cases is missing. /* p is pointer to address of rear (double pointer). This function adds new node after rear and updates rear which is *p to point to new node */ void enqueue(struct node **p, struct node *new_node) /* Missing code to handle base cases like *p is NULL */ new_node->next = (*p)->next; (*p)->next = new_node; (*p) = new_node /* new is now rear */ /* Note that p is again front and p->next is rear */ /* p is pointer to rear. This function removes the front element and returns the new front */ struct node *dequeue(struct node *p) /* Missing code to handle base cases like p is NULL, p->next is NULL,... etc */ struct node *temp = p->next->next; p->next = p->next->next; return temp; /* Note that p is again front and p->next is rear */ 13. What are the time complexities of finding 8th element from beginning and 8th element from end in a singly linked list? Let n be the number of nodes in linked list, you may assume that n > 8. (A) O(1) and O(n) (B) O(1) and O(1) (C) O(n) and O(1) (D) O(n) and O(n) Answer: (A)

138 Explanation: Finding 8th element from beginning requires 8 nodes to be traversed which takes constant time. Finding 8th from end requires the complete list to be traversed. 14. Is it possible to create a doubly linked list using only one pointer with every node. (A) Not Possible (B) Yes, possible by storing XOR of addresses of previous and next nodes. (C) Yes, possible by storing XOR of current node and next node (D) Yes, possible by storing XOR of current node and previous node Answer: (B) Explanation: An ordinary Doubly Linked List requires space for two address fields to store the addresses of previous and next nodes. A memory efficient version of Doubly Linked List can be created using only one space for address field with every node. This memory efficient Doubly Linked List is called XOR Linked List or Memory Efficient as the list uses bitwise XOR operation to save space for one address. In the XOR linked list, instead of storing actual memory addresses, every node stores the XOR of addresses of previous and next nodes. Consider the above Doubly Linked List. Following are the Ordinary and XOR (or Memory Effiecient) representations of the Doubly Linked List. Ordinary Representation: Node A: prev = NULL, next = add(b) // previous is NULL and next is address of B Node B: prev = add(a), next = add(c) // previous is address of A and next is address of C Node C: prev = add(b), next = add(d) // previous is address of B and next is address of D Node D:

139 prev = add(c), next = NULL // previous is address of C and next is NULL XOR List Representation: Let us call the address variable in XOR representation npx (XOR of next and previous) Node A: npx = 0 XOR add(b) // bitwise XOR of zero and address of B Node B: npx = add(a) XOR add(c) // bitwise XOR of address of A and address of C Node C: npx = add(b) XOR add(d) // bitwise XOR of address of B and address of D Node D: npx = add(c) XOR 0 // bitwise XOR of address of C and 0 Traversal of XOR Linked List: We can traverse the XOR list in both forward and reverse direction. While traversing the list we need to remember the address of the previously accessed node in order to calculate the next node s address. For example when we are at node C, we must have address of B. XOR of add(b) and npx of C gives us the add(d). The reason is simple: npx(c) is add(b) XOR add(d). If we do xor of npx(c) with add(b), we get the result as add(b) XOR add(d) XOR add(b) which is add(d) XOR 0 which is add(d). So we have the address of next node. Similarly we can traverse the list in backward direction. 15. Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node is not given, can we delete the node X from given linked list? (A) Possible if X is not last node. Use following two steps (a) Copy the data of next of X to X. (b) Delete next of X. (B) Possible if size of linked list is even. (C) Possible if size of linked list is odd (D) Possible if X is not first node. Use following two steps (a) Copy the data of next of X to X. (b) Delete next of X. Answer: (A) Explanation: Following are simple steps. struct node *temp = X->next;

140 X->data = temp->data; X->next = temp->next; free(temp); 16. You are given pointers to first and last nodes of a singly linked list, which of the following operations are dependent on the length of the linked list? (A) Delete the first element (B) Insert a new element as a first element (C) Delete the last element of the list (D) Add a new element at the end of the list Answer: (C) Explanation: a) Can be done in O(1) time by deleting memory and changing the first pointer. b) Can be done in O(1) time, see push() here c) Delete the last element requires pointer to previous of last, which can only be obtained by traversing the list. d) Can be done in O(1) by changing next of last and then last. 17. Consider the following function to traverse a linked list. void traverse(struct Node *head) while (head->next!= NULL) printf("%d ", head->data); head = head->next; Run on IDE Which of the following is FALSE about above function? (A) The function may crash when the linked list is empty (B) The function doesn t print the last node when the linked list is not empty (C) The function is implemented incorrectly because it changes head Answer: (C) 18. The following C function takes a singly-linked list of integers as a parameter and rearranges the elements of the list. The list is represented as pointer to a structure. The function is called

141 with the list containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the function completes execution? struct node int value; struct node *next;); void rearrange (struct node *list) struct node *p, *q; int temp; if (!list!list -> next) return; p = list; q = list -> next; while (q) temp = p -> value; p -> value = q -> value; q -> value = temp; p = q -> next; q = p? p -> next : 0; (A) 1, 2, 3, 4, 5, 6, 7 (B) 2, 1, 4, 3, 6, 5, 7 (C) 1, 3, 2, 5, 4, 7, 6 (D) 2, 3, 4, 5, 6, 7, 1 Answer: (B) 19. Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-case time complexity of the best known algorithm to delete the node x from the list? (A) O(n) (B) O(log2 n) (C) O(logn) (D) O(1) Answer: (A) Explanation: To delete an element with given pointer, we need pointer to previous node, because next of previous node must be modified. In worst case, to find the previous node, we may have to traverse till second last node. Therefore worst case time complexity is O(n). 20. N items are stored in a sorted doubly linked list. For a delete operation, a pointer is provided to the record to be deleted. For a decrease-key operation, a pointer is provided to the record on

142 which the operation is to be performed. An algorithm performs the following operations on the list in this order: Θ(N) delete, O(log N) insert, O(log N) find, and Θ(N) decrease-key What is the time complexity of all these operations put together (A) O(Log 2 N) (B) O(N) (C) O(N 2 ) (D) Θ(N 2 Log N) Answer: (C)

143 INTRODUCTION: The tree is one of the most powerful of the advanced data structures and it often pops up in even more advanced subjects such as AI and compiler design. Surprisingly though the tree is important in a much more basic application - namely the keeping of an efficient index. Whenever you use a database there is a 99% chance that an index is involved somewhere. The simplest type of index is a sorted listing of the key field. This provides a fast lookup because you can use a binary search to locate any item without having to look at each one in turn. The trouble with a simple ordered list only becomes apparent once you start adding new items and have to keep the list sorted - it can be done reasonably efficiently but it takes some advanced juggling. A more important defect in these days of networking and multi-user systems is related to the file locking properties of such an index. Basically if you want to share a linear index and allow more than one user to update it then you have to lock the entire index during each update. In other words a linear index isn't easy to share and this is where trees come in - I suppose you could say that trees are shareable. A tree is a data structure consisting of nodes organised as a hierarchy. Tree represents nodes connected by edges. We'll going to discuss binary tree or binary search tree specifically. Binary Tree is a special data structure used for data storage purposes. A binary tree has a special condition that each node can have two children at maximum. A binary tree have benefits of both an ordered array and a linked list as search is as quick as in sorted array and insertion or deletion operation are as fast as in linked list.

144 Terms Following are important terms with respect to tree. Path Path efe s to se ue e of odes alo g the edges of a t ee. Root Node at the top of the t ee is alled oot. The e is o l o e oot pe t ee a d o e path from root node to any node. Parent A ode e ept oot ode has o e edge up a d to a ode alled pa e t. Child Node elo a gi e ode o e ted its edge do a d is alled its hild ode. Leaf Node hi h does ot ha e a hild ode is alled leaf ode. Subtree Su tree represents descendents of a node. Visiting Visiti g efe s to he ki g alue of a ode he o t ol is o the ode. Traversing T a e si g ea s passi g th ough odes i a spe ifi o de. Levels Le el of a ode ep ese ts the ge e atio of a ode. If root node is at level 0, then its next child node is at level 1, its grandchild is at level 2 and so on. keys Ke ep ese ts a alue of a ode ased o hi h a sea h ope atio is to e a ied out for a node.

145 Trees can be used for underlying structure in decision-making algorithms to represent Heaps (Priority Queues) to represent B-Trees (fast access to database) for storing hierarchies in organizations for file system Binary Tree: A binary tree is a tree like structure that is rooted and in which each node has at most two children and each child of a node is designated as its left or right child. In this kind of tree, the maximum degree of any node is at most 2. A binary tree T is defined as a finite set of elements such that T is empty (called NULL tree or empty tree). T contains a distinguished Node R called the root of T and the remaining nodes of T form an ordered pair of disjoint binary trees T 1 and T 2. Any node N in a binary tree T has either 0, 1 or 2 successors. Level l of a binary tree T can have at most 2 l nodes. Number of nodes on each level i of binary tree is at most 2 i The number n of nodes in a binary tree of height h is atleast n = h + 1 and atmost n = 2 h+1 1, where h is the depth of the tree. Depth d of a binary tree with n nodes >= floor(lg n)

146 d = floor(lg N) ; lower bound, when a tree is a full binary tree d = n 1 ; upper bound, when a tree is a degenerate tree Creation of a binary tree void insert(node ** tree, int val) node *temp = NULL; if(!(*tree)) temp = (node *)malloc(sizeof(node)); temp->left = temp->right = NULL; temp->data = val; *tree = temp; return; if(val < (*tree)->data) insert(&(*tree)->left, val); else if(val > (*tree)->data) insert(&(*tree)->right, val); Search an element into binary tree node* search(node ** tree, int val) if(!(*tree))

147 return NULL; if(val == (*tree)->data) return *tree; else if(val < (*tree)->data) search(&((*tree)->left), val); else if(val > (*tree)->data) search(&((*tree)->right), val); Delete an element from binary tree void deltree(node * tree) if (tree) deltree(tree->left); deltree(tree->right); free(tree); Extended Binary Trees: 2. Trees or Strictly Binary Trees If every non-terminal node in a binary tree consist of non-empty left subtree and right subtree. In other words, if any node of a binary tree has either 0 or 2 child nodes, then such tree is known as strictly binary tree or extended binary tree or 2- tree. Complete Binary Tree: A complete binary tree is a tree in which every level, except possibly the

148 last, is completely filled. A Complete binary tree is one which have the following properties Which can have 0, 1 or 2 children. In which first, we need to fill left node, then right node in a level. In which, we can start putting data item in next level only when the previous level is completely filled. A complete binary tree of the height h has between 2 h and 2 (h+1) -1 nodes. Tree Traversal: Three types of tree traversal are given below Preorder Process the root R. Traverse the left subtree of R in preorder. Traverse the right subtree of R in preorder. /* Recursive function to print the elements of a binary tree with preorder traversal*/ void preorder(struct btreenode *node) if (node!= NULL) printf("%d", node->data); preorder(node->left); preorder(node->right);

149 Inorder Traverse the left subtree of R in inorder. Process the root R. Traverse the right subtree of R in inorder. /* Recursive function to print the elements of a binary tree with inorder traversal*/ void inorder(struct btreenode *node) if (node!= NULL) inorder(node->left); printf("%d", node->data); inorder(node->right); Postorder Traverse the left subtree of R in postorder. Traverse the right subtree of R in postorder. Process the root R. /* Recursive function to print the elements of a binary tree with postorder traversal*/ void postorder(struct btreenode *node)

150 if (node!= NULL) postorder(node->left); postorder(node->right); printf("%d", node->data); OBJECTIVE QUESTIONS AND ANSWERS 1. The height of a BST is given as h. Consider the height of the tree as the no. of edges in the longest path from root to the leaf. The maximum no. of nodes possible in the tree is? a) 2 h-1-1 b) 2 h+1-1 c) 2 h +1 d) 2 h-1 +1 ANSWER: B 2. The no of external nodes in a full binary tree with n internal nodes is? a) n b) n+1 c) 2n d) 2n + 1 ANSWER: B

151 3. The difference between the external path length and the internal path length of a binary tree with n internal nodes is? a) 1 b) n c) n + 1 d) 2n ANSWER: D 4. Suppose a binary tree is constructed with n nodes, such that each node has exactly either zero or two children. The maximum height of the tree will be? a) (n+1)/2 b) (n-1)/2 c) n/2-1 d) (n+1)/2-1 ANSWER: B 5. Which of the following statement about binary tree is CORRECT? a) Every binary tree is either complete or full b) Every complete binary tree is also a full binary tree c) Every full binary tree is also a complete binary tree d) A binary tree cannot be both complete and full ANSWER: C 6. Suppose we have numbers between 1 and 1000 in a binary search tree and want to search for the number 363. Which of the following sequence could not be the sequence of the node examined?

152 a) 2, 252, 401, 398, 330, 344, 397, 363 b) 924, 220, 911, 244, 898, 258, 362, 363 c) 925, 202, 911, 240, 912, 245, 258, 363 d) 2, 399, 387, 219, 266, 382, 381, 278, 363 ANSWER: C 7. In full binary search tree every internal node has exactly two children. If there are 100 leaf nodes in the tree, how many internal nodes are there in the tree? a) 25 b) 49 c) 99 d) 101 ANSWER: C 8. Which type of traversal of binary search tree outputs the value in sorted order? a) Pre-order b) In-order c) Post-order d) None ANSWER: B 9. Suppose a complete binary tree has height h>0. The minimum no of leaf nodes possible in term of h is? a) 2 h -1 b) 2 h c) 2 h -1 d) 2 h +1 ANSWER: C

153 10. A 2-3 is a tree such that a) All internal nodes have either 2 or 3 children b) All path from root to leaves have the same length The number of internal nodes of a 2-3 tree having 9 leaves could be a) 4 b) 5 c) 6 d) 7 ANSWER: A, D 11. If a node having two children is to be deleted from binary search tree, it is replaced by its a) In-order predecessor b) In-order successor c) Pre-order predecessor d) None ANSWER: B 12. A binary search tree is formed from the sequence 6, 9, 1, 2, 7, 14, 12, 3, 8, 18. The minimum number of nodes required to be added in to this tree to form an extended binary tree is? a) 3 b) 6 c) 8 d) 11 ANSWER: D

154 13. In a full binary tree, every internal node has exactly two children. A full binary tree with 2n+1 nodes contains a) n leaf node b) n internal nodes c) n-1 leaf nodes d) n-1 internal nodes ANSWER: B 14. the run time for traversing all the nodes of a binary search tree with n nodes and printing them in an order is a) O(nlg(n)) b) O(n) O d) O(log(n)) ANSWER: B 15. When a binary tree is converted in to an extended binary tree, all the nodes of a binary tree in the external node becomes a) Internal nodes b) External nodes c) Root nodes d) None ANSWER: A

155 16. If n numbers are to be sorted in ascending order in O(nlogn) time, which of the following tree can be used a) Binary tree b) Binary search tree c) Max-heap d) Min-heap ANSWER: D 17. If n elements are sorted in a binary search tree. What would be the asymptotic complexity to search a key in the tree? a) O(1) b) O(logn) c) O(n) d) O(nlogn) ANSWER: C 18. If n elements are sorted in a balanced binary search tree. What would be the asymptotic complexity to search a key in the tree? a) O(1) b) O(logn) c) O(n) d) O(nlogn) ANSWER: B

156 19. The minimum number of elements in a heap of height h is a) 2 h+1 b) 2 h c) 2 h -1 d) 2 h-1 ANSWER: B 20. The maximum number of elements in a heap of height h is a) 2 h+1-1 b) 2 h c) 2 h -1 d) 2 h -1 ANSWER: A 21. A threaded binary tree is a binary tree in which every node that does not have right child has a thread to its a) Pre-order successor b) In-order successor c) In-order predecessor d) Post-order successor ANSWER: B

157 22. In which of the following tree, parent node has a key value greater than or equal to the key value of both of its children? a) Binary search tree b) Threaded binary tree c) Complete binary tree d) Max-heap ANSWER: D 23. A binary tree T has n leaf nodes. The number of nodes of degree 2 in T is a) log 2 n b) n-1 c) n d) 2 n ANSWER: B 24. A binary search tree is generated by inserting in order the following integers: 50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24 The number of the node in the left sub-tree and right sub-tree of the root, respectively, is a) (4, 7) b) (7, 4) c) (8, 3) d) (3, 8) ANSWER: B

158 Binary search tree Type Tree Invented 1960 Invented by P.F. Windley, A.D. Booth, A.J.T. Colin, and T.N. Hibbard Average Time complexity in big O notation Worst case Space Θ n) O(n) Search Θ log n) O(n) Insert Θ log n) O(n) Delete Θ log n) O(n) A binary search tree of size 9 and depth 3, with 8 at the root. The leaves are not drawn. Binary search trees (BST), sometimes called ordered or sorted binary trees, are a particular type of containers: data structures that store "items" (such as numbers, names etc.) in memory. Binary search trees keep their keys in sorted order, so that lookup and other operations can use the principle of binary search: when looking for a key in a tree (or a place to insert a new key), they traverse the tree from root to leaf, making comparisons to keys stored in the nodes of the tree and deciding, based on the comparison, to continue searching in the left or right subtrees. Several variants of the binary search tree have been studied in computer science; this article deals primarily with the basic type, making references to more advanced types when appropriate.

HISTORY OF C LANGUAGE. Facts about C. Why Use C?

HISTORY OF C LANGUAGE. Facts about C. Why Use C? 1 HISTORY OF C LANGUAGE C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating

More information

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section : CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart ANS. Flowchart:- A diagrametic reperesentation of program is known as flowchart Symbols Q-2) Explain basic structure of c language

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands Introduction Operators are the symbols which operates on value or a variable. It tells the compiler to perform certain mathematical or logical manipulations. Can be of following categories: Unary requires

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

Decision Making in C

Decision Making in C Decision Making in C Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CprE 288 Introduction to Embedded Systems Exam 1 Review.  1 CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

A flow chart is a graphical or symbolic representation of a process.

A flow chart is a graphical or symbolic representation of a process. Q1. Define Algorithm with example? Answer:- A sequential solution of any program that written in human language, called algorithm. Algorithm is first step of the solution process, after the analysis of

More information

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered )   FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING ( Word to PDF Converter - Unregistered ) http://www.word-to-pdf-converter.net FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING INTRODUCTION TO C UNIT IV Overview of C Constants, Variables and Data Types

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard.

In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. C Quick Guide https://www.tutorialspoint.com/cprogramming/c_quick_guide.htm Copyright tutorialspoint.com C Language Overview C is a general purpose, high level language that was originally developed by

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

C Programming Class I

C Programming Class I C Programming Class I Generation of C Language Introduction to C 1. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) 2. In 1970, Ken Thompson created a language

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 30, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above P.G.TRB - COMPUTER SCIENCE Total Marks : 50 Time : 30 Minutes 1. C was primarily developed as a a)systems programming language b) general purpose language c) data processing language d) none of the above

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7. Iulian Năstac Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

More information

CHW 469 : Embedded Systems

CHW 469 : Embedded Systems CHW 469 : Instructor: Dr. Ahmed Shalaby http://bu.edu.eg/staff/ahmedshalaby14# https://piazza.com/fci.bu.edu.eg/spring2017/chw469/home Assignment no. 3 kindly read the following paper [Software Engineering

More information

Technical Questions. Q 1) What are the key features in C programming language?

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

CS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam Multimedia Programming 2004 Lecture 2 Erwin M. Bakker Joachim Rijsdam Recap Learning C++ by example No groups: everybody should experience developing and programming in C++! Assignments will determine

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

High Performance Computing in C and C++

High Performance Computing in C and C++ High Performance Computing in C and C++ Rita Borgo Computer Science Department, Swansea University Summary Introduction to C Writing a simple C program Compiling a simple C program Running a simple C program

More information

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps 1 True and False in C False is represented by any zero value The int expression having the

More information

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one. http://www.tutorialspoint.com/go/go_operators.htm GO - OPERATORS Copyright tutorialspoint.com An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

More information

Variation of Pointers

Variation of Pointers Variation of Pointers 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

More information

Part I Part 1 Expressions

Part I Part 1 Expressions Writing Program in C Expressions and Control Structures (Selection Statements and Loops) Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague

More information

C Programming Multiple. Choice

C Programming Multiple. Choice C Programming Multiple Choice Questions 1.) Developer of C language is. a.) Dennis Richie c.) Bill Gates b.) Ken Thompson d.) Peter Norton 2.) C language developed in. a.) 1970 c.) 1976 b.) 1972 d.) 1980

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

Programming. Elementary Concepts

Programming. Elementary Concepts Programming Elementary Concepts Summary } C Language Basic Concepts } Comments, Preprocessor, Main } Key Definitions } Datatypes } Variables } Constants } Operators } Conditional expressions } Type conversions

More information

Preview from Notesale.co.uk Page 6 of 52

Preview from Notesale.co.uk Page 6 of 52 Binary System: The information, which it is stored or manipulated by the computer memory it will be done in binary mode. RAM: This is also called as real memory, physical memory or simply memory. In order

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Introduction to C Final Review Chapters 1-6 & 13

Introduction to C Final Review Chapters 1-6 & 13 Introduction to C Final Review Chapters 1-6 & 13 Variables (Lecture Notes 2) Identifiers You must always define an identifier for a variable Declare and define variables before they are called in an expression

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Quick Reference Guide

Quick Reference Guide SOFTWARE AND HARDWARE SOLUTIONS FOR THE EMBEDDED WORLD mikroelektronika Development tools - Books - Compilers Quick Reference Quick Reference Guide with EXAMPLES for Basic language This reference guide

More information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

Functions. (transfer of parameters, returned values, recursion, function pointers).

Functions. (transfer of parameters, returned values, recursion, function pointers). Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value

More information

KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur

KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur Bachelor of Engineering First Year Subject Name: Computer Programming Objective: 1. This course is designed to provide a brief study of the C programming

More information

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

Writing Program in C Expressions and Control Structures (Selection Statements and Loops) Writing Program in C Expressions and Control Structures (Selection Statements and Loops) Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague

More information

C - Basic Introduction

C - Basic Introduction C - Basic Introduction C is a general-purpose high level language that was originally developed by Dennis Ritchie for the UNIX operating system. It was first implemented on the Digital Equipment Corporation

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

edunepal_info

edunepal_info facebook.com/edunepal.info @ edunepal_info C interview questions (1 125) C interview questions are given with the answers in this website. We have given C interview questions faced by freshers and experienced

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below: QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

More information

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

More information

Operators in C. Staff Incharge: S.Sasirekha

Operators in C. Staff Incharge: S.Sasirekha Operators in C Staff Incharge: S.Sasirekha Operators An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Disclaimer The slides are prepared from various sources. The purpose of the slides is for academic use only Operators in C C supports a rich set of operators. Operators

More information

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants Data types, variables, constants Outline.1 Introduction. Text.3 Memory Concepts.4 Naming Convention of Variables.5 Arithmetic in C.6 Type Conversion Definition: Computer Program A Computer program is a

More information

Basics of Programming

Basics of Programming Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

More information

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g. 1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object

More information

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and #include The Use of printf() and scanf() The Use of printf()

More information

Operators & Expressions

Operators & Expressions Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

4.1. Structured program development Overview of C language

4.1. Structured program development Overview of C language 4.1. Structured program development 4.2. Data types 4.3. Operators 4.4. Expressions 4.5. Control flow 4.6. Arrays and Pointers 4.7. Functions 4.8. Input output statements 4.9. storage classes. UNIT IV

More information

Computers Programming Course 6. Iulian Năstac

Computers Programming Course 6. Iulian Năstac Computers Programming Course 6 Iulian Năstac Recap from previous course Data types four basic arithmetic type specifiers: char int float double void optional specifiers: signed, unsigned short long 2 Recap

More information

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value. 3. EXPRESSIONS It is a sequence of operands and operators that reduce to a single value. Operator : It is a symbolic token that represents an action to be taken. Ex: * is an multiplication operator. Operand:

More information

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR.  VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS S.LAWRENCE CHRISTOPHER, M.C.A., B.Ed., LECTURER IN COMPUTER SCIENCE PONDICHERRY

More information

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah Lecturer Department of Computer Science & IT University of Balochistan 1 Outline p Introduction p Program development p C language and beginning with

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information