c language - nizamabad info & data structures.doc · web viewincludes: ( c & data...

148
C & Data Structures Includes: C & Data Structures Notes C & Data Structures Programs C & Data Structures Interview Questions 1

Upload: doxuyen

Post on 20-Apr-2018

221 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

C & Data Structures

Includes:

C & Data Structures Notes

C & Data Structures Programs

C & Data Structures Interview Questions

1

Page 2: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

CONTENTS Page No 1. C Language Introduction 3-3 2. Algorithm 4-4

3. Flowchart 5-6

4. Program 7-9

5. Constants 10-19 6. Variables 20-20

7. Data types 21-21

8. Operators 22-26 9. Expressions 27-27

10. Input and output 28-31

11. Decision Making 32-35

12. Loops 36-41

13. Arrays 42-43

14. Strings 44-44

15. Functions 45-45

16. Pointers 46-48

17. Structures 49-50

18. Unions 51-51

19. Files 52-55

20. Data Structures 56-82

21. Important Programs 83-107

22. C Language Interview Questions 108-118

2

Page 3: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

1. C LANGUAGE INTRODUCTION

C language is the implementation language. UNIX Operating system is developed by using C Language. Various other software programming languages is developed using C Language. It is one of the basic programming language.

The programming languages are mainly developed for the purpose of the computer to work efficiently and accurately with out any errors. The input given by the user is processed and the accurate result i.e. the output is given by the computer. All these are happening because of the installation of some of the programming languages to get the accurate output for the User. As C is the procedural language, where as the programming language JAVA is the purely Object Oriented language. Procedural in the sense, each and every instruction is executed sequentially. A general another language called Basic Combined Programming Language (BCPL) was developed by Martin Richards at Cambridge University with some additional features than CPL.

A language called ‘B’ was developed by the Ken Thompson at AT &T’s Bell labs. But like BCPL and B turned out to be very specific. Dennis Ritchie developed a language with some additional features of BCPL and B which is very simple, relatively good programming efficiency and a relatively good machine efficiency called ‘C’ language, consequently the ANSI (American National Standard Institute) has began to work on a standardized definition of the ‘C’ language this make it still powerful.

C is a Middle Level Language. C stands between the two categories Low Level Language nor a High Level Language. It is a Middle Level Language. It means it performs the task of Low Level Language as well as High Level Language. Set of instructions to carry out particular task is known as a Program. As C is a procedural language each instruction is executed sequentially one after the other.

Every individual requires a language for communication. Similarly, “C” is one of the language which can be understand by the computer and processes the execution with the instructions. There are many languages to develop softwares.

The execution starts from main() in C Language.

The concept of programming is very important to write any program, algorithm is the best approach to start and the flowchart for diagrammatic representation helps to build the program easily in an efficient way. The easy way to learn “C” is to understand each and every concept carefully. Try to do more programs and practice, with in few days you will get the concept easily.

3

Page 4: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

2. ALGORITHM

Algorithm is the step-by-step process of performing an operation. The algorithm defines the concept of the program task. The developer before implementing the code, writes the algorithm for better understanding.

Example:

1. Algorithm for addition of two numbers.

Step 1: Start

Step 2: Read a,b,c

Step 3: c=a+b

Step 4: Print c

Step 5: Stop

2. Algorithm for subtraction of two numbers.

Step 1: Start

Step 2: Read a,b,c

Step 3: c=a-b

Step 4: Print c

Step 5: Stop

In this way the algorithm is written to perform the given task. The algorithm which can be executed quickly and easy to be developed can be used for the development which provides flexibility and clarity for the C program. The algorithm is written first to understand the flow of execution and concept.

4

Page 5: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

3. FLOWCHART

Flowchart is the pictorial representation, which is shown diagrammatically for better understanding. Different symbols are used for representing the flow of data execution.

These are the different shapes used to represent the flow of execution depending upon the program. By looking at the diagram we can easily understand the program. Diagrammatic representation is the one of the good way to understand the concept of program.

5

A rectangle indicates any processing operation except a decision.

A diamond indicates a decision

A parallelogram indicates an input or output operation

An oval indicates beginning or ending point of a program

A small circle indicates connection between two points in a flowchart

Arrow indicates direction of flow through the flowchart

Page 6: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Example: Flowchart for addition of two numbers

In this way the flowchart is represented diagrammatically,

1) Start is used to represent the process is started2) Read a,b,c means , initializing the variables and read the a,b values3) C=a+b means the values of a and b gets added and sent to the variable ‘c’4) Print c, means the added value which is in ‘c’ gets printed.5) Stop, means the process is finished.

By looking at the diagram we can understand the flow of execution with clarity. It starts with oval shaped “Start” and ends with oval shape “Stop”.

6

Read a,b,c

c=a+b

Print c

Start

Stop

Page 7: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

4. PROGRAM

Set of instructions to carry out particular task is known as a Program. As C is a procedural language each instruction is executed sequentially one after the other.

Example:

1. Write a sample Program

main(){ clrscr(); printf("Hello"); getch(); return 0;}

Output:

Hello

Explanation:

Here, The execution starts from main(), the clrscr() clears the screen neatly, the printf statement “Hello” is printed as output.

2. Write a sample Program

main(){ clrscr(); printf("Hello \n"); printf("Good "); getch(); return 0;}

Output:

Hello Good

Explanation:

Here, The execution starts from main(), the clrscr() clears the screen neatly, the printf statement “Hello” is printed and “\n” means in the next line “Good” is printed as output.

7

Page 8: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

3. Write a Program to find addition of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=10,b=10,c; c=a+b; printf(“ Value of c is %d”, c); getch();}

Output:

Value of c is 20

Explanation: After the main function, two variables a and b are declared as a=10 and b=10 , then c=a+b means both the values of a and b are added and stored in variable “c”. so the value in “c” becomes 20. Finally the “printf” statement is used to print the output on the moniter , here the value 20 is printed.

4. Write a Program to find subtraction of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=20,b=10 c=a-b; printf(“ Value of c is %d”, c); getch();}

Output: Value of c is 10

Explanation:

After the main function, two variables a and b are declared as a=20 and b=10 , then c=a-b means both the values of a and b are subtracted and stored in variable “c”. so the value in “c” becomes 10. Finally the “printf” statement is used to print the output on the moniter, here the value 10 is printed.

8

Page 9: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

5. Write a program to find the multiplication of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=10,b=10 c=a*b; printf(“ Value of c is %d”, c); getch();}

Output: Value of c is 100

Explanation:

After the main function, two variables a and b are declared as a=10 and b=10 , then c=a*b means both the values of a and b are multiplied and stored in variable “c”. so the value in variable “c” becomes 100. Finally the “printf” statement is used to print the output on the moniter , here the value 100 is printed.

6. Write a program to find the division of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=20,b=10 c=a/b; printf(“ Value of c is %d”, c); getch();}

Output: Value of c is 2

Explanation:

After the main function, two variables a and b are declared as a=20 and b=10 , then c=a/b means both the values of a and b are multiplied and stored in c. so the value in variable “c” becomes 2. Finally the “printf” statement is used to print the output on the moniter , here the value 2 is printed.The difference between ‘a/b’ and ‘a%b’ is a/b prints output quotient and a%b prints the remainder. In the previous program if c=a%b then the output will be “0”.

9

Page 10: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

5. CONSTANTS

C Tokens:

Identifiers = e.g (total, value)Keywords = e.g (int, char)Constants = e.g (pi=3.14)Strings = e.g (“prince”)Operators = e.g (+, -)Special symbols = e.g (#, $)

Constants:

The values which can’t be changed during program execution are known as Constants.

C Constants can be classified into 2 types:

1) Numeric Constants2) Character Constants

1) Numeric Constants are of 2 types: i) Integer Constants: Integer Constants are sequence of digits. Example:

Decimal Number – 0 to 9 Octal Number – 0 to 7 Hexa Decimal Number – 0 to 9, A, B, C, D, E, F ii) Real Constants: It is sequence of numeric digits with decimal point. Example: Average=85.5;

In a program if we want to declare a value as a constant through out the program till execution then the declaration is done as,

Example:

const int number=1;

Here, ‘const’ means it’s a Constant , the Variable number=1 will remain same through out the program execution.

10

Page 11: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

In this way the Constant values get assigned and run till the program execution finishes.Examples:

const float pi=3.14

const int rank=1;

In the above example as the ‘pi’ value is always 3.14, is remains constant and hence declared as a constant.

#include<stdio.h> main(){ float radius,area,circumference,pi=3.14; printf(“Enter radius”); scanf(“%f”,&radius); area=pi*radius*radius; circumference=2*pi*radius; printf(“Area=%f”,area); printf(“Circumference=%f”,circumference);}

Output:

Enter radius 1Area=3.14Circumference=6.28

Explanation:

The execution starts from main(), the first statement, radius, area, circumference are declared as float because it may have decimal values (1.3, 0.14 etc..,) , the printf statement asks to “Enter radius”, the scanf statement “&radius” stores the radius value. Now the area and circumference are calculated as per the formula, and last two printf statements area and circumference are printed as output.

11

Page 12: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

C Language Keywords

Standard ANSI C recognizes the following keywords:

autobreakcasecharconstcontinuedefaultdodoubleelseenumexternfloatforgotoifintlongregisterreturnshortsignedsizeofstaticstructswitchtypedefunionunsignedvoidvolatilewhile

12

Page 13: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

auto

Defines a local variable as having a local lifetime.

Keyword auto uses the following syntax:

[auto] data-definition;

As the local lifetime is the default for local variables, auto keyword is extremely rarely used. 

break

Passes control out of the compound statement.

The break statement causes control to pass to the statement following the innermost enclosing while, do, for, or switch statement.

The syntax is simply

break;

const

Makes variable value or pointer parameter unmodifiable.

When const is used with a variable, it uses the following syntax:

const variable-name [ = value];

In this case, the const modifier allows you to assign an initial value to a variable that cannot later be changed by the program. For example,

const my_age = 32;

Any assignments to 'my_age' will result in a compiler error. However, such declaration is quite different than using

continue

Passes control to the begining of the loop.

continue causes control to pass to the end of the innermost enclosing while, do, or for statement, at which point the loop continuation condition is re-evaluated. The syntax is simply

continue;

13

Page 14: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

do-while loop.

Keyword do is usually used together with while to make another form of repeating statement. Such form of the loop uses the following syntax:

do statement while (expression)statement, which is usually a compound statement, is executed repeatedly as long as the value of expression remains non-zero.

enum

Defines a set of constants of type int.

The syntax for defining constants using enum is

enum [tag] {name [=value], ...};

The set can optionally be given a type tag name with tag. name is the name of a constant that can optionally be assigned the (constant) value of value, etc. For example,

enum Numbers {One = 1, Two = 2, Three = 3, Four = 4, Five = 5};

If value is missing, then a value is assumed to be the value of the previous constant in the list + 1. If this is the first constant in the list, the default value is 0. 

If you give a type tag name, then you can declare variables of enumerated type using

enum tag variable-names;

For example,

enum Numbers x, y, z;

declares three variables x, y and z, all of type Numbers (they are, in fact, integer variables). More precise, 'enum tag becomes a new type which is equal in rights with any built-in type.

extern

Indicates that an identifier is defined elsewhere.

Keyword extern indicates that the actual storage and initial value of a variable, or body of a function, is defined elsewhere, usually in a separate source code module. So, it may be applied to data definitions and function prototypes:

extern data-definition;extern function-prototype;

14

Page 15: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

float, double

Floating point data types.

The keyword float usually represents a single precision floating point data type, and double represents a double precision floating point data type. In TIGCC, both float and double (and even long double) are the same. The TI-89 and TI-92 Plus use a non-IEEE floating point format called SMAP II BCD for floating point values. 

These values have a range from 1e-999 to 9.999999999999999e999 in magnitude, with a precision of exactly 16 significant digits. Principally, the exponent range may be as high as 16383, but a lot of math routines do not accept exponents greater than 999.

For loop

For-loop is yet another kind of loop. It uses for keyword, with the following syntax:

for ([expr1]; [expr2]; [expr3]) statement

statement is executed repeatedly until the value of expr2 is 0. Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop. After each iteration of the loop, expr3 is evaluated. This is usually used to increment a loop counter. In fact, the for-loop is absolutely equivalent to the following sequence of statements:

goto

Unconditionally transfer control.

goto may be used for transferring control from one place to another. The syntax is:

goto identifier;

Control is unconditionally transferred to the location of a local label specified by identifier. For example,

Again: ...goto Again;Jumping out of scope (for example out of the body of the for loop) is legal, but jumping into a scope (for example from one function to another) is not allowed. 

15

Page 16: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

if, else

Conditional statement.

Keyword if is used for conditional execution. The basic form of if uses the following syntax:

if (expression) statement1

Alternatively, if may be used together with else, using the following syntax:

if (expression) statement1else statement2If expression is nonzero when evaluated, then statement1 is executed. In the second case, statement2 is executed if the expression is 0. 

int, char

Basic data types (integer and character).

Variables of type int are one machine-type word in length. They can be signed (default) or unsigned, which means that in this configuration of the compiler they have by default a range of -32768 to 32767 and 0 to 65535 respectively,

register

Tells the compiler to store the variable being declared in a CPU register.

In standard C dialects, keyword auto uses the following syntax:

register data-definition;

The register type modifier tells the compiler to store the variable being declared in a CPU register (if possible), to optimize access. For example,

register int i;

return

Exits the function.

return exits immediately from the currently executing function to the calling routine, optionally returning a value. The syntax is:

return [expression];

16

Page 17: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

short, long, signed, unsigned

Type modifiers.

A type modifier alters the meaning of the base type to yield a new type. Each of these type modifiers can be applied to the base type int. The modifiers signed and unsigned can be applied to the base type char. In addition, long can be applied to double. 

When the base type is omitted from a declaration, int is assumed. For example,

long x; // 'int' is impliedunsigned char ch;signed int i; // 'signed' is defaultunsigned long int l; // 'int' is accepted, but not needed

In this implementation of the compiler, the valid range of valid data types is as listed in the following table:

short int -32768 to 32767long int -2147483648 to 2147483647signed char -128 to 127signed int -32768 to 32767 (signed is default)signed short int -32768 to 32767signed long int -2147483648 to 2147483647unsigned char 0 to 255unsigned int 0 to 65535unsigned short int 0 to 65535unsigned long int 0 to 4294967295

sizeof

Returns the size of the expression or type.

Keyword sizeof is, in fact, an operator. It returns the size, in bytes, of the given expression or type (as type size_t). Its argument may be an expression of a type name:

sizeof expressionsizeof (type)

For example,

workspace = calloc (100, sizeof (int));memset(buff, 0, sizeof buff);nitems = sizeof (table) / sizeof (table[0]);

17

Page 18: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

static

Preserves variable value to survive after its scope ends.

Keyword static may be applied to both data and function definitions:

static data-definition;static function-definition;

struct

Groups variables into a single record.

The syntax for defining records is:

struct [struct-type-name] { [type variable-names]; ... } [structure-variables];

switch, case, default

Branches control.

switch causes control to branch to one of a list of possible statements in the block of statements. The syntax is

switch (expression) statement

typedef

Creates a new type.

The syntax for defining a new type is

typedef type-definition identifier;

union

Groups variables which share the same storage space.

A union is similar to a struct, except it allows you to define variables that share storage space. The syntax for defining unions is:

union [union-type-name] { type variable-names;

18

Page 19: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

... } [union-variables] ;

void

Empty data type.

When used as a function return type, void means that the function does not return a value. For example,

void hello (char *name){ printf("Hello, %s.", name);}

volatile

Indicates that a variable can be changed by a background routine.

Keyword volatile is an extreme opposite of const. It indicates that a variable may be changed in a way which is absolutely unpredictable by analyzing the normal program flow (for example, a variable which may be changed by an interrupt handler). This keyword uses the following syntax:

volatile data-definition;

Every reference to the variable will reload the contents from memory rather than take advantage of situations where a copy can be in a register.

while

Repeats execution while the condition is true.

Keyword while is the most general loop statements. It uses the following syntax:

while (expression) statement

statement is executed repeatedly as long as the value of expression remains nonzero. The test takes place before each execution of the statement.

19

Page 20: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

6. VARIABLES

Variable represents some specified type of information, it takes different values during program execution.

Variable Declaration:

datatype a, b, c;

Example: int name; char b;

Initializing variable:

The initializing of variable is done as,

Example: int a=10; char b=’C’

Local Variables:

The Variables declared inside the function block are known as Local Variables.

Example:

main()function() { int a,b;}Hence a, b are declared inside the function() block, these variables are accessed only for that function only.

Global Variables:

The Variables declared above the function main(), are known as Global Variables.

Example:

int a=1,b=2;main(){ fun() -----------; -----------;}

20

Page 21: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Hence a,b, are declared above the function main(), these Variables are accessed for the entire program and inside the fun() also.

7. DATATYPES

The different types of datatypes are,

1) integer2) character3) float4) double

1. Integer: It stores the numbers with in a range. The range starts from -32768 to 32767.

Example: int a=1;

Here, the value 1 is stored in the Variable a. Integer has 2 bytes of memory.

2. Character: The character stores only the single character. Example: char a=’c’; Here the character ‘c’ is stored in ‘a’.Character has 1 byte of memory.

3. Float: This data type is used when the given values are in decimal point.

Example: float a=3.14; Here the value ‘3.14’ is stored in ‘a’.Float has 4 bytes of memory.

4. Double: This data type is used when the given values are in decimal point with greater values.

Example:

double a=2973738.0

Here the value ‘3.14’ is stored in ‘a’.Double has 8 bytes of memory.

21

Page 22: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

If the given values in any of the data types are not with in the specified range, that is if it exceeds its datatype limit then it can’t take the value.

8. OPERATORS

It is a symbol which performs an operation on the operands.

Types of operators:

1) Arithmetic operator2) Relational operator3) Logical operator4) Increment and Decrement operator5) Assignment operator6) Conditional operator7) Bitwise operator8) Special operator

1. Arithmetic operator: It performs arithmetic operations like addition, subtraction, multiplication, division and Modulo division.

Example:

main() { int a=1,b=2,c; c=a+b; printf(“%d”,c); }

Here c=a+b, ‘a’,’b’ are called operands and ‘+’ is called operator.

Explanation:

The execution starts from main(), a, ,b, c values are declared as integer. The a value is assigned as 1, b value is assigned as 2. “c=a+b” means the values of a and b are added. The last printf statement prints the “c” value as 3.

22

Page 23: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

2 Relational operator:

It is used to compare the two or more operands.

Symbol Meaning< Less Than

<= Less than or equal to

> Greater Than

>= Greater than or equal to

= = Equal to

!= Not equal to

Example:

main(){ int a=2,b=1; if(a>b) printf(“ a is big”); else { printf(“b is big”); } } Output:

a is big

Here a>b, the values of a and b are compared and the output is printed.

Explanation:

The a=2 and b=1 are taken, the condition if(a>b) is checked , means (3>1) , yes the condition is true the first printf statement “a is big” is printed.

23

Page 24: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

3. Logical operator:

It is used to combine two or more conditions.

Operator Meaning&& Logical AND

|| Logical OR! Logical NOT

&& - If two are more expressions are true then the statement is executed. || - If at least one is true the statement is executed. ! - It makes true statement false and false statement true.

Example:

main(){ int a=1,b=2; if(a=1 && b=2) { printf(“True”); } else { printf(“False”); }}

Output:

True

Here, if the condition (a=1 && b=2), if both the statements are true then only the output “True” is executed else “False” is executed.

4. Increment and Decrement operator:

Increment operator is used to increment the value, same as the decrement value is mainly used to decrement the value. The variation comes in the pre increment and post increment.

++a is known as pre Increment.a++ is known as post Increment. --a is known as pre Decrement.a- - is known as post Decrement.

24

Page 25: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Example:

main(){ int a=1; printf(“%d”,a++); printf(“%d”,++a);}

Output:

1 3

Explanation:

As the a=1, the first printf statement a++ means the value is first displayed, then incremented. The second printf statement ++a says that the value is first incremented and then displayed , that is the reason in a++ the value first displayed as ‘1’, then it is incremented then became ‘2’, ++a says the value is first incremented and displayed as ‘3’.

5. Assignment operator:

This operator is mainly used to assign the value to another Variable.

Example:

a=1;b=c+d; Here, 1 is assigned to a, and the values of ‘c’ and ‘d’ are added and assigned to b.

6. Conditional operator:

This is mainly checks conditions and executes.

main(){ int a=2,b=1, greater; greater=a>b?a:b; printf(“%d”,greater);}Output:

2

25

Page 26: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

7. Bitwise Operator:

It mainly uses bit level data.

Operator Meaning& Bitwise AND| Bitwise OR^ Bitwise XOR

<< Shift left>> Shift right~ One’s complement

8. Special operator:

The Special operators are,

i) sizeof() operator:

It mainly gives the size of the variable in bytes. Example:

main(){ int b=1; printf(“size of variable b is %d”,sizeof(b));}

Output:

size of variable b is 2

ii) Pointer operators:

Operators Meaning

& It gives address of the variable* It gives value of the variable

26

Page 27: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

9. EXPRESSIONS

The expression can be determined as,

Variable=expression

Example:

int a=(a/b)+c;

Highest priority - *, / , %

Lowest priority - + , -

Example:

a=1, b=2, c=3;

Expression a+b/a+c

a+b/a+c

1+2/1+3

1+2+3

6

Here, the 2/1 is done first because ‘/’ has high priority, then 1+2+3 is added and the result is 6.

Example:

a=2, b=4, c=6

Expression a+b+c/a

a+b+c/a

2+4+6/2

2+4+3

9

27

Page 28: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Here, 6/2 is executed first because ‘/’ has highest priority, then 2+4+3 is added and the result is 9.

10. INPUT AND OUTPUT

Input and output are the two important concepts in C. The data is taken in the form of input and process it and the result is done and executed as output.

The 2 types of input and output statements are,

a. Unformated Input / Output statementb. Formated Input-Output statement

1. Unformated Input / Output statement

2. Formated Input-Output statement

Input Outputgetc()

getchar()gets()

getche()getch()

putc()putchar()

puts()

Input Outputscanf()fscanf()

printf()fprintf()

28

Page 29: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

getchar():

It mainly accepts only one character, for example

#include<stdio.h>#include<conio.h>main(){ char ch; printf(“enter any character”); ch=getchar(); if(isalpha(ch)>0) printf(“It is alphabet”); else if(isdigit(ch)>0) printf(“It is a digit”); else printf(“It is alphanumeric”);}

Explanation:

The variable ‘ch’ is declared , the getchar() takes the entered character and stores in ‘ch’, the condition if(isalpha(ch)>0) means if we entered any alphanumeric then the printf statement “It is alphanumeric is printed”.If we entered digit as ‘1’ or ‘2’ or etc.., the printf statement “It is a digit” is printed.

29

Page 30: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

gets() and puts():

gets() is used to read the string from keyboard.

For example:

#include<stdio.h>#include<conio.h>main(){ char name[10]; printf(“Enter name:”); gets(name); puts(“you entered:”); puts(name); getch();}

Output:

Enter name: princeYou entered: prince

Explanation:

The char[10] means we can enter any string upto 10 characters, the entered string is taken by gets(name) and it is displayed in the moniter by puts(name). If we entered “prince” the output displayed as “prince”.

30

Page 31: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

printf and scanf():

The printf() and scanf() are the unformated input / output statements to read and write the data.

For example:

1. Write a Program to find addition of two numbers

#include<stdio.h>#include<conio.h>main(){ int a,b,c; printf(“Enter two values”); scanf(“%d%d”,&a,&b); c=a+b; printf(“ value of c is %d”, c); getch();}

Output:

Enter two values: 10 10

Value of c is 20

Explanation:

The scanf() function takes the values of ‘a’ and ‘b’ as 10,10 the statement c=a+b means both values a and b are added , the result 20 is printed as output in the printf statement as “ The value of c is 20”.

31

Page 32: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

11. DECISION MAKING

C language has the following control structures,

1. “if” statement2. “if-else” statement3. “Nested if-else” statement

1. “if” statement:The “if” statement is used to decide to execute the statement depending on the condition.

For example:

#include<stdio.h> #include<conio.h> main() { int i; printf(“enter any number”); scanf(“%d”,&i); if(i<5) { printf(“The number is less than 10”); } }

32

Page 33: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

2. “if-else” statement:

The if-else statement is used to check if the condition is true one statement is executed otherwise the other statement is executed.

For example:

#include<stdio.h>#include<conio.h>main(){ int i; printf(“enter any number”); scanf(“%d”,&i); if(i<=5) { printf(“The number is below 5 or 5”); }else { printf(“The number is above 5”); } } Output:

Enter any number: 5

The number is below 5 or 5

Explanation:

Here, the printf statement “ enter any number” is shown in output, if we give the value as 10 , the 10 is stored in “&i” of scanf statement, and the condition (i<=10) is satisfied and the printf statement “The number is below 10 or 10” is printed as output.

33

Page 34: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

3. “Nested if-else” statement:

Example:

#include<stdio.h>#include<conio.h>main(){ int n; printf(“Enter a number:”); scanf(“%d”,&n”); if(n= =1) { printf(“Entered number 1”); } else { if(n= =2) { printf(“Entered number 2”); else printf(“Other number”); }}

Output:

Enter a number:1Entered number 1

Explanation:

Here, the printf statement “Enter a number” is shown on moniter, if our given value is 10 then the printf statement “Entered number 10” is printed as output.

34

Page 35: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

“Switch” statement:

Switch statement is used to check the number of conditions satisfying the given value.

For example:include<stdio.h>include<conio.h>main(){ int i=1; switch(i){ case 1: printf(“I entered one”); break;

case2: printf(“I entered two”); break;

default: printf(“default”); break;}} In “switch” statement the following cases tested and the result is printed as output.

Output:

I entered one

Explanation:

Here, i value is declared as 1, so it is suitable to case1, so the printf statement “I entered one” is printed as output.

35

Page 36: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

12. LOOPS

1. “while” loop2. “do-while” loop3. “for” loop

1. “while” loop:

It’s a repetitive control structure, executes the statement until the condition is false

#include<stdio.h>#include<conio.h>main(){ int i=1; while(i<=10) { printf(“value is %d”,i); i++; }}Here until the i value less value is equal than or equal to 10 the values of i are printed.

Output:

Value is 1Value is 2Value is 3Value is 4Value is 5Value is 6Value is 7Value is 9Value is 10

Explanation:

Here, i value is 1, while(i<=10) is tested as i=1 and it is less than 10 so the printf statement is executed and 1 is printed, now i++ means as “i” value is 1 it will be incremented to 2, again the 2 is less than 10 ,the printf statement is executed and 2 is printed….. the process continues until the “i” value reached 10.

36

Page 37: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

2. “do-while” loop

In this the statement is executed and late the condition is checked.

#include<stdio.h>#include<conio.h>main(){ int i=1; do { printf(“value is %d”,i); i++; }while(i<=10);}

Output:

Value is 1Value is 2Value is 3Value is 4Value is 5Value is 6Value is 7Value is 9Value is 10

Explanation:

Here, i value is 1, the “do” condition gives the value 1, and it is incremented, until the while(i<=10) The difference between while and do-while is, in while first the condition is tested and the value is printed, where as in do-while the value is printed first and later the condition is tested.

37

Page 38: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

3. “for” loop:

#include<stdio.h>#include<conio.h>main(){ int i; for(i=1;i<=10;i++) { printf(“value is %d”,i); }}Output: Value is 1 Value is 2Value is 3Value is 4Value is 5Value is 6Value is 7Value is 8Value is 9Value is 10

Explanation:

Here, i value is 1, the for loop (i=1;i<=10;i++) is tested and the values are printed until i value is equal to 10..

“Break” statement:

#include<stdio.h>#include<conio.h>main(){ int i; for(i=1;i<=10;i++) { if(i= =6) break; printf(“%d”,i);}}

Output:

38

Page 39: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

1 2 3 4 5

Here, when the condition satisfies (i= =6) the loop terminates.

“Continue” statement:

#include<stdio.h>#include<conio.h>main(){ int i,n,sum=0; for(i=1;i<=5;i++) { printf(“enter any number”); scanf(“%d”,&n); if(n<0) continue; else sum=sum+n;} printf(“sum is %d”,sum);}

Here, if the condition (i<0) is true, then it calculates the sum.

39

Page 40: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

“Goto” statement:

#include<stdio.h>#include<conio.h>main(){ int a,b; printf(“enter number”); scanf(“%d%d”,&a,&b); if(a= =b) goto equal; else { printf(“ a and b are not equal”); exit 0; } equal: printf(“a and b are equal”);}

Output: Enter number10 10a and b are equal

Explanation:

Here, if the ‘a’ and ‘b’ values are same, then it goes to “equal:”, hence the printf statement ”a and b are equal” is printed as output.

40

Page 41: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

“Goto” statement:

#include<stdio.h>#include<conio.h>main(){ int a,b; printf(“enter number”); scanf(“%d%d”,&a,&b); if(a= =b) goto equal; else { printf(“ a and b are not equal”); exit 0; } equal: printf(“a and b are equal”);}

Output:

Enter number10 11a and b are not equal

Explanation:

Here, if the ‘a’ and ‘b’ values are same, then it does not goes to “equal:”, hence the printf statement ”a and b are not equal” is printed as output.

41

Page 42: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

13. ARRAYS

Array is the collection of similar datatypes.

Arrays are classified into,

1. One-Dimensional Array2. Two-Dimensional Array

Array Declaration:

int a[5];

It means that “a” is the array name and it has 5 storage locations.

aa[0]a[1]a[2]a[3]a[4]

Example: int rank[3]={10,20,30};

It means the variable rank has 3 elements.

rank[0]rank[1]rank[2]

Example:

#include<stdio.h>#<include<conio.h>main(){ char a[]={‘n’,’a’,’m’,’e’}; int i; clrscr(); for(i=0;i<4;i++) printf(“%c”,a[i]); getch();}

102030

42

Page 43: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Output: Name

Two dimensional array

#include<stdio.h>main(){ int a[4][2]; int i; for(i=0;i<=3;i++) { printf(“Enter roll number and marks:”); scanf(“%d%d”,&a[i][0],&a[i][1]);}for(i=0;i<=3;i++)printf(“student roll no %d marks %d”,a[i][0],a[i][1]);} Output:

Enter roll number and marks: 1201 91

Enter roll number and marks: 1202 92

Enter roll number and marks: 1203 93

Enter roll number and marks: 1204 94

Student roll no 1201 marks 91

Student roll no 1202 marks 92

Student roll no 1203 marks 93

Student roll no 1204 marks 94

Col 0 Col 1 Row 0

Row 1 Row 2 Row 3

1201 911202 921203 931204 94

43

Page 44: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

14. STRINGS

The string is a group of characters, symbols, digits.

Syntax: char name[]=”PRINCE”;

Example:

#include<stdio.h>main(){ char name1[]= “prince”; char name2[]= “good”; strcat(name1,name2); printf(“name1 is %s”,name1); }

Output:

Name1 is princegood

Here in this, the name1 stores prince, name2 stores good , the strcat() is concatenation which combines both and stores in name1 as “princegood”.

strlen = used to find length strcpy = used to copy one string to anotherstrcat = used to combine two stringsstrlwr = used to convert strings into lower casestrupr = used to convert strings into upper case

#include<stdio.h>main(){ char y[30]; printf(“Enter name: “); gets(y);printf(“The name reversed is %s”,strrev(y));}

Output:

Enter name: princeThe name reversed is ecnirp

44

Page 45: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

strrev is used to reverse the string name, so the name of the prince is reversed and printed as ecnirp

15. FUNCTIONS

Example:

#include<stdio.h>main(){ message(); printf(“This is main message”);}message(){ printf(“This is function message\n”);}

Output:

This is function messageThis is main message

Explanation:

Execution starts from main() method, the message() function is called the statement “This is function message” is printed , next “This is main message is printed”.

45

Page 46: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

16. POINTERS

A pointer is a variable it stores address of another variable. It is denoted by “*”

#include<stdio.h>main(){ int num=10; printf(“address of num=%u”,&num); printf(“value of num=%d”,num);}

Output:

address of num= 1354value of num=10

Example Program

#include<stdio.h>main(){ int a=2; int *b; b=&a;

printf(“value of a=%d”,a);

printf(“value of a=%d”,*(&a));

printf(“value of a=%d”,*b);

printf(“address of a=%u”,&a);

}

Output:value of a=2value of a=2value of a=2address of a=4000

46

Page 47: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Call by Value

The process of passing the actual value of the variable, this values are taken by the calling program and can be used inside the function.

Example:

main(){ int a=1, b=2; printf(“Before Calling a and b is%d%d”,a,b); void change(a,b); printf(“After calling a and b is %d%d”,a,b);}void change(x,y)int x,y;{ x=2; y=1; printf(“function changes a and b is %d%d”,x,y);}

Output:

Before Calling a and b is 1, 2function changes a and b is 2, 1After calling a and b is 1,2

47

Page 48: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Call by Reference Calling a function using pointers to pass the addresses of variables .

Example:

main(){ int a=1, b=2; printf(“Before Calling a and b is%d%d”,a,b); void change(&a,&b); printf(“After calling a and b is %d%d”,a,b);}void change(x,y)int x,y;{ x=2; y=1;printf(“function changes a and b is %d%d”,*x,*y);}

Output:

Before Calling a and b is 1, 2function changes a and b is 2, 1After calling a and b is 2,1

48

Page 49: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

17. STRUCTURES

Structure is a collection of dissimilar datatypes.

#include<stdio.h>struct st{ int num; char name[10]; int m1; int m2;};struct st s;void main(){ float tot,avg;printf(“Enter student num,name,marks1,marks2”);scanf(“%d%s%d%d”,&s.num,&s.name,&s.m1,&s.m2);tot=s.m1+s.m2;avg=tot/2;printf(“%d%s%d%d”,s.num,s.name,tot,avg);}

Output:

Enter student num,name,marks1,marks2

1 prince 80 851 prince 80 85

2. Example program on structures.

struct pri { int page; char name[10]; }p;void main() { int i; clrscr(); { printf("Enter page and name"); scanf("%d%s",&p.page,p.name); }

49

Page 50: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

printf("\n%d\t %s\n",p.page,p.name); getch();}

Nested structure:

#include<stdio.h>main(){ struct marks{ int m1;}struct student{ char name[10]; int rollno;struct marks m;}struct student stu;printf(“/n”);printf(“Enter student name: “);scanf(“%d”,&stu.name”);printf(“Enter student marks”);scanf(“%d%d”,&stu.m.m1);printf(“student name is %s”,stu.name);printf(“student marks is %d”,stu.m.m1);}

Output:

Enter student name: princeEnter student marks: 10

Student name is princeStudent marks is 10

50

Page 51: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

18. UNIONS

Union is declared like structure but the difference occurs in the storage location.

#include<stdio.h>#include<conio.h>void main(){ union id; { char branch[20]; int size;};struct student{ char name[30];float rollno;union id details;};static struct student info ={“great”,10.0,”cse”};clrscr();printf(“%d”,sizeof(unionid));printf(“%s%f”,info.name, info.rollno);printf(“%s%d”,info.details.branch);}

Output:

20Great 10.0 cse

51

Page 52: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

19. FILES

A file is a collection of related information that is permanently stored on the disk and allows us to access and alter the information.

File can be opened as

fp=fopen(“file_name”,”mode”);fp= file pointermode= file opening mode

file can be closed as

fclose(file_pointer);

What is a File?

Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a machine decipherable storage media where programs and data are stored for machine usage.

Creating a file and output some data

In order to create files we have to learn about File I/O i.e. how to write data into a file and how to read data from a file. We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type.

/* Program to create a file and write some data the file */#include <stdio.h>#include <stdio.h>main( ){ FILE *fp; char stuff[25]; int index;

52

Page 53: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line."); for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %d\n", stuff, index); fclose(fp); /* close the file before ending program */}The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type.

Reading (r)

When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your Reference Manual for details. Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program.Here is a small program that reads a file and display its contents on screen.

/* Program to display the contents of a file on screen */#include <stdio.h>void main(){ FILE *fopen(), *fp; int c; fp = fopen("prog.c","r"); c = getc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp);}

53

Page 54: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Writing (w)

When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file.Here is the program to create a file and write some data into the file.

#include <stdio.h>int main(){ FILE *fp; file = fopen("file.txt","w"); /*Create a file and add text*/ fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/ fclose(fp); /*done!*/ return 0;}

Appending (a)

When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file.Here is a program that will add text to a file which already exists and there is some text in the file.

#include <stdio.h>int main(){ FILE *fp file = fopen("file.txt","a"); fprintf(fp,"%s","This is just an example :)"); /*append some text*/ fclose(fp); return 0;}

Outputting to the file

The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the

54

Page 55: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement.

Closing a file

To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program.

Reading from a text file

Now for our first program that reads from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it.

#include <stdio.h> main( ) { FILE *fp; char c; funny = fopen("TENLINES.TXT", "r"); if (fp = = NULL) printf("File doesn't exist\n"); else { do { c = getc(fp); /* get one character from the file */ putchar(c); /* display it on the monitor */ } while (c != EOF); /* repeat until EOF (end of file) */ } fclose(fp); }

55

Page 56: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

20. DATA STRUCTURES

What is a linked list?

Linked list is a data structure in which each data item points to the next data item. This "linking" is accomplished by keeping an address variable (a pointer) together with each data item. This pointer is used to store the address of the next data item in the list. The structure that is used to store one element of a linked list is called a node. A node has two parts: data and next address. The data part contains the necessary information about the items of the list, the next address part contains the address of the next node.

Creating Linked Lists:

A special pointer will be used to point to the first node of a linked list. We will call this pointer head. At the beginning, when there are no nodes, head will be NULL (pointer pointing to nowhere). As soon as there is a node in the list, head will contain the address of this first node.

A list with no nodes is called an empty list or a null list.

A NULL Pointer is used to signal the end of a list. The last node will have NULL in its next address part. 

Dynamic Memory Allocation:

The memory to store a node of a linked list is allocated whenever needed. This allocation is made by the help of a function called malloc. malloc is defined in stdlib.h.

The function prototype for malloc is:

void * malloc(size_t size);

Freeing Allocated Memory: Whenever an allocated memory block is not necessary, it may be freed by using free function defined in stdlib.h.void * free( void *block);

Defining a Node:

56

Page 57: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Assume that we will keep information about courses in a linked list. The information consists of the course code, course name, credits, no. of lecture hours, no. of lab hours. Each course will point to the course to which it is a prerequisite.

Simple Node Example:

typedef struct node_s{ int item; /* data consisting of an integer */ struct node_s *next; /* pointer to the next node */} node_t;

Another Node Example:

typedef struct node_s{ char name[NAMELEN]; /* data: name */ int year; /* data: year */ struct node_s *next; /* pointer to the next node */} node_t;

More Complex Node Example:

Data part:

typedef struct{ char code[8]; /* course code */ char name[26];/* course name */ int credits; /* course credits */ int lectures; /* no. of lecture hours */ int labs; /* no. of lab hours */ } course_t;

Node:

typedef struct node_s{ course_t course; /* course information */ struct node_s *next; /* pointer to the next node */ } node_t;

Typedef for Pointer to a node:

typedef node_t* nodeptr;

Declaring a node:

57

Page 58: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

node_t course_node;

Declaring a pointer to a node:

nodeptr ptr; /* ptr is of type nodeptr */node_t *ptr; /* This has exactly the same meaning */Allocating space for a node:ptr = (node_t *) malloc(sizeof(node_t));

Type Casting:

Since malloc returns a void pointer, the return value will be converted to a type which is necessary for the specific use of the pointer. In the above example, the pointer will be used to point to a memory block of type node_t. Conversion to a requested type is possible by an action called casting. It is possible to convert a value temporarily to a different type by placing the requested type in parenthesis just to the beginning of an expression, a value of a function call. 

Examples for casting:int number = 9;double result;

result = (double)number / 2;

Getting a new node:

/* allocates memory for a new node */nodeptr getnode(void){ nodeptr ptr; ptr = (nodeptr) malloc(sizeof(node_t)); return(ptr);}

Actions Related With Linked Lists: (These will be explained in the lecture.)

Adding a node to a Linked List: (a) To the beginning, (b) To the end, (c) Between two nodes.

Traversing a Linked List.

Deleting a node from a Linked List: (a) From the beginning, (b) From the end, (c) A node between two nodes.

Searching a node in a Linked List.

58

Page 59: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Functions Related with Linked Lists:

Add (insert) a new node to the beginning

Add (insert) a new node to the end

Add (insert) a new node after n'th node

Search: a node with a given data

Add (insert) a new node after a node with a given data (uses Search)

Add (insert) a new node before a node with a given data

Traverse all nodes

Delete a node from the beginning

Delete a node from the end

Delete a node with a given data

Delete the n'th node

Modify the data of all nodes in a linked list

Modify data of nodes for a given criteria

59

Page 60: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Doubly Linked Lists

What is a Doubly Linked List?

Doubly Linked List (DLL) is a type of Linked List in which each data item points to the next and also to the previous data item. This "linking" is accomplished by keeping two address variables (pointers) together with each data item. These pointers are used to store the address of the previous and the address of the next data items in the list. 

The structure that is used to store one element of a linked list is called a node like in Linked Lists. 

A node has three parts: data, previous address and next address. 

The data part contains the necessary information about the items of the list, the previous address part contains the address of the previous node, the next address part contains the address of the next node.

60

Page 61: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

STACK

A stack is a list like structure where stack items can only be added or removed from the end of the stack. Just like a plate stack in canteens where plates are added to the top and later removed from the top.

/* Program of stack using array*/

#include#define MAX 5

int top = -1;int stack_arr[MAX];

main(){int choice;while(1){printf("1.Push\n");printf("2.Pop\n");printf("3.Display\n");printf("4.Quit\n");printf("Enter your choice : ");scanf("%d",&choice);switch(choice){case 1 :push();break;case 2:pop();break;case 3:display();break;case 4:exit(1);default:printf("Wrong choice\n");}/*End of switch*/}/*End of while*/}/*End of main()*/

61

Page 62: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

push(){int pushed_item;if(top = = (MAX-1))printf("Stack Overflow\n");else{printf("Enter the item to be pushed in stack : ");scanf("%d",&pushed_item);top=top+1;stack_arr[top] = pushed_item;}}/*End of push()*/

pop(){if(top = = -1)printf("Stack Underflow\n");else{printf("Popped element is : %d\n",stack_arr[top]);top=top-1;}}/*End of pop()*/

display(){int i;if(top = = -1)printf("Stack is empty\n");else{printf("Stack elements :\n");for(i = top; i >=0; i--)printf("%d\n", stack_arr[i] );}}/*End of display()*/

Output:

1.Push2.Pop3.Display4.Quit

Enter your choice1Enter the item to be pushed in stack2

62

Page 63: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Enter your choice1Enter the item to be pushed in stack4Stack elements42

QUEUE

Queue is a data structure that maintain "First In First Out" (FIFO) order. And can be viewed as people queuing up to buy a ticket.

/*Program of queue using array*/

# include# define MAX 5

int queue_arr[MAX];int rear = -1;int front = -1;

main(){int choice;while(1){printf("1.Insert\n");printf("2.Delete\n");printf("3.Display\n");printf("4.Quit\n");printf("Enter your choice : ");scanf("%d",&choice);

switch(choice){case 1 :insert();break;case 2 :del();break;case 3:display();break;case 4:exit(1);default:printf("Wrong choice\n");}/*End of switch*/}/*End of while*/

63

Page 64: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

}/*End of main()*/

insert(){int added_item;if (rear= =MAX-1)printf("Queue Overflow\n");else{if (front= =-1) /*If queue is initially empty */front=0;printf("Input the element for adding in queue : ");scanf("%d", &added_item);rear=rear+1;queue_arr[rear] = added_item ;}}/*End of insert()*/

del(){if (front = = -1 || front > rear){printf("Queue Underflow\n");return ;}else{printf("Element deleted from queue is : %d\n", queue_arr[front]);front=front+1;}}/*End of del() */

display(){int i;if (front = = -1)printf("Queue is empty\n");else{printf("Queue is :\n");for(i=front;i<= rear;i++)printf("%d ",queue_arr[i]);}}/*End of display() */ 

Output:

1.Insert2.Delete3.Display

64

Page 65: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

4.QuitEnter your choice: 1Input the element for adding in queue : 6Enter your choice: 1Input the element for adding in queue : 10Enter your choice: 3Queue is : 6 10

Algorithm for Breadth First Search (BFS)

BFS (){

Initialize Q:Insert the root vertex into Q.While (Q is not empty) {Delete an item from the Q and store it into vertex;If (visited flag of vertex is false) {Visit vertex;Set visited flag of the vertex is equals to true;Insert all the neighbors of the vertex in the Q;}}

BFS CODE IN C:

Code:

/* prog. on bfs */

#include<stdio.h>#include<stdlib.h>#define SIZE 10#define T 1#define F 0#define NULL 0struct edge{ int terminal; struct edge *next;};struct vertex{ int visit; int vertex_no; char info; int path_lenth; struct edge *edge_ptr;};

65

Page 66: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

struct q{ int info; struct q *next;};void table(int,int matrix[SIZE][SIZE],struct vertex vert[SIZE]);struct edge *insert_vertex(int,struct edge *);void bfs(int ,int *dist,struct vertex vert[SIZE]);void output(int,int a[SIZE][SIZE]);void input(int,int a[SIZE][SIZE]);struct q *insert_queue(int vertex_no,struct q *first);struct q *delet_queue(int *vertex_no,struct q *first);struct edge *insert_vertex(int vertex_no,struct edge *first){ struct edge *new1,*current ; new1=(struct edge*)malloc(sizeof(struct edge)); new1->terminal=vertex_no; new1->next=NULL; if(!first) return new1; for(current=first;current->next;current=current->next); current->next=new1; return first;}struct q *insert_queue(int vertex_no,struct q *first){ struct q *new1,*current; new1=(struct q*)malloc(sizeof(struct q)); new1->info=vertex_no; new1->next=NULL; if(!first) return new1; for(current=first;current->next;current=current->next); current->next=new1; return first;}struct q *delet_queue(int *vertex_no,struct q *first){ struct q *previous; if(!first) return NULL; *vertex_no=first->info; first=first->next; free(previous); return first;}void table(int vertex_num,int matrix[SIZE][SIZE],struct vertex vert[SIZE]){ int i,j; for(i=0;i<vertex_num;i++)

66

Page 67: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

{ vert[i].visit=F; vert[i].vertex_no=i+1; vert[i].info='A'+i; vert[i].path_lenth=0; vert[i].edge_ptr=NULL; } for(i=0;i<vertex_num;i++) for(j=0;j<vertex_num;j++) if(matrix[i][j]>0) vert[i].edge_ptr=insert_vertex(j,vert[i].edge_ptr);}void bfs(int index,int *dist,struct vertex vert[SIZE]){ struct q *queue=NULL; struct edge *link; vert[index].visit=T; queue=insert_queue(index,queue); while(queue) { queue=delet_queue(&index,queue); for(link=vert[index].edge_ptr;link;link=link->next) if(vert[link->terminal].visit= =F) { vert[link->terminal].visit=T; vert[link->terminal].path_lenth=vert[index].path_lenth+1; queue=insert_queue(link->terminal,queue); } }}void input(int number,int a[SIZE][SIZE]){ int i,j; printf("input the adjacency matrix is:\n"); for(i=0;i<number;i++) { for(j=0;j<number;j++) scanf("%d",&a[i][j]); printf("\n"); }}void output(int number,int a[SIZE][SIZE]){ int i,j; printf("\n adjacency matrix is:\n"); for(i=0;i<number;i++) { for(j=0;j<number;j++) printf("%d\t",a[i][j]); printf("\n");

67

Page 68: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

}}void main(){ int i,number,index,dist,a[SIZE][SIZE]; struct vertex vert[SIZE]; struct edge *list; clrscr(); printf("\ninput the number of vertices in graph:"); scanf("%d",&number); input(number,a); output(number,a); table(number,a,vert); printf("\ninput the strating vertex 0-%d:",number-1); scanf("%d",&index); dist=0; bfs(index,&dist,vert); printf("\n path lenth of the vertex %c",vert[index].info); printf("\n vertex length vertex complexity\n"); for(i=0;i<number;i++) { printf("\n%c\t\t%d",vert[i].info,vert[i].path_lenth); for(list=vert[i].edge_ptr;list;list=list->next) { printf(" "); putchar(list->terminal+'A'); } } getch();}

68

Page 69: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Algorithm for Depth First Search (DFS)

DFS (){

Initialize stack;Push the root vertex into stack.While (stack is not empty) {Pop an item from the stack and store it into vertex;If (visited flag of vertex is false) {Visit vertex;Set visited flag of the vertex is equals to true;Push all the neighbors of the vertex into stack ;}}

DFS CODE IN C:

Code:

/* prog. on dfs */

#include<stdio.h>#include<stdlib.h>#define SIZE 10#define T 1#define F 0#define NULL 0struct edge{ int terminal; struct edge *next;};struct vertex{ int visit; int vertex_no; char info; int path_lenth; struct edge *edge_ptr;};

69

Page 70: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

void table(int,int matrix[SIZE][SIZE],struct vertex vert[SIZE]);struct edge *insert_vertex(int,struct edge *);void dfs(int ,int *dist,struct vertex vert[SIZE]);void output(int,int a[SIZE][SIZE]);void input(int,int a[SIZE][SIZE]);struct edge *insert_vertex(int vertex_no,struct edge *first){ struct edge *new1,*current ; new1=(struct edge*)malloc(sizeof(struct edge)); new1->terminal=vertex_no; new1->next=NULL; if(!first) return new1; for(current=first;current->next;current=current->next); current->next=new1; return first;}void table(int vertex_num,int matrix[SIZE][SIZE],struct vertex vert[SIZE]){ int i,j; for(i=0;i<vertex_num;i++) { vert[i].visit=F; vert[i].vertex_no=i+1; vert[i].info='A'+i; vert[i].path_lenth=0; vert[i].edge_ptr=NULL; } for(i=0;i<vertex_num;i++) for(j=0;j<vertex_num;j++) if(matrix[i][j]>0) vert[i].edge_ptr=insert_vertex(j,vert[i].edge_ptr);}void dfs(int index,int *dist,struct vertex vert[SIZE]){ struct edge *link; vert[index].visit=T; vert[index].path_lenth= *dist; *dist+=1; for(link=vert[index].edge_ptr;link;link=link->next) if(vert[link->terminal].visit= =F) dfs(link->terminal,dist,vert);}void input(int number,int a[SIZE][SIZE]){ int i,j; printf("input the adjacency matrix is:\n"); for(i=0;i<number;i++) { for(j=0;j<number;j++)

70

Page 71: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

scanf("%d",&a[i][j]); printf("\n"); }}void output(int number,int a[SIZE][SIZE]){ int i,j; printf("\n adjacency matrix is:\n"); for(i=0;i<number;i++) { for(j=0;j<number;j++) printf("%d\t",a[i][j]); printf("\n"); }}void main(){ int i,number,index,dist,a[SIZE][SIZE]; struct vertex vert[SIZE]; struct edge *list; clrscr(); printf("\ninput the number of vertices in graph:"); scanf("%d",&number); input(number,a); output(number,a); table(number,a,vert); printf("\ninput the strating vertex 0-%d:",number-1); scanf("%d",&index); dist=0; dfs(index,&dist,vert); printf("\npath lenth of thevertex %c",vert[index].info); printf("\nvertex lenth vertex complexity\n"); for(i=0;i<number;i++) { printf("\n%c\t\t%d",vert[i].info,vert[i].path_lenth); for(list=vert[i].edge_ptr;list;list=list->next) { printf(" "); putchar(list->terminal+'A'); } } getch();}

71

Page 72: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

SORTING

BUBBLE SORT:

The entered integers are stored in the array A. Here, to sort the data in ascending order, any number is compared with the next numbers for orderliness. i.e. first element A[0] is compared with the second  element A[1]. If forth is greater than the prior element then swapping them, else no change. Then second element is compared with third element, and procedure is continued. Hence, after the first iteration of the outer for loop, largest element is placed at the end of the array. In the second iteration, the comparisons are made till the last but one position and now second largest element is placed at the last but one position. The procedure is traced till the array length.

72

Page 73: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

73

Page 74: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

Bubble sort Image Demo

C program to sort the numbers using Bubble sort

#include<stdio.h>

void main()

{

int A[20], N, Temp, i, j;

clrscr();

printf(“\n\n\t ENTER THE NUMBER OF TERMS…: “);

scanf(“%d”,&N);

printf(“\n\t ENTER THE ELEMENTS OF THE ARRAY…:”);

for(i=0; i<N; i++)

{

scanf(“\n\t\t%d”, &A[i]);

}

for(i=0; i<N-1; i++)

for(j=0; j<N-i;j++)

if(A[j]>A[j+1])

{

Temp = A[j];

A[j] = A[j+1];

A[j+1] = Temp;

}

printf(“\n\tTHE ASCENDING ORDER LIST IS…:\n”);

for(i=0; i<N; i++)

printf(“\n\t\t\t%d”,A[i]);

getch();

}

74

Page 75: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

INSERTION SORT

Here, sorting takes place by inserting a particular element at the appropriate position, that’s why the name-  insertion sorting. In the First iteration, second element A[1] is compared with the first element A[0]. In the second iteration third element is compared with first and second element. In general, in every iteration an element is compared with all the elements before it. While comparing if it is found that the element can be inserted at a suitable position, then space is created for it by shifting the other elements one position up and inserts the desired element at the suitable position. This procedure is repeated for all the elements in the list.If we complement the if condition in this program, it will give out the sorted array in descending order. Sorting can also be done in other methods, like selection sorting and bubble sorting, which follows in the next pages.

75

Page 76: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

76

Page 77: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

C PROGRAM FOR INSERTION SORT

#include<stdio.h>void main(){ int A[20], N, Temp, i, j; clrscr(); printf("\n\n\t ENTER THE NUMBER OF TERMS...: "); scanf("%d", &N); printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:"); for(i=0; i<N; i++) { scanf("\n\t\t%d", &A[i]); } for(i=1; i<N; i++) { Temp = A[i]; j = i-1;while(Temp<A[j] && j>=0){A[j+1] = A[j];j = j-1;}A[j+1] = Temp;}printf("\n\tTHE ASCENDING ORDER LIST IS...:\n");for(i=0; i<N; i++)printf("\n\t\t\t%d", A[i]);getch();}

77

Page 78: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

C CODE FOR SELECTION SORT

Searching and sorting have been popular operations in elementry data structures. Although now a days many advanced sorting techniques are used to sort a set of data, the basic sorting methods are still popular and are the used frequently. Here C code for selection sort is given. The algorithm for selection sort is quite simple. In the first iteration, 1st element is compared against all the other elements (from array index 1 to array index n). In the second iteration 2nd element is compared with the elements from array index 2 to n. This process is repeated n-1 times.The C code is as follows :

#include <stdio.h>

void main( ){

int arr[5] = { 25, 17, 31, 13, 2 } ;int i, j, temp ;for ( i = 0 ; i <= 3 ; i++ ){

for ( j = i + 1 ; j <= 4 ; j++ ){

if ( arr[i] > arr[j] ){

temp = arr[i] ;arr[i] = arr[j] ;arr[j] = temp ;

}}

}

printf ( "\n\nArray after sorting:\n") ;

for ( i = 0 ; i <= 4 ; i++ )printf ( "%d\t", arr[i] ) ;

}

Output:

Array after sorting

2, 13, 17, 25, 31

78

Page 79: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

C CODE FOR QUICK SORT

Writing programs for sorting of a given set of numbers is one of the common programming tasks. Various types of sorting techniques like selection sort, inserting sort and quick sort are quite popular. Here C code for Quick sort is being presented. Here, in each iteration the array is subdivided into 2 arrays, and hence is a good example of Divide and Conquer algorithm. The program has the worst case complexity of O(n²) and an average and best case complexity of O(n logn).Following is the C code implementation of Quick Sort algorithm :

#include <stdio.h>

int split ( int*, int, int ) ;

void main( ){

int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;int i ;

void quicksort ( int *, int, int ) ;

quicksort ( arr, 0, 9 ) ;

printf ( "\nArray after sorting:\n") ;

for ( i = 0 ; i <= 9 ; i++ )printf ( "%d\t", arr[i] ) ;

}

void quicksort ( int a[ ], int lower, int upper ){

int i ;if ( upper > lower ){

i = split ( a, lower, upper ) ;quicksort ( a, lower, i - 1 ) ;quicksort ( a, i + 1, upper ) ;

}}

int split ( int a[ ], int lower, int upper ){

int i, p, q, t ;

p = lower + 1 ;q = upper ;i = a[lower] ;

79

Page 80: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

while ( q >= p ){

while ( a[p] < i )p++ ;

while ( a[q] > i )q-- ;

if ( q > p ){

t = a[p] ;a[p] = a[q] ;a[q] = t ;

}}

t = a[lower] ;a[lower] = a[q] ;a[q] = t ;

return q ;}

Output:

Array after sorting:

1, 2, 3, 9, 11, 13, 17, 25, 57, 90

80

Page 81: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

LINEAR SEARCH

#include<stdio.h>int main(){

int a[10],i,n,m,c=0;printf("Enter the size of an array");scanf("%d",&n);printf("\nEnter the elements of the array");for(i=0;i<=n-1;i++){scanf("%d",&a[i]);}printf("\nThe elements of an array are");for(i=0;i<=n-1;i++){printf(" %d",a[i]);}printf("\nEnter the number to be search");scanf("%d",&m);for(i=0;i<=n-1;i++){if(a[i]= =m){c=1;break;}}if(c= =0)printf("\nThe number is not in the list");elseprintf("\nThe number is found");return 0;

}

Output:

Enter the size of an array: 5

Enter the elements of the array: 3 2 1 5 4

The elements of an array are: 3 2 1 5 4

Enter the number to be search: 1

The number is found

81

Page 82: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

BINARY SEARCH

#include<stdio.h>int main(){  int a[10],i,n,m,c=0,l,u,mid;  printf("Enter the size of an array->");  scanf("%d",&n);  printf("\nEnter the elements of the array->");  for(i=0;i<n;i++){      scanf("%d",&a[i]);  }  printf("\nThe elements of an array are->");  for(i=0;i<n;i++){      printf(" %d",a[i]);  }  printf("\nEnter the number to be search->");  scanf("%d",&m);  l=0,u=n-1;  while(l<=u){      mid=(l+u)/2;      if(m= =a[mid]){      c=1;          break;      }      else if(m<a[mid]){      u=mid-1;      }      else      l=mid+1;  }  if(c= =0)      printf("\nThe number is not in the list");  else      printf("\nThe number is found");  return 0;}

Output:

Enter the size of an array: 5

Enter the elements of the array: 3 2 1 5 4

The elements of an array are: 3 2 1 5 4

Enter the number to be search: 1

The number is found

82

Page 83: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

21. IMPORTANT PROGRAMS

1. Write a sample Program

main(){ clrscr(); printf("Hello"); getch(); return 0;}

Output:

Hello

Explanation:

Here, The execution starts from main(), the clrscr() clears the screen neatly, the printf statement “Hello” is printed as output.

2. Write a sample Program

main(){ clrscr(); printf("Hello \n"); printf("Good "); getch(); return 0;}

Output:

Hello Good

Explanation:

Here, The execution starts from main(), the clrscr() clears the screen neatly, the printf statement “Hello” is printed and “\n” means next line “Good” is printed as output.

83

Page 84: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

3. Write a Program to find addition of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=10,b=10,c; c=a+b; printf(“ Value of c is %d”, c); getch();}

Output:

Value of c is 20

Explanation: After the main function, two variables a and b are declared as a=10 and b=10 , then c=a+b means both the values of a and b are added and stored in c. so the value inc becomes 20. Finally the “printf” statement is used to print the output on the moniter , here the value 20 is printed.

4. Write a Program to find subtraction of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=20,b=10 c=a-b; printf(“ Value of c is %d”, c); getch();}

Output: Value of c is 10

Explanation:

After the main function, two variables a and b are declared as a=20 and b=10 , then c=a-b means both the values of a and b are subtracted and stored in c. so the value in c becomes 10. Finally the “printf” statement is used to print the output on the moniter , here the value 10 is printed.

84

Page 85: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

5. Write a program to find the multiplication of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=10,b=10 c=a*b; printf(“ Value of c is %d”, c); getch();}

Output: Value of c is 100

Explanation:

After the main function, two variables a and b are declared as a=10 and b=10 , then c=a*b means both the values of a and b are multiplied and stored in c. so the value inc becomes 100. Finally the “printf” statement is used to print the output on the moniter , here the value 100 is printed.

6. Write a program to find the division of two numbers

#include<stdio.h>#include<conio.h>main(){ int a=20,b=10 c=a/b; printf(“ Value of c is %d”, c); getch();}

Output: Value of c is 2

Explanation:

After the main function, two variables a and b are declared as a=20 and b=10 , then c=a/b means both the values of a and b are multiplied and stored in c. so the value inc becomes 2. Finally the “printf” statement is used to print the output on the moniter , here the value 2 is printed.

85

Page 86: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

7. Write a program to find the number is a positive number or negative number

#include<stdio.h>#include<conio.h>main(){ int a=1; if(a>0) { printf(“ It is a Positive Number”); } else { printf(“It is a Negative Number”); }getch();}

Output: It is a Positive Number

Explanation:

After the main function, the variable a is declared as 1, according to the condition if(a>0) , as ‘a’ value is greater than ‘0’ so the printf statement “It is a positive number” is printed.

86

Page 87: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

8. Write a program to find the number is an even number or odd number

#include<stdio.h>#include<conio.h>main(){ int a=2; if(a%2= =0) { printf(“ It is an Even Number”); } else { printf(“It is an Odd Number”); }getch();}

Output:

It is an Even Number

Explanation:

After the main function, the variable a=2 is declared, means ‘a’ value is 2, according to the condition if(a%2= =0) then it is a even number.

9. Write a program to find area and circumference of a circle

#include<stdio.h> main(){ float radius,area,circumference; printf(“Enter radius”); scanf(“%f”,&radius); area=3.14*radius*radius; circumference=2*3.14*radius; printf(“Area=%f”,area); printf(“Circumference=%f”,circumference);}

Output:

Enter radius 1Area=3.14Circumference=6.28

87

Page 88: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

10. write a program to find factorial of a given number.

main() { int i,fact=1,n; printf("Enter a num: "); scanf("%d",&n); for(i=1;i<=n;i++) { fact=fact*i; } printf("Factorial=%d",fact); return 0;}

Output:

Enter a num: 5Factorial=120

Explanation:

Here, fact=1,i,n are declared as integer, the printf statement will ask to “Enter a num” the scanf statement “&n” will take the number, the condition for(i=1;i<=n;i++) is tested and fact=fact*i is done and the “fact” value is displayed as output.

11. write a program to find a number is prime or not.

main(){ int num,i=2; clrscr(); printf("Enter a number"); scanf("%d",&num); while(i<=num-1) {

if(num%i= =0) { printf("Not Prime"); break; }

i++;}if(i= =num)printf("Prime");return 0;}

Output:Enter a number 3Prime

88

Page 89: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

12. write a program to find biggest of two numbers.

#include<stdio.h>main(){ int a,b; printf(“Enter numbers a and b”); scanf(“%d%d”,&a,&b); if(a>b) { printf(“a is big”); } if(b>a) { printf(“b is big”); } if(a= =b) { printf(“b is big”); }}

Output:

Enter numbers a and b10 20B is big

13. write a program to display sum of first 10 numbers.

main(){ int i,sum=0;clrscr(); for(i=1;i<=10;i++) { sum=sum+i; }printf("sum=%d",sum);getch();return 0;}

Output:

55

89

Page 90: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

14. write a program to display sum of n numbers using while loop.

main(){ int i=1,sum=0,n;clrscr(); printf("Enter the number to do sum:"); scanf("%d",&n); while(i<=n) {

sum=sum+i;i++;

}printf("sum=%d",sum);getch();return 0;}

Output:

Enter the number to do sum: 10

55

15. write a program to display sum of n numbers using “for” loop

main(){ int i,sum=0,n;clrscr(); printf("Enter the number to do sum:"); scanf("%d",&n); for(i=1;i<=n;i++) {

sum=sum+i; }printf("sum=%d",sum);getch();return 0;}

Output:

Enter the number to do sum: 10

55

90

Page 91: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

16. Write a program to find roots of the quadratic equation

main() { float a,b,c,d,root1,root2; printf("Enter a,b,c num"); scanf("%f%f%d,&a,&b,&c); d=b*b-4*a*c; if(d>=0) { root1=(-b+sqrt(d))/(2*a); root2=(+b+sqrt(d))/(2*a); printf("root1=%f, root2=%f",root1,root2); } else printf("imaginary");return 0;} Output:Enter a,b,c num: 1 0 -9 a=1,b=0,c=-9 are 3.00 3.00

17. write a program to find fibonnic series.

main(){ int f1=0,f2,f=1,n,i; printf("Enter number"); scanf("%d",&n); if(n= =0) printf("0");else{ for(i=0;i<n;i++) { f1=f1+f2; f2=f; f=f1; printf("%d",f1); } }return 0;}

Output:

Enter Number 5 0 1 1 2 3

91

Page 92: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

18. write a program to find the leap year or not.

#include<stdio.h>main(){ int a; clrscr(); printf("Enter year: "); scanf("%d",&a); if(a%4= =0) { printf("Leap year"); }else { printf("Not a Leap year"); } getch();return 0;}

Output:

Enter year: 2000

Leap year

92

Page 93: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

19. write a program to find the number is a palindrome or not.

#include<stdio.h>main(){ int num,rev=0,digit=0,a; clrscr(); printf("Enter any number: "); scanf("%d",&num); a=num; while(num!=0) { digit=num%10; rev=rev*10+digit; num=num/10; }printf("\n reverse is %d",rev);if(a= =rev)printf("\n Palindrome");elseprintf("\n Not Palindrome");return 0;}

Output:

Enter any number: 121Palindrome

20. write a program to swap two numbers.

#include<stdio.h>main(){ int a,b,c; printf(“enter two a and b values”); scanf(“%d%d”,&a,&b); c=a; a=b; b=c; printf(“a=%d,b=%d”,a,b);}

Output:

Enter two values10 20a=20 b=10

93

Page 94: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

21. Write a program to find size.

main(){ int i=10; float f=10.25; char name[]="welcome";clrscr(); printf("int size is %d",sizeof(i)); printf("float size is %d",sizeof(f)); printf("character size is %d",sizeof(name));return 0;}

22. Write a program to find character from Lowercase to Uppercase

#include<stdio.h>main(){ char ch; printf(“Enter alphabet lower or upper: ”); ch=getchar(); if(islower(ch)) putchar(toupper(ch)); else putchar(tolower(ch));}

Output:

Enter alphabet lower or upper: m

M

23. write a sample program on arrays.

#include<stdio.h>#include<conio.h>main(){ char a[]={‘n’,’a’,’m’,’e’}; int i; clrscr(); for(i=0;i<4;i++) printf(“%c”,a[i]); getch();}

Output:

Name

94

Page 95: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

24. write a two-dimensional program on arrays.

#include<stdio.h>main(){ int a[4][2]; int i; for(i=0;i<=3;i++) { printf(“Enter roll number and marks:”i); scanf(“%d%d”,&a[i][0],&a[i][1]);} for(i=0;i<=3;i++) printf(“Student roll no %d marks %d”,a[i][0],a[i][1]);} Output:

Enter roll number and marks: 1201 91

Enter roll number and marks: 1202 92

Enter roll number and marks: 1203 93

Enter roll number and marks: 1204 94

Student roll no 1201 marks 91

Student roll no 1202 marks 92

Student roll no 1203 marks 93

Student roll no 1204 marks 94

Col 0 Col 1 Row 0

Row 1 Row 2

Row 3

1201 911202 921203 931204 94

95

Page 96: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

25. write a program to find addition of two matrixs using arrays

#include<stdio.h>int main(){  int a[3][3],b[3][3],c[3][3],i,j;  printf("Enter the First matrix");   for(i=0;i<3;i++)   for(j=0;j<3;j++)     scanf("%d",&a[i][j]);  printf("\nEnter the Second matrix");   for(i=0;i<3;i++)   for(j=0;j<3;j++)     scanf("%d",&b[i][j]);  printf("\nThe First matrix is\n");   for(i=0;i<3;i++){   printf("\n");   for(j=0;j<3;j++)   printf("%d\t",a[i][j]);  }  printf("\nThe Second matrix is\n");   for(i=0;i<3;i++){  printf("\n");    for(j=0;j<3;j++)   printf("%d\t",b[i][j]);   }   for(i=0;i<3;i++)       for(j=0;j<3;j++)            c[i][j]=a[i][j]+b[i][j];   printf("\nThe Addition of two matrix is\n");   for(i=0;i<3;i++){       printf("\n");       for(j=0;j<3;j++)            printf("%d\t",c[i][j]);   }   return 0;}

Output:

Enter the First matrix 1 2 3 4 5 6 7 8 9 Enter the Second matrix 1 2 3 4 5 6 7 8 9

The First matrix is The First matrix is The Addition of two matrix is 1 2 3 1 2 3 2 4 6 4 5 6 4 5 6 8 10 12 7 8 9 7 8 9 14 16 18

96

Page 97: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

26. write a program to find multiplication of two matrixs using arrays

#include<stdio.h>int main(){  int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;  printf("\nEnter the row and column of first matrix");  scanf("%d %d",&m,&n);  printf("\nEnter the row and column of second matrix");  scanf("%d %d",&o,&p);  if(n!=o){      printf("Matrix mutiplication is not possible");      printf("\nColumn of first matrix must be same as row of second matrix");  }  else{      printf("\nEnter the First matrix->");      for(i=0;i<m;i++)      for(j=0;j<n;j++)           scanf("%d",&a[i][j]);      printf("\nEnter the Second matrix->");      for(i=0;i<o;i++)      for(j=0;j<p;j++)           scanf("%d",&b[i][j]);      printf("\nThe First matrix is\n");      for(i=0;i<m;i++){      printf("\n");      for(j=0;j<n;j++){           printf("%d\t",a[i][j]);      }      }      printf("\nThe Second matrix is\n");      for(i=0;i<o;i++){      printf("\n");      for(j=0;j<p;j++){           printf("%d\t",b[i][j]);      }             }      for(i=0;i<m;i++)      for(j=0;j<p;j++)           c[i][j]=0;      for(i=0;i<m;i++){ //row of first matrix      for(j=0;j<p;j++){  //column of second matrix           sum=0;           for(k=0;k<n;k++)               sum=sum+a[i][k]*b[k][j];           c[i][j]=sum;      }      }  }  printf("\nThe multiplication of two matrix is\n");  for(i=0;i<m;i++){

97

Page 98: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

      printf("\n");      for(j=0;j<p;j++){           printf("%d\t",c[i][j]);      }  }  return 0;}

Output:

Enter the row and column of first matrix: 3 3Enter the row and column of second matrix: 3 3Enter the First matrix: 1 2 3 4 5 6 7 8 9 Enter the Second matrix: 1 2 3 4 5 6 7 8 9

The First matrix is The Second matrix is The Multiplication of two matrix is 1 2 3 1 2 3 30 36 42 4 5 6 4 5 6 66 81 96 7 8 9 7 8 9 102 126 150

98

Page 99: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

27. write a program to find transpose of a given matrix using arrays

#include<stdio.h>#include<conio.h>

int main(){ int m, n, i, j; int mat[10][10], trans[10][10]; printf("Enter the number of rows and columns of matrix "); scanf("%d%d",&m,&n); printf("Enter the elements of matrix \n"); for( i = 0 ; i < m ; i++ ) { for( j = 0 ; j < n ; j++ ) { scanf("%d",&mat[i][j]); } } for( i = 0 ; i < m ; i++ ) { for( j = 0 ; j < n ; j++ ) { trans[j][i] = mat[i][j]; } } printf("Transpose of entered matrix :-\n"); for( i = 0 ; i < n ; i++ ) { for( j = 0 ; j < m ; j++ ) { printf("%d\t",trans[i][j]); } printf("\n"); } getch(); return 0;}

Output:Enter the number of rows and columns of matrix: 3 3Enter the elements of matrix1 2 3 4 5 6 7 8 9Transpose of entered matrix :-1 4 72 5 83 6 9

99

Page 100: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

28. Write a program on Strings.

#include<stdio.h>main(){ char name1[]= “prince”; char name2[]= “good”; strcat(name1,name2); printf(“name1 is %s”,name1); }

29. Write a program on reverse of String.

#include<stdio.h>main(){ char y[30]; printf(“Enter name: “); gets(y);printf(“The name reversed is %s”,strrev(y));}

Output:

Enter name: princeThe name reversed is ecnirp

30. Write a program on strings to check for palindrome.

main(){ char s[10],t[10]; clrscr(); printf("Enter Name: "); scanf("%s",s); strcpy(t,s); strrev(s); if(strcmp(s,t)= =0) printf("Palindrome");else printf("Not Palindrome");getch();return 0;}

Output:

Enter Name: madamPalindrome

100

Page 101: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

31. Write a program to find both the strings are equal.

main(){ char s[10],t[10]; clrscr(); printf("Enter Name: "); scanf("%s",s); printf("Enter Name: ");scanf("%s",t); if(strcmp(s,t)= =0) printf("Equal");else printf("Not Equal");getch();return 0;}

Output:

Enter Name: good Enter Name: goodEqual

32. Write a program on Functions

#include<stdio.h>main(){ message(); printf(“This is main message”);}message(){ printf(“This is function message\n”);}

Output:

This is function messageThis is main message

101

Page 102: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

33. Example Program on Pointers

#include<stdio.h>main(){ int num=10; printf(“Address of num=%u”,&num); printf(“Value of num=%d”,num);}

Output:

Address of num= 1354Value of num=10

34. Example Program on Pointers

#include<stdio.h>main(){ int a=22; int *b; b=&a;

printf(“Value of a=%d”,a);

printf(“Value of a=%d”,*(&a));

printf(“Value of a=%d”,*b);

printf(“Address of a=%u”,&a);

printf(“Address of a=%u”,b);

printf(“Address of b=%u”,&b);

printf(“Value of b=Address of a=%u”,b);}

Output:

Value of a=22Value of a=22Value of a=22Address of a=4000Address of a=4000Address of b=5000Value of b=Address of a=4000

102

Page 103: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

35. Write a program for call by value.

Example:

main(){ int a=1, b=2; printf(“Before Calling a and b is%d%d”,a,b); void change(a,b); printf(“After calling a and b is %d%d”,a,b);}void change(x,y)int x,y;{ x=2; y=1; printf(“Function changes a and b is %d%d”,x,y); getch(); return 0;}

Output:

Before Calling a and b is 1, 2Function changes a and b is 2, 1After calling a and b is 1,2

103

Page 104: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

36. Write a program for call by Reference

main(){ int a=1, b=2; printf(“Before Calling a and b is%d%d”,a,b); void change(&a,&b); printf(“After calling a and b is %d%d”,a,b);}void change(x,y)int x,y;{ x=2; y=1;printf(“Function changes a and b is %d%d”,*x,*y);}

Output:

Before Calling a and b is 1, 2Function changes a and b is 2, 1After calling a and b is 2,1

104

Page 105: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

37. Program on Structure example

#include<stdio.h>struct st{ int num, char name[10]; int m1; int m2;};struct st s;void main(){ float tot,avg;printf(“Enter student num,name,marks1,marks2”);scanf(“%d%s%d%d”,&s.num,&s.name,&s.m1,&s.m2);tot=s.m1+s.m2+s.m3;avg=tot/3;printf(“%d%s%d%d”,s.num,s.name,tot,avg);}

Output:

Enter student num,name,marks1,marks21 prince 80 851 prince 80 85

38. Example program on structures.

struct pri { int page; char name[10]; }p;void main() { int i; clrscr(); { printf("Enter page and name"); scanf("%d%s",&p.page,p.name); } printf("\n%d\t %s\n",p.page,p.name); getch();}

105

Page 106: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

39. Program on Nested structure

#include<stdio.h>main(){ struct marks{ int m1;}struct student{ char name[10]; int rollno; struct marks m;}struct student stu;printf(“/n”);printf(“Enter student name: “);scanf(“%d”,&stu.name”);printf(“Enter student marks”);scanf(“%d%d”,&stu.m.m1);printf(“Student name is %s”,stu.name);printf(“Student marks is %d”,stu.m.m1);}

Output:

Enter student name: princeEnter student marks: 10Student name is princeStudent marks is 10

106

Page 107: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

40. Program on Union example

#include<stdio.h>#include<conio.h>void main(){ union id; { char branch[20]; int size;};struct student{ char name[30];float rollno;union id details;};static struct student info ={“great”,10.0,”cse”};clrscr();printf(“%d”,sizeof(unionid));printf(“%s%f”,info.name, info.rollno);printf(“%s%d”,info.details.branch);}

Output:

20Great 10.0 cse

107

Page 108: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

22. C LANGUAGE INTERVIEW QUESTIONS

1. What is C Language?

C language is the implementation language. UNIX Operating system is developed by using C Language. Various other software programming languages is developed using C Language. It is one of the basic programming language. As C is the procedural language, where as the programming language. Procedural in the sense, each and every instruction is executed sequentially. C is a Middle Level Language. C stands between the two categories Low Level Language nor a High Level Language. It is a Middle Level Language. It means it performs the task of Low Level Language as well as High Level Language. Low Level Language in terms of 0’s and 1’s (bits), examples Assembly Language or Machine Language. High level language looks like normal english whose instructions are understandable to the human languages, examples C, C++, FORTRAN, PASCAL, COBOL etc. 2. What is an Algorithm?

Algorithm is the step-by-step process of performing an operation. The algorithm defines the concept of the program task. The developer before implementing the code, writes the algorithm for better understanding.

3. What is a Flowchart?

Flowchart is the pictorial representation, which is shown diagrammatically for better understanding. Different symbols are used for representing the flow of data execution.

4. What is a Program?

Set of instructions to carry out particular task is known as a Program. As C is a procedural language each instruction is executed sequentially one after the other.

5. What is a Constant?

The values which can’t be changed during program execution are known as Constants.

C Constants can be classified into 2 types:

1. Numeric Constants2. Character Constants

108

Page 109: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

6. what are C tokens?

There are six classes of tokens: identifier, keywords, constants, string literals, operators and other separators.

7. What are C identifiers?

These are names given to various programming element such as variables, function, arrays. It is a combination of letter, digit and underscore. It should begin with letter. Backspace is not allowed.

8. Explain a small printf program? main(){ printf("Hello"); getch(); return 0;}

Output:Hello

Explanation:Here, The execution starts from main(), the clrscr() clears the screen neatly, the printf statement “Hello” is printed as output.

109

Page 110: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

9. What are different types of C Language Keywords?

autobreakcasecharconstcontinuedefaultdodoubleelseenumexternfloatforgotoifintlongregisterreturnshortsignedsizeofstaticstructswitchtypedefunionunsignedvoidvolatilewhile

10. What is a Variable?

Variable represents some specified type of information, it takes different values during program execution.

110

Page 111: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

11. What is an Operator?

It is a symbol which performs an operation on the operands. Types of operators:

1. Arithmetic operator2. Relational operator3. Logical operator4. Increment and Decrement operator5. Assignment operator6. Conditional operator7. Bitwise operator8. Special operator

12. What is an expression?

An expression is combination of variables, constants connected with operators.

13. Differentiate between for loop and a while loop? What are it uses?

For executing a set of statements fixed number of times we use for loop while when the number of iterations to be performed is not known in advance we use while loop.

14. What is an array?

An array is the collection of similar datatypes. int a[5];

It means that “a” is the array name and it has 5 storage locations.

aa[0]a[1]a[2]a[3]a[4]

15. Explain a program on arrays?

#include<stdio.h>main(){ char a[]={‘n’,’a’,’m’,’e’}; int i; clrscr(); for(i=0;i<4;i++) printf(“%c”,a[i]); getch();}

Output: Name

111

Page 112: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

16. Difference between arrays and linked list?

An array is a repeated pattern of variables in contiguous storage. A linked list is a set of structures scattered through memory, held together by pointers in each element that point to the next element. With an array, we can (on most architectures) move from one element to the next by adding a fixed constant to the integer value of the pointer. With a linked list, there is a “next” pointer in each structure which says what element comes next.

17. What are Strings?

The string is a group of characters, symbols, digits. Syntax: char name[]=”PRINCE”;

strlen = used to find length strcpy = used to copy one string to anotherstrcat = used to combine two stringsstrlwr = used to convert strings into lower casestrupr = used to convert strings into upper case

18. What is the difference between Strings and Arrays?

String is a sequence of characters ending with NULL .it can be treated as a one dimensional array of characters terminated by a NULL character.

19. What is function?

Function has set of statements used to perform task

20. What is a pointer?

A pointer is a variable it stores address of another variable. It is denoted by “*”

21. What are the uses of a pointer?

Pointer is used in the following casesi) It is used to access array elementsii) It is used for dynamic memory allocation.iii) It is used in Call by referenceiv) It is used in data structures like trees, graph, linked list etc.

22. Call by Value

The process of passing the actual value of the variable, this values are taken by the calling program and can be used inside the function.

112

Page 113: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

23. Call by Reference Calling a function using pointers to pass the addresses of variables .

24. What is structure?

Structure is a collection of dissimilar datatypes.

25. What are the differences between structures and arrays?

Structure is a collection of heterogeneous data type but array is a collection of homogeneous data types.Structure1-It is a collection of data items of different data type.2- It has declaration and definition3- keyword struct is used4-Structure name is known as tag it is the short hand notation of the declaration.Array 1-It is a collection of data items of same data type.2-It has declaration only3-.There is no keyword.4- array name represent the address of the starting element.

26. What is Union?

Union is a collection of heterogeneous data type but it uses efficient memory utilization technique by allocating enough memory to hold the largest member. Union is declared like structure but the difference occurs in the storage location.

27. What the advantages of using Unions?

When the C compiler is allocating memory for unions it will always reserve enough room for the largest member.

28. What are the differences between structures and union?

A structure variable contains each of the named members, and its size is large enough to hold all the members. Structure elements are of same size.A union contains one of the named members at a given time and is large enough to hold the largest member. Union element can be of different sizes.

113

Page 114: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

29. What are Files?

A file is a collection of related information that is permanently stored on the disk and allows us to access and alter the information.File can be opened asfp=fopen(“file_name”,”mode”);fp= file pointermode= file opening mode

File can be closed asfclose(file_pointer);

30. What is meant by file opening?

The action of connecting a program to a file is called opening of a file. This requires creating an I/O stream before reading or writing the data.

31. What is FILE?

FILE is a predefined data type. It is defined in stdio.h file.

32. How is fopen()used ?

The function fopen() returns a file pointer. Hence a file pointer is declared and it is assigned as

FILE *fp;fp= fopen(filename,mode);

filename is a string representing the name of the file and the mode represents:

“r” for read operation“w” for write operation“a” for append operation“r+”,”w+”,”a+” for update operation

33. How is a file closed ?

A file is closed using fclose() function

Eg. fclose(fp);Where fp is a file pointer.

114

Page 115: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

34. What is Data Structure?

A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. Some are used to store the data of same type and some are used to store different types of data.

35. What does each entry in the Link List called?

Each entry in a linked list is called a node. Think of a node as an entry that has three sub entries. One sub entry contains the data, which may be one attribute or many attributes. Another points to the previous node, and the last points to the next node. When you enter a new item on a linked list, you allocate the new node and then set the pointers to previous and next nodes.

36. What is Linked List ?

Linked List is one of the fundamental data structures. It consists of a sequence of? nodes, each containing arbitrary data fields and one or two (?links?) pointing to the next and/or previous nodes. A linked list is a self-referential datatype because it contains a pointer or link to another data of the same type. Linked lists permit insertion and removal of nodes at any point in the list in constant time, but do not allow random access.

37. What member function places a new node at the end of the linked list?

The appendNode() member function places a new node at the end of the linked list. The appendNode() requires an integer representing the current data of the node.

38. Run Time Memory Allocation is known as ?

Allocating memory at runtime is called a dynamically allocating memory. In this, you dynamically allocate memory by using the new operator when declaring the array, for example : int grades[] = new int[10];

39. What method is used to place a value onto the top of a stack?

push() method, Push is the direction that data is being added to the stack. push() member method places a value onto the top of a stack.

115

Page 116: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

40. What method removes the value from the top of a stack?

The pop() member method removes the value from the top of a stack, which is then returned by the pop() member method to the statement that calls the pop() member method.

41. What does isEmpty() member method determines?

isEmpty() checks if the stack has at least one element. This method is called by Pop() before retrieving and returning the top element.

42. What is the difference between a Stack and an Array?

STACKi) Stack is a ordered collection of itemsii) Stack is a dynamic object whose size is constantly changing as items are pushed and popped .iii) Stack may contain different data typesiv) Stack is declared as a structure containing an array to hold the element of the stack, and an integer to indicate the current stack top within the array.

ARRAYi) Array is an ordered collection of itemsii) Array is a static object i.e. no of item is fixed and is assigned by the declaration of the arrayiii) It contains same data types.iv) Array can be home of a stack i.e. array can be declared large enough for maximum size of the stack.

43. What is a queue ?

A Queue is a sequential organization of data. A queue is a first in first out type of data structure. An element is inserted at the last position and an element is always taken out from the first position.

116

Page 117: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

44. What is the relationship between a queue and its underlying array?

Data stored in a queue is actually stored in an array. Two indexes, front and end will be used to identify the start and end of the queue.

When an element is removed front will be incremented by 1. In case it reaches past the last index available it will be reset to 0. Then it will be checked with end. If it is greater than end queue is empty.

When an element is added end will be incremented by 1. In case it reaches past the last index available it will be reset to 0. After incrementing it will be checked with front. If they are equal queue is full.

45. Which process places data at the back of the queue?Enqueue is the process that places data at the back of the queue.

46. Why is the isEmpty() member method called?

The isEmpty() member method is called within the dequeue process to determine if there is an item in the queue to be removed i.e. isEmpty() is called to decide whether the queue has at least one element. This method is called by the dequeue() method before returning the front element.

47. How is the front of the queue calculated ?

The front of the queue is calculated by front = (front+1) % size.

48. How is any Data Structure application is classified among files?

A linked list application can be organized into a header file, source file and main application file. The first file is the header file that contains the definition of the NODE structure and the LinkedList class definition. The second file is a source code file containing the implementation of member functions of the LinkedList class. The last file is the application file that contains code that creates and uses the LinkedList class.

49. Which file contains the definition of member functions?

Definitions of member functions for the Linked List class are contained in the LinkedList.cpp file.

117

Page 118: C LANGUAGE - Nizamabad Info & DATA STRUCTURES.doc · Web viewIncludes: ( C & Data Structures Notes ( C & Data Structures Programs ( C & Data Structures Interview Questions CONTENTS

50. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model.

1. RDBMS Array (i.e. Array of structures)2. Network data model Graph3. Hierarchical data model Trees.

51. What are the goals of Data Structure?

 It must rich enough in structure to reflect the actual relationship of data in real world.The structure should be simple enough for efficient processing of data.

118