c booknewcopy

237
EMBEDDED C

Upload: mani-kandan

Post on 27-Oct-2014

104 views

Category:

Documents


0 download

DESCRIPTION

learn c by this

TRANSCRIPT

Page 1: C BOOKnewcopy

EMBEDDED C

Page 2: C BOOKnewcopy

EMBEDDED C

CONTENTS

Ch.No. Index

1. Constants, Variables Data Types1.1 Introduction1.2 Character Set

1.2.1 Letters1.2.2 Digits1.2.3 Special Characters1.2.4 White Spaces

1.3 C Tokens1.3.1 Keywords1.3.2 Identifiers1.3.3 Constants

1.3.3.1 Integer Constants1.3.3.2 Real Constants1.3.3.3 Single Character Constants1.3.3.4 String Constants1.3.3.5 Backslash Character Constants

1.4 Variables1.4.1 Definition1.4.2 Rules for Defining Variables

1.5 Data Types1.5.1 Introduction1.5.2 Integer Types1.5.3 Floating Point Types1.5.4 Character Types

1.6 Declaration of Variables1.6.1 User-Defined Type Declaration

1.7 Storage ClassExerciseWorkshop 2. Operators

2.1 Introduction2.2 Operators of C

2.2.1 Arithmetic Operators2.2.1.1 Integer Arithmetic2.2.1.2 Real Arithmetic

Page 3: C BOOKnewcopy
Page 4: C BOOKnewcopy

2.2.1.3 Mixed-Mode Arithmetic 17

2.2.2 Relational Operators 18

2.2.3 Logical Operators 18

2.2.4 Assignment Operators 19

2.2.5 Increment and Decrement Operators 19

2.2.6 Conditional Operator 20

2.2.7 Bitwise Operators 20

2.2.8 Special Operators 22

2.2.8.1 The Comma Operator 23

2.2.8.2 The Size of Operator 23

2.2.9 Hierarchy of Operations 23

Exercise 24Workshop

3. Control Structure

Introduction 27

3.2 Branching 27

The If Statement 28

3.2.1 Simple If Statement 28

3.2.2 The If....Else Statement 30

3.2.3 Nested If...Else Statement 31

3.2.4 The Else If Ladder 32

3.3 Switch Case Statement 34

3.4 The Conditional Operator 37

3.5 Go to Statement 37

Workshop

Page 5: C BOOKnewcopy

4. Looping 41

4.1 Introduction 41

4.2 The While Statement 41

4.3 The ‘Do...While’ Statement 42

4.4 The ‘For’ Loop 43

4.5 The Break Statement 44

4.6 The Continue Statement 45

Exercise 48

Workshop

5. Pointers and Functions 53

5.1 Introduction 53

5.2 Passing value between functions 56

5.3 Calling Convention 57

5.4 Advanced Features of Functions 57

5.5 An Introduction to Pointers 58

Exercise 65

workshop

6. Arrays 736.1Introduction 736.2One Dimensional Array 73

6.2.1 Declaration of Arrays 736.2.2 Initialization of Arrays 736.2.3 Function and Arrays 74

6.3Two-Dimensional Arrays 756.4Multidimensional Array 80

Exercise 83Workshop

7. Strings 87

Page 6: C BOOKnewcopy

7.1Introduction 877.2Pointers and Strings 887.3Standard Library functions and Strings 897.4Two dimensional array of characters 917.5Array of pointers to strings 927.6Limitations of Array of pointers to strings 94

Exercise 97 Workshop

8. Structures 1008.1Introduction 1008.2Declaring with structures 1008.3Structure elements are stored 1028.4Array of structures 1038.5Uses of Structures 103

Exercise 104

Workshop

9.Files

9.1Introduction9.2File operation9.3Record I/O in Files

110 110

Workshop

Page 7: C BOOKnewcopy

C Language 1-constants, variables & data types

Chapter 11. CONSTANTS, VARIABLES&DATA TYPES

1.1 INTRODUCTIONA programming language is designed to help certain kinds of data process consisting of

numbers, characters and strings to provide useful output known as information. The task of processing of data is accomplished by executing a sequence of precise instructions called program.

1.2 CHARACTER SETC characters are grouped into the following categories.1. Letters2. Digits3. Special Characters4. White SpacesNote: The compiler ignores white spaces unless they are a part of a string constant.

1.2.1 LettersUppercase A….ZLowercase a…..z1.2.2 DigitsAll decimal digits 0…..9

1.23 Special Character, Comma & Ampersand. Period ^ Caret; Semicolon * Asterisk: Colon - Minus? Question mark + Plus sign‘Apostrophe < Less than“Quotation mark > Greater than

! Exclamation (Left parenthesis| Vertical Bar ) Right parentheses/ Slash [Left bracket\ Back slash ] Right bracket~ Tilde {Left brace_ Underscore } Right brace$ Dollar sign # Number sign

% Percent sign

1

ADVETECH PVT LTD – Diploma in Embedded system design

Page 8: C BOOKnewcopy

C Language 1-constants, variables & data types

1.2.4 White SpacesBlank SpaceHorizontal TabCarriage ReturnNew LineForm Feed

1.3 C TOKENSIn C programs, the smallest individual words and punctuation marks are known as tokens. In c program the smallest individual units are known as C tokens and has six types of tokens and they are shown below

1.3.1 KEYWORDS Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings and these meanings cannot be changed. Only lower case is allowed in keywords. There are 32 keywords available in c, listed below

2

Page 9: C BOOKnewcopy

C Language 1-constants, variables & data types

1.3.2 IDENTIFIERS Identifiers refer to the names of variables, functions and arrays. They are user-defined names and consist of a sequence of letters and digits, with a letter

as a first character. Both uppercase and lowercase letters are permitted. The underscore character is also permitted in identifiers.

1.3.3 CONSTANTSConstants in C refer to fixed values that do not change during the execution of a Program.

CONSTANTS

Numeric constants Character constants

Integer Real Single character String

Constants constants constants constants

1.3.3.1 Integer ConstantsAn integer constant refers to a sequence of digits; there are three types’ integers, namely,

decimal, octal, and hexa decimal.

Decimal Constant

3

auto double int char

float break else long

switch case enum register

typedef extern union const

short unsigned continue for

signed void default goto

size of volatile do if

static while struct case

Page 10: C BOOKnewcopy

C Language 1-constants, variables & data types

Decimal integer consist of set of digits, 0 through 9, preceded by an optional + or - signE.g.: 123,-321 etc.Note: Embedded spaces, commas and non-digit characters are not permitted between digits.E.g.: 1) 15 750 2) $1000

Octal ConstantAn octal integer constant consists of any combination of digits from the set 0 through

7, with a leading 0.E.g.: 1) 037 2) 0435

Hexadecimal Constant A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also include alphabets A through F or a through f.

E.g.: 1) 0X2 2) 0x9F 3) 0Xbcd

1.3.3.2 Real Constants Certain quantities that vary continuously, such as distances, heights etc., are represented

by numbers containing functional parts like 17.548.Such numbers are called real (Or floating point) constants.E.g.: 0.0083,-0.75 etc.

A real number may also be expressed in exponential or scientific notation.E.g.: 215.65 may be written as 2.1565e2

1.3.3.3 Single Character ConstantsA single character constants contains a single character enclosed within a pair of

Single quote marks.E.g.: ’5’‘X’‘;’

1.3.3.4 String ConstantsA string constant is a sequence of characters enclosed in double quotes. The characters

may be letters, numbers, special characters and blank space.E.g.:”Hello!”“1987”“?….!”

1.3.3.5 Backslash Character Constants

4

Page 11: C BOOKnewcopy

C Language 1-constants, variables & data types

C supports special backslash character constants that are used in output functions. These character combinations are known as escape sequences.Constant Meaning‘\a’ audible alert‘\b’ backspace‘\f’ form feed‘\n’ new line‘\0’ null‘\v’ vertical tab‘\t’ horizontal tab‘\r’ carriage return‘\?’ Question mark‘\\’ backslash

1.4 VARIABLES1.4.1 Definition:

A variable is a data name that may be used to store a data value. A variable may take different values at different times of execution and may be chosen by the programmer in a meaningful way. It may consist of letters, digits and underscore character. E.g.: int salary; ch67, time_12

1.4.2 Rules for defining variables: They must begin with a letter. Some systems permit underscore as the first character. ANSI standard recognizes a length of 31 characters. However, the length should not be normally more than eight characters. Uppercase and lowercase are significant. The variable name should not be a keyword. White space is not allowed.

1.5 DATA TYPES1.5.1 INTRODUCTION

C supports four classes of data types. 1. Primary or Fundamental data types. 2. User-defined data types. 3. Derived data types. 4. Empty data set.

PRIMARY DATA TYPES

5

Page 12: C BOOKnewcopy

C Language 1-constants, variables & data types

1.5.2 Integer TypesType Size (bits) Rangeint or signed int 16 -32,768 to 32767unsigned int 16 0 to 65535short int 8 -128 to 127unsigned short int 8 0 to 255long int 32 -2,147,483,648 to 2,147,483,648unsigned long int 32 0 to 4,294,967,295

1.5.3 Floating Point TypesType Size(bits) Rangefloat 32 3.4E-38 to 3.4E+38double 64 1.7E-308 to 1.7E+308long double 80 3.4E-4932to 1.1E+4932

1.5.4 Character TypesType Size (bits) Rangechar 8 -128 to 127unsigned char 8 0 to 255

1.6 DECLARATION OF VARIABLESThe syntax is

Data-type v1, v2…..vn;

6

CHAR INT FLOAT

int unsigned intshort int unsigned short int long int unsigned long int

signed charunsigner char

float double long double

Page 13: C BOOKnewcopy

C Language 1-constants, variables & data types

E.g.: 1.int count; 2. double ratio, total;

1.7 STORAGE CLASSESIts fully define a variable one needs to mention not only its ‘type’ but also its ‘storage

class’. In other words, not only do all variables have a data type, they also have a ‘storage classes’.A variable in C can have any one of the four storage classes.

1. Automatic variables.2. External variables.3. Static variables.4. Register variables.

1.7.1 AUTOMATIC VARIABLES (LOCAL/INTERNAL)Automatic variables are declared inside a function in which they are to be utilized. They

are created when a function is called and destroyed automatically when the function is exited. The features of a variable defined to have an automatic storage class are as under:

Storage Memory

Default initial value An unpredictable value, which is often called a garbage value

Scope Local to the block in which the variable is definedLife Till the control remains within the block in which the variable is defined

E.g.: auto int x; auto int y;Following program shows how an automatic storage class variable is declared, and the fact that if the variable is not initialized it contains a garbage value. Example Code:void main( ) { auto int i, j ; printf ( "\n%d %d", i, j ) ; } The output of the above program could be... 1211 221 Where, 1211 and 221 are garbage values of i and j. When you run this program you may get different values, since garbage values are unpredictableNote: The keyword for this storage class is auto, and not automatic.

1.7.2 STATIC VARIABLES:

7

Page 14: C BOOKnewcopy

C Language 1-constants, variables & data types

As the name suggests, the value of a static variable persists until the end of the program. A variable can be declared static using the keyword static.The features of a variable defined to have a static storage class are as under:Storage Memory

Default initial value Zero

Scope Local to the block in which the variable is defined

Life Value of the variable persists between different function calls

E.g.: static int x; static int y;Following program shows how a static storage class variable is declared,Example Code:void main( ) { static int i, j ; printf ( "\n%d %d", i, j ) ; } The output of the above program could be... 0static variable gets automatically initialized to zero Note: The keyword for this storage class is static.

Compare the two programs and their output given to understand the difference between the automatic and static storage classes.main(){increment();increment();increment();}increment();{auto int i=0;printf(“%d”,i);i=i+1;}

Output111

main(){increment();increment();increment();}increment();{static int i=0;printf(“%d”,i);i=i+1;}

Output123

8

Page 15: C BOOKnewcopy

C Language 1-constants, variables & data types

In the above example, when variable i is auto, each time increment ( ) is called it is re-initialized to one. When the function terminates, i vanishes and its new value of 2 is lost. The result i is initialized to 1 every time.

On the other hand, if static, it is initialized to 1 only once. It is never initialized again. During the first call to increment ( ), i is incremented to 2. Because static, this value persists. The next time increment ( ) is called, i is not re-initialized to 1; on the contrary its old value 2 is still available. This current value of i (i.e. 2) gets printed and then i = i + 1 adds 1 to i to get a value of 3. When increment ( ) is called the third time, the current value of i (i.e. 3) gets printed and once again i is incremented.

1.7.3 EXTERNAL VARIABLES:Variables that are both alive and active throughout the entire program are known as

external variables. They are also known as global variables.

Storage MemoryDefault initial value ZeroScope GlobalLife As long as the program execution doesn’t come to an end.

E.g.: int number; Float length = 7.5;Following program shows how an extern storage class variable is declared,Example Code:int i ; main( ) { printf ( "\n i = %d", i ) ; increment( ) ; increment( ) ; decrement( ) ; decrement( ) ; } increment( ) { i = i + 1 ; printf ( "\non incrementing i = %d", i ) ; } decrement( ) { i = i - 1;

9

Page 16: C BOOKnewcopy

C Language 1-constants, variables & data types

printf ( "\non decrementing i = %d", i ) ; } The output would be: i = 0 on incrementing i = 1 on incrementing i = 2 on decrementing i = 1 on decrementing i = 0As is obvious from the above output, the value of i is available to the functions increment ( ) and decrement ( ) since i has been declared outside all functions.Note: The keyword for this storage class is extern.

1.7.4 REGISTER VARIABLES We can tell the compiler that a variable should be kept in one of the machine’s registers,

instead of keeping in the memory. Since a register access is much faster than a memory access, keeping the frequently accessed variables in the register will lead to faster execution of programs. This is done as follows:

Storage CPU register

Default initial value Garbage value

Scope Local to the block in which the variable is defined.

Life Till the control remains within the block which the variable is defined.

E.g. register int count;Following program shows how a register storage class variable is declared, main( )

{ register int i ; for ( i = 1 ; i <= 10 ; i++ ) printf ( "\n%d", i ) ; }

We have declared the storage class of i as register, we cannot say for sure that the value of i would be stored in a CPU register. This is because the numbers of CPU registers are limited, and the variable works as if its storage class is auto.The keyword for this storage class is reg, not as register.

Which to Use When

10

Page 17: C BOOKnewcopy

C Language 1-constants, variables & data types

The rules are as under: − Use static storage class only if you want the value of a variable to persist between different function calls. − Use register storage class for only those variables that are being used very often in a program. Reason is, there are very few CPU registers at our disposal and many of them might be busy doing something else. Make careful utilization of the scarce resources. A typical application of register storage class is loop counters, which get used a number of times in a program. − Use extern storage class for only those variables that are being used by almost all the functions in the program. This would avoid unnecessary passing of these variables as arguments when making a function call. Declaring all the variables as extern would amount to a lot of wastage of memory space because these variables would remain active throughout the life of the program. − If you don’t have any of the express needs mentioned above, then use the auto storage class. In fact most of the times we end up using the auto variables, because often it so happens that once we have used the variables in a function we don’t mind losing them.

EXERCISE:1. Which of the following are invalid variable names and why? BASICSALARY _basic basic-hra #MEAN group. 422 Population in 2006 over time mindovermatter FLOAT hELLO queue. team’svictory Plot # 3 2015_DDay

2. What would be the output of the following programs?(a) main( )

{printf ( "nn \n\n nn\n" ) ;printf ( "nn /n/n nn/n" ) ;}

(b) main( ){int a, b ;printf ( "Enter values of a and b" ) ; scanf ( " %d %d ", &a, &b ) ; printf ( "a = %d b = %d", a, b ) ; }

11

Page 18: C BOOKnewcopy

C Language 1-constants, variables & data types

(c) main( ) { int p, q ; printf ( "Enter values of p and q" ) ; scanf ( " %d %d ", &p,&q ) ; printf ( "p = %d q =%d", p, q ) ; }

C INTERVIEW QUESTIONS:1. What is the function of c?main() function is essential in c programming language. User defined function are those function written by the user. These functions are called user defined function. Inbuilt functions are predefined in the c-language itself main function has three parameters:1.Environment vector2.Argument counter 3.Argument vector

Function those we write in c program performs one or more specific tasks. main function calls the function and given authority of execution. main function passes control to the userdefined function. Then execution gets started. After executing the function the control is transferred back to the main function.

2. Is C is platform dependent or independent? How and why?Major issue behind designing C language is that it is a small, portable programming language. It is used to implement an operating system. In past time C is a powerful tool for writing all types of program and has mechanism to achieve all most programming goals. So, we can say that C is platform dependent.

3. What are the uses of the keyword static?This simple question is rarely answered completely. Static has three distinct uses in C:

A variable declared static within the body of a function maintains its value between function invocations.

A variable declared static within a module, (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module. That is, it is a localized global

Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared

12

Page 19: C BOOKnewcopy

C Language 1-constants, variables & data types

4. What are the different storage classes in C?C has three types of storage: automatic, static and allocated.

Variable having block scope and without static specifier have automatic storage duration. Variables with block scope, and with static specifier have static scope. Global variables

(i.e., file scope) with or without the static specifier also have static scope.Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated storage class.

5. What are advantages and disadvantages of external storage class?Advantages of external storage class1) Persistent storage of a variable retains the latest value2) The value is globally availableDisadvantages of external storage class1) The storage for an external variable exists even when the variable is not needed2) The side effect may produce surprising output3) Modification of the program is difficult4) Generality of a program is affected.

6. Can static variables be declared in a header file?You can’t declare a static variable without defining it as well (this is because the storage class modifiers static and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended.

7. What is the difference between "printf (...)" and "sprintf (...)"? sprintf (...) writes data to the character array whereas printf (...) writes data to the standard output device.

8. What is the difference between declaring a variable and defining a variable? Declaring a variable means describing its type to the compiler but not allocating any space for it. Defining a variable means declaring it and also allocating space to hold the variable. You can also initialize a variable at the time it is defined. Here is a declaration of a variable and a structure, and two variable definitions, one with initialization: extern int decl1; /* this is a declaration */struct decl2 { int member;}; /* this just declares the type--no variable mentioned */int def1 = 8; /* this is a definition */int def2; /* this is a definition */

13

Page 20: C BOOKnewcopy

C Language 1-constants, variables & data types

9. What is the difference between compile time error and run time error?Some main differences between compiler time error and run time error are given below:1. Compile time error are semantic and syntax error. Where Run time errors are memory allocation error e.g. segmentation faults.2. Compile time errors come because of improper Syntax. where in java Run time Errors are considered as exceptions. Run time errors are logical errors.3. Compile time errors are handled by compiler. Where Run time errors are handled by programmers.

10. What are enumerations?Enumeration is a kind of type. It is used to hold the group of cost values that are given by programmer. After defining we can use it like integer type. E.g. enum off, on; here, off and on are 2 integer constants. These are called enumerators. By default value assign to enumerator are off.

11. How to differentiate local memory and global memory? Local and global memory allocation is applicable with Intel 80x86 CPUs.Some main difference between local and global variables are given below:1. Using local memory allocation we can access the data of the default memory segment, where as with global memory allocation we can access the default data, located outside the segment, usually in its own segment. 2. If our program is a small or medium model program, the default memory pool is local, where as if our program uses the large or compact memory model, the default memory pool is global.

WORKSHOP

1. Read a bill no : print its next 2 bill numbers.2. Read two nos : Swap them and print3. Read miles: Print in Kilometers (5 miles=8 kms)4. Given total months, find out the no of years and months.5. Given year and months, find out the months.6. Given opening stock, purchase qty and sales qty find out the stock of the item.7. Given annual premium and no of years, calculate the total amount paid.

14

Page 21: C BOOKnewcopy

C Language 2-Operators

2. OPERATORS

2.1 INTRODUCTIONIn this lesson, we are going to learn about the various operators of C language that

include among others arithmetic, relational and logical operators. Arithmetic operators Relational operators Logical, assignment operators Increment, decrement, conditional operators Bitwise and special operators.

2.2 OPERATORS OF CC supports a rich set of operators. Operators are used in programs to manipulate data and

variables. They usually form a part of the mathematical of logical expressions. C operators are classified into a number of categories. They include:1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and Decrement operators6. Conditional operators7. Bitwise operators8. Special operators

2.2.1 ARITHMETIC OPERATORSThe operators are

+ (Addition)- (Subtraction)* (Multiplication)/ (Division)% (Modulo division)

E.g.: 1) a-b 2) a+b 3) a*b 4) p%q The modulo division produces the remainder of an integer division. The modulo division operator cannot be used on floating point data.

Note: C does not have any operator for exponentiation.

2.2.1.1 Integer Arithmetic

15

Page 22: C BOOKnewcopy

C Language 2-Operators

When both the operands in a single arithmetic expression are integers, the expression is called an integer expression, and the operation is called integer arithmetic. During modulo division the sign of the result is always the sign of the first operand.That is-14 % 3 = -2-14 % -3 = -214 % -3 = 2

2.2.1.2 Real ArithmeticAn arithmetic operation involving only real operands is called real arithmetic. If x and y

are float then we will have: x = 6.0 / 7.0 = 0.857143 y = 1.0 / 3.0 = 0.333333

The operator % cannot be used with real operands.

2.2.1.3 Mixed-mode ArithmeticWhen one of the operands is real and the other is integer, the expression is called a

Mixed-mode arithmetic expression and its result is always a real number.E.g.: 15 / 10.0 = 1.5

Programs for arithmetic operation(a) main( )

{ float a = 5, b = 2 ; int c ; c = a +b ; printf ( "%d", c ) ; }

The output of c is 7

(b) main( ) { int a, b ; a = -3 - - 3 ; b = -3 - - ( - 3 ) ; printf ( "a = %d b = %d", a, b ) ; }

The output of a = 0 and b=-6

(c) main( )

16

Page 23: C BOOKnewcopy

C Language 2-Operators

{ int i = 2, j = 3, k, l ; float a, b ; k = i / j * j; l = j / i * i; a = i / j * j; b = j / i * i; printf ( "%d %d %f %f", k, l, a, b ) ; }

The output is 0 2 0.000000 2.000000

(d) main( ) { int a = 5, b = 2 ; int c ; c = a % b ; printf ( "%d", c ) ; }

The output of c =1

2.2.2 RELATIONAL OPERATORSComparisons can be done with the help of relational operators. The expression

containing a relational operator is termed as a relational expression. The value of a relational expression is either one or zero.

< (is less than)<= (is less than or equal to)> (is greater than)>= (is greater than or equal to)= = (is equal to)!= (is not equal to)

E.g.: o if (age>55 )

o if (a<b),

o if (a<b),

o if (a<b),

o if (a<b)

2.2.3 LOGICAL OPERATORSC has the following three logical operators.

&& (logical AND)|| (logical OR)

17

Page 24: C BOOKnewcopy

C Language 2-Operators

! (logical NOT) E.g.:

o if (age>55 && salary<1000)

o if (number<0 || number>100)

This relational operator and logical operator are performed with control statements and they are discussed detailed in chapter 3.

2.2.4 ASSIGNMENT OPERATORSThe usual assignment operator is ‘=’.In addition, C has a set of ‘shorthand’ assignment

operators of the form, v op = exp; E.g.:

o 1.x += y+1;

This is same as the statemento x=x+(y+1);

Shorthand assignment operator:S t a t e m e n t w i t h Statement with simpleshorthand operator assignment operatora + =1 a = a + 1a - = 1 a = a – 1a *= n + 1 a = a * (n+1)a /= n + 1 a = a / (n+1)a %= b a = a % b

Programs for assignment operation(a) main ()

{int i, king,issac,noteit ; i = i + 1; king = issac * 234 + noteit - 7689 ;

2.2.5 INCREMENT AND DECREMENT OPERATORSC has two very useful operators that are not generally found in other languages. These

are the increment and decrement operator:++ and --The operator ++ adds 1 to the operands while – subtracts 1.It takes the following form:++m; or m++--m; or m—

Programs for increment/Decrement operation

18

Page 25: C BOOKnewcopy

C Language 2-Operators

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

The output is 3 3 1

(b) main (){int a=10;y= --a + --a + --aprintf (“\n%d%d”, y, a);getch();}

The output is of y=24, a=7

2.2.6 CONDITIONAL OPERATORA ternary operator pair “?,:” is available in C to construct conditional expression of the

form: exp1? exp2: exp3;Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and

becomes the value of the expression. If exp1 is false then exp3 is evaluated and its value becomes the value of the expression.E.g.: if (a>b)x = a;elsex = b;

2.2.7 BITWISE OPERATORSOperator Meaning& Bitwise AND| Bitwise OR^ Bitwise XOR<< Shift left>> Shift right~ One’s complement

Program for Bitwise operator:(a) main( )

19

Page 26: C BOOKnewcopy

C Language 2-Operators

{ int j=0b00000111, k ; printf ( "\n Decimal %d is same as binary ", j ) ; showbits ( j ) ; k = ~j ; printf ( "\n One’s complement of %d is ", j ) ;showbits ( k ) ;

} }

And here is the output of the above program... Decimal 0 is same as binary 00001111 One’s complement of 0 is 11110000

(b) main( ) {int i = 5225, k ; printf ( "\n Decimal %d is same as binary ", i ) ;

showbits ( i ) ; k = i >>1; printf ( "\n%d right shift %d gives ", i) ; showbits ( k ) ; }

The output of the above program would be... Decimal 5225 is same as binary 0001010001101001 5225 right shift 1gives 0000101000110100, equivalent decimal value is 2614.

(c) main( ){int i = 5225, j, k ;printf ( "\nDecimal %d is same as ", i ) ;showbits ( i )k = i <<1 ;printf ( "\n%d left shift %d gives ", i, j ) ;showbits ( k ) ;}

The output of the above program would be... Decimal 5225 are same as binary 0001010001101001 5225 left shift 1 gives 0010100011010010, equivalent decimal value is 10450.

(d) main( )

20

Page 27: C BOOKnewcopy

C Language 2-Operators

{int i = 65, j ; printf ( "\nvalue of i = %d", i ) ; j = i & 32 ; if ( j == 0 ) printf ( "\n and its fifth bit is off" ) ; else printf ( "\n and its fifth bit is on" ) ; j = i & 64 ; if ( j == 0 ) printf ( "\n whereas its sixth bit is off" ) ; else printf ( "\n whereas its sixth bit is on" ) ; }

And here is the output... Value of i = 65 and its fifth bit is off whereas its sixth bit is on

(e) main( ) { int b = 50 ; b = b ^ 12 ; printf ( "\n%d", b ) ; b = b ^ 12 ; printf ( "\n%d", b ) ; }

And here is the output... Value of b=62, b=50

2.2.8 SPECIAL OPERATORSC supports some special operators such as

Comma operator Size of operator Pointer operators (& and *) and Member selection operators (. and -)

2.2.8.1 The Comma OperatorThe comma operator can be used to link the related expressions together. A comma linked List of expressions is evaluated left to right and the value of right-most expression is the value of the combined expression.

21

Page 28: C BOOKnewcopy

C Language 2-Operators

E.g.: value = (x = 10, y = 5, x + y); this statement first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15(i.e., 10+5) to value.

2.2.8.2 The Size of Operator The sizeof is a compiler time operator and, when used with an operand, it returns the number of bytes the operand occupies. E.g.: m = sizeof (sum); n = sizeof(long int) k = sizeof(235L)

2.3 Hierarchy of OperationsPriority Operators Description

1st

2nd

3rd

* % /

+ -

=

Multiplication,modular division,division

Addition,subtraction

Equal to

Determine the hierarchy of operations and evaluate the following expression: i = 3 *2 4 + 4 / 4 + 8 - 2 + 5 / 8 Stepwise evaluation of this expression is shown below:

i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8 i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: * i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: / i = 1 + 1+ 8 - 2 + 5 / 8 operation: / i = 1 + 1 + 8 - 2 + 0 operation: / i = 2 + 8 - 2 + 0 operation: + i = 10 - 2 + 0 operation: +

i = 8 + 0 operation : - i = 8 operation: +

Note that 6 / 4 give 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore would evaluate to only an integer constant. Similarly 5 / 8 evaluates to zero, since 5 and 8 are integer constants and hence must return an integer value.

EXERCISE:1. Point out the errors, if any, in the following C statements:

22

Page 29: C BOOKnewcopy

C Language 2-Operators

(a) int = 314.562 * 150 ; (b) name = ‘Ajay’ ; (c) varchar = ‘3’ ; (d) 3.14 * r * r * h = vol_of_cyl ; (e) k = ( a * b ) ( c + ( 2.5a + b ) ( d + e ) ; (f) m_inst = rate of interest * amount in rs ; (g) si = principal * rateofinterest * numberofyears / 100 ; (h) area = 3.14 * r ** 2 ; (i) volume = 3.14 * r ^ 2 * h ; (j) k = ( (a * b ) + c ) ( 2.5 * a + b ) ; (k) a = b = 3 = 4 ; (l) date = '2 Mar 04' ;

Programs: 1. Rajesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.2. If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. 3. If a five-digit number is input through the keyboard, write a program to reverse the number.4. Two numbers are input through the keyboard into two locations C and D. Write a program to interchange the contents of C and D.5. Write a program to calculate simple interest (si=(pnr)/100).

C interview questions: 1. Is left-to-right or right-to-left order guaranteed for operator precedence?Answer: The simple answer to this question is neither. The C language does not always evaluate left-to-right or right-to-left. Generally, function calls are evaluated first, followed by complex expressions and then simple expressions. Additionally, most of today’s popular C compilers often rearrange the order in which the expression is evaluated in order to get better optimized code. You therefore should always implicitly define your operator precedence by using parentheses. For example, consider the following expression:a = b + c/d / function_call() * 5

23

Page 30: C BOOKnewcopy

C Language 2-Operators

The way this expression is to be evaluated is totally ambiguous, and you probably will not get the results you want. Instead, try writing it by using implicit operator precedence:a = b + (((c/d) / function_call()) * 5)Using this method, you can be assured that your expression will be evaluated properly and that the compiler will not rearrange operators for optimization purposes.

2. What does the modulus operator do? The modulus operator (%) gives the remainder of two divided numbers. For instance, consider the following portion of code:x = 15/7If x were an integer, the resulting value of x would be 2. However, consider what would happen if you were to apply the modulus operator to the same equation:x = 15%7The result of this expression would be the remainder of 15 divided by 7, or 1. This is to say that 15 divided by 7 is 2 with a remainder of 1.The modulus operator is commonly used to determine whether one number is evenly divisible into another.

3. Which is unary operator?Increment and decrement operator is also called as unary operator

4. Why increment decrement operator is called as unary operator? Because, it has only one operand a++

5. What is a modulus operator? What are the restrictions of a modulus operator? A Modulus operator gives the remainder value. The result of x%y is obtained by (x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to float or double.

6. What is the difference between the two operators = and ==? = assignment operator which is used to assign value to the operand. e.g.: a=10;== Equality operator which is used to compare two operands. e.g.: a==b

7. What will be the output of x++ + ++x? let, x = 1. Then answer will be. main(){ int x=1,y; y = x++ + ++x; printf("/n%d",y);

24

Page 31: C BOOKnewcopy

C Language 2-Operators

}Answer: y = 3 8. How to differentiate i++* and *++i?i++* is false representation.*++i->First it increment the value of i, after that is points the value to i.

9. Difference between assignment operator and copy constructorTwo major differences between copy constructor and assignment are:(i) Copy constructor doesn’t return any value (not even void) whereas assignment operator returns a value.(ii)  Copy constructor will be called only when a new object is being instantiated whereas assignment operator is called for an existing object to which a new value is being assigned

25

Page 32: C BOOKnewcopy

C Language 3-The Control Structure

3. The Control StructureWe have used sequence control structure in which the various steps are executed

sequentially, in serious programming situations; seldom do we want the instructions to be executed sequentially. Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction.

3.1 BranchingBranching is the process of choosing the right branch for execution, depending on the

result of “conditional statement”. Branch is the term given to the code executed in sequence as a result of change in the program’s flow; the program’s flow can be changed by conditional statements in the program.

As mentioned earlier, a decision control instruction can be implemented in C using: (a) The if statement (b) switch case statement(c) The conditional operators(d) goto statement

3.2 The If Statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two way decision-statement. It takes the following form,

General Form:

26

Page 33: C BOOKnewcopy

C Language 3-The Control Structure

if (test expression)This point of program has two paths to follow, one for the true condition and the other for the false condition.

Flow Chart:

The if statement may be used in different forms depending on the complexity of conditions to be tested. The different forms are,i) simple if statementii) if....else statementiii) Nested if......else statementiv) else if ladder

3.2.1 Simple If Statement: The general form of a simple if statement is as follows,

General formif (test expression){

statement-block;}

statement – x; Here, the statement block may contain a single statement or a group of statements. If the test expression is true then the statement block will be executed; otherwise it will be skipped to the statement – x. This can be shown by the following flowchart,

Flowchart

27

Page 34: C BOOKnewcopy

C Language 3-The Control Structure

Sample Code: Consider the case when we are asked to write a program for exforsys.com where users are asked to give ratings on each article; we want to output different messages depending on the ratings given. Messages are as follow: 1 is bad, 2 is average and 3 are good.

int rate;printf("Please Enter Rating? 1 for bad, 2 for average and 3 for good \n");scanf("%d",&rate);

if(rate==1) { printf("nit is poor"); } if(rate==2) { printf("nit is average"); } if(rate==3) { printf("nit is good"); }

3.2.2 The If....Else Statement:

28

Page 35: C BOOKnewcopy

C Language 3-The Control Structure

The general form of the if....else statement is as follows,

General Formif (test expression) {

true-block statements; }else {

False-block statements; }

statement-x; Here, if the test expression is true, then the true-block statements will be executed, otherwise the false-block statements will be executed. In either case, either true block or false block statements will be executed, not both. The general form can be shown by the following flowchart

Flowchart

Sample Code: Imagine the case where we need an input “greater than or equal to 5” and we want to warn the user if they use invalid input (less than 5).

int number;printf("Please Enter a number greater than or equal to 5?n");scanf(“%d”,&number);

29

Page 36: C BOOKnewcopy

C Language 3-The Control Structure

if(number>=5){printf("\n it is valid");}else{printf("\n it is invalid");}

3.2.3 Nested If...Else Statement: When a series of decisions are involved, we may have to use more than one if....else

statement in nested form as shown below,

General Form:

Here, if the condition 1 is false then it skipped to statement 3. But if the condition 1 is true, then it tests condition 2. If condition 2 is true then it executes statement 1 and if false then it executes statement 2. Then the control is transferred to the statement x. This can also be shown by the following flowchart,

Flowchart:

30

Page 37: C BOOKnewcopy

C Language 3-The Control Structure

Sample code: Write a program to find the biggest of three numbersif(a<b){if(a>c){printf(“Statement a is big”);}else{printf(“statement c is big”)}else{printf(“b is big”);}

3.2.4 The Else If Ladder: When a multipath decision is involved then we use else if ladder. A multipath decision is

a chain in which the statement associated with each else is an if. It takes the following

General Form

31

Page 38: C BOOKnewcopy

C Language 3-The Control Structure

This construct is known as the else if ladder. The conditions are evaluated from the top, downwards. This can be shown by the following flowchart

Flowchart:

Sample Code:

32

Page 39: C BOOKnewcopy

C Language 3-The Control Structure

int num;clrscr();printf(“enter a number below 41”);scanf(“%d”,&num);if(num<=10)printf(“the number is between 1-10”);else if(num<=20)printf(“the number is between 11-20”);else if(num<=30)printf(“the number is between 21-30”);else if(num<=40)printf(“the number is between 31-40”);elseprintf(“the number is above 40”);printf(“\n\n program ends”);getch();}

3.3 Switch-case:The switch-case statement is a multi-way decision statement. Unlike the multiple

decisions statement that can be created using if-else, the switch statement evaluates the conditional expression and tests it against numerous constant values. The branch corresponding to the value that the expression matches is taken during the execution.

The value of the expressions in a switch-case statement must be an ordinal type i.e. int, char, short, long, etc. float and double are not allowed.

The syntax is:switch( expression ){case constant-expression1:

statements1;case constant-expression2:

statements2;case constant-expression3:

statements3;default:

statements4; }

33

Page 40: C BOOKnewcopy

C Language 3-The Control Structure

The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

Flow Chart:

Sample Coding:Consider the following program:

main( ) { int i = 2 ; switch ( i ) { case 1 : printf ( "I am in case 1 \n" ) ; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; } }

The output of this program would be: I am in case 2 I am in case 3

34

Page 41: C BOOKnewcopy

C Language 3-The Control Structure

I am in default If you want that only case 2 should get executed, we didn’t use break in cases, and here the program below there by using a break statement. Note that there is no need for a break statement after the default, since the control comes out of the switch anyway.

main( ) { int i = 2 ; switch ( i ){ case 1 :printf ( "I am in case 1 \n" ) ;break;case 2 :printf ( "I am in case 2 \n" ) ;break;case 3 :printf ( "I am in case 3 \n" ) ;break;default :printf ( "I am in default \n" ) ;}}

The output of this program would be: I am in case 2 At times we may want to execute a common set of statements for multiple cases, this can be done as shown in the following example.

main( ) { char ch ; printf ( "Enter any of the alphabet a, b, or c " ) ;scanf ( "%c", &ch ) ; switch ( ch ) {case 'a' : case 'A' :printf ( "a as in ashar" ) ;

break ; case 'b' : case 'B' : printf ( "b as in brain" ) ; break ;

35

Page 42: C BOOKnewcopy

C Language 3-The Control Structure

case 'c' : case 'C' : printf ( "c as in cookie" ) ; break ; default : printf ( "wish you knew what are alphabets" ) ; } } Here, we are making use of the fact that once a case is satisfied the control simply falls through the case till it doesn’t encounter a break statement. That is why if an alphabet a is entered the case ‘a’ is satisfied and since there are no statements to be executed in this case the control automatically reaches the next case i.e. case ‘A’ and executes all the statements in this case.

3.4 The Conditional Operator:It's called the conditional or ``ternary'' or ?,: operator, and in action it looks something

like this:

The Syntax of the Conditional Operator isExpression 1? Expression 2: expression 3

What this expression says is: “if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3”. Let us understand this with the help of a few examples: Example: average = (n > 0) ? sum / n : 0 In other words, the conditional expression is sort of an if/else statement buried inside of an expression. The above computation of average could be written out in a longer form using an if statement:

if(n > 0)average = sum / n;elseaverage = 0;The conditional operator, however, forms an expression and can therefore be used

wherever an expression can be used. This makes it more convenient to use when an if statement would otherwise cause other sections of code to be needlessly repeated.

3.5 Go to Statement:C has goto statement but one must ensure not to use too much of goto statement in their

program because its functionality is limited and it is only recommended as a last resort if structured solutions are much more complicated. First let us understand the goto statement, its syntax and functionality.

36

Page 43: C BOOKnewcopy

C Language 3-The Control Structure

The goto is an unconditional branching statement used to transfer control of the program from one statement to another.

General Form

goto label;  label:…………. Statement;…………. ………….…………. ………….label:  …………. Statement; goto label;Forward jump backward jumpProgram:

main( ) { int goals ; printf ( "Enter the number of goals scored against India" ) ; scanf ( "%d", &goals ) ; if ( goals <= 5 ) goto sos ; else { printf ( "About time soccer players learnt C\n" ) ; printf ( "and said goodbye! adieu! to soccer" ) ; exit( ) ; /* terminates program execution */ } sos: printf ( "To err is human!" ) ; }

And here are two sample runs of the program... Enter the number of goals scored against India 3 To err is human! Enter the number of goals scored against India 7 About time soccer players learnt C and said goodbye! adieu! to soccer

WORKSHOP

1) If-Else Construct1) Read length & breath: print whether it is square or a rectangular.2) Read 3 nos; Count the negative numbers and print.3) Read an applicants age; print whether his age is between 22 nad 28 or not.4) Read a character; print if it is a vowel or not.

37

Page 44: C BOOKnewcopy

C Language 3-The Control Structure

2) Nested-If-Statements Read a no; print if it is a zero, positive or negative number. Read two nos ; print if both are equal. Otherwise print the biggest. Read three nos; print the biggest number. Read an option 1 or 2; if 1 Read a no; Print if it is an odd or even number; If 2 Read a

no; print if it is a positive or negative number.

3) If-Else If Statements Read a weekday number[1 to 7]; Print weekdays name. Read a percentage of marks; Geade it. A grade :80-100%, B garde:60-70%, C

grade:40-59%, D grade:0-39%. Read a purchase value; Calculate and print the discount amount based on following

condition. No discount for purchase less than Rs.1000.00.2% Discount for purchase upto Rs.2,000.005% Discount for purchase upto Rs.5,000.008% Discount for purchase above Rs.5000.00

4) Switch Construct Read a month number[1 to 12]; print month name. Read a month number[1 to 12]; print if it is first/second/third/fourth quarter. Read two nos; Display the following menu for selection. Then read the option, and do

the appropriate action.a. Addb. Multiplyc. Divided. Do Nothinge. Choose Your Option[1-4]:________

38

Page 45: C BOOKnewcopy

C Language 3-The Control Structure

39

Page 46: C BOOKnewcopy

C Language 4.Looping

4. Looping4.1 INTRODUCTION

The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction. There are three methods by way of which we can repeat a part of a program.

They are: Using(a) For statement (b) Using a while statement (c) Using a do-while statement

4.2 The while statement It is often the case in programming that you want to do something a fixed number of

times. Perhaps you want to calculate gross salaries of ten different persons, or you want to convert temperatures from centigrade to Fahrenheit for 15 different cities. The while loop is ideally suited for such cases. Let us look at which uses a while loop.

General Form:while(test-expression){code to execute}

Flowchart:

40

Test expression

code

false

true

Page 47: C BOOKnewcopy

C Language 4.Looping

Sample Code: Here we will consider the case of repeating the same line of code for 10 times

int counter=1;while(counter <=10){ printf("\n Number: %d",counter);counter++;}

The output of this program would be: 1 2 3 4 5 6 7 8 9 10

4.3 ‘Do...While’ Statement The “do...While” statement is a sentinel controlled repetition which is quite different

from the other two statements we covered earlier. This statement runs the code first and then checks the test-expression, so there is always a guarantee that the code runs atleast once. This type of loop is generally used for password checks and menus.

General Form:do{code to iterate}while(test-expression)

Flow Chart:

41

code

Test expressio

true

false

Page 48: C BOOKnewcopy

C Language 4.Looping

Sample Code: We will consider a simple menu using “do...While” this code for the even numbers between 1 and 10.

int counter;do{ //for(counter=1;counter<=10;counter++){if(counter%2==0)printf("\n number: %d ",counter);}}while(count<=10);

The output of this program would be: 2 4 6 8 10

4.4 The ‘For’ Loop The “For” loops is a counter controlled repetition; therefore the number of iterations must be known before the loop starts.

General Form:for (control-variable; continuation-condition; increment/decrement-control) {Code to iterate} 

Flowchart:

42

Page 49: C BOOKnewcopy

C Language 4.Looping

Sample Code: Consider the case of repeating the same line of code for 10 times. We write the code below.We will consider a simple menu using “do...While” this code for the even numbers between 1 and 10.

int counter;for(counter=1;counter<=10;counter++){if (counter%2==0)printf("\n number: %d ",counter);} 

The output of this program would be: 2 4 6 8 10

4.5 The Break Statement: The “break” statement is used to exit the iteration. This statement is usually used when early escape from the loop is acceptable by the programmer. For example if we are searching for a data, we can use “break” as soon as we find the data to exit the loop. You can simply use “break” by writing “break;” at the point where you want to escape the loop. “break” can be used with all the statements .

Flow Chart:

Sample Code:

43

start

code

break

code

end

Page 50: C BOOKnewcopy

C Language 4.Looping

In this, we will write a program which will escape the loop using “break” as soon as the number is equal to “2”.

main( ){int i = 1 , j = 1;while ( i++ <= 4) { while ( j++ <= 20 ) { if ( j == 15 ) break ; else printf ( "%d %d\n", i, j ) ; }} }

In this program when j equals 15, break takes the control outside the inner while only, since it is placed inside the inner while.

4.6 The Continue Statement The “continue” statement is used to skip the remaining code of the loop and start the

new one. This statement can be implemented by “continue;”

Flow Chart:

Sample Code: We will consider the case in which the loop will skip all the even numbers between 1 and 10.

main( ) {

44

start

code

continue

code

end

Page 51: C BOOKnewcopy

C Language 4.Looping

int i, j ; for ( i = 1 ; i <= 2 ; i++ ){for ( j = 1 ; j <= 2 ; j++ ) {if ( i == j )continue ;printf ( "\n%d %d\n", i, j ) ;}}}

The output of the above program would be... 1 2 2 1

EXERCISE:What would be the output of the following programs? (a)

main( ) { int i = -4, j, num ; j = ( num < 0 ? 0 : num * num ) ; printf ( "\n%d", j ) ; }

(b) main( ) { int k, num = 30 ; k = ( num > 5 ? ( num <= 10 ? 100 : 200 ) : 500 ) ; printf ( "\n%d", num ) ; }

(c) main( ) { int j = 4 ; ( !j != 1 ? printf ( "\n Welcome") : printf ( "\n Good Bye") ) ;}

(d) main( ) {

45

Page 52: C BOOKnewcopy

C Language 4.Looping

int i = 0 ; for ( ; i ; )printf ( "\n Here is some mail for you" ) ; }

(e) main( ) { int i ; for ( i = 1 ; i <= 5 ; i++)printf ( "\n%d", i ) ; }

(f) main( ) { int i = 1, j = 1 ; for ( ; ; ) { if ( i > 5 ) break; else j += i ; printf ( "\n%d", j ) ; i += j; } }

(g) main( ) { int i ; for ( i = 1 ; i <= 5 ;i++) printf ( "\n %d", i ) ; }

(h) main( ) { int i ; for ( i = 1 ; i <= 5 ;); printf ( "\n%d", i ) ; i++;

46

Page 53: C BOOKnewcopy

C Language 4.Looping

}

(i) main( ) { int i = 1, j = 1 ; for ( ; ; ) { if ( i > 5 ) break; else j += i; printf ( "\n%d", j ) ; i += j; } }

(j) main( ) { int i ; for ( i = 1 ; i <= 5 ;); printf ( "\n%c", 65 ) ; i++; }

PROGRAMS1. Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.2. Write a program to find out whether it is an odd number or even number.3. Write a c program to find the eligibility for vote using if statement4. Write a c program to find the largest of three numbers using nested if5. Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not. 6. Write a c program using else if ladder to find the rank of 10 students using their marks7. Write a program to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in. 8. Write a program to print all prime numbers from 1 to 300. (Hint: Use nested loops, break and continue)9. Write a program to produce the following output: 11 2

47

Page 54: C BOOKnewcopy

C Language 4.Looping

1 2 31 2 3 41 2 3 4 5

10. Write a program to find the factorial value of any number 11. Write a program to print all prime numbers from 1 to 300. Using nested loops, break and continue12. Write a program to generate all combinations of 1, 2 and 3 using while loop. 13. Write a program to fill the entire screen with diamond and heart alternatively. The ASCII value for heart is 3 and that of diamond is 4. 14. What would be the output of the following programs?

C INTERVIEW QUESTIONS:1. What is a loop? In looping, a sequence of statements is executed until some conditions for terminating of the loop are satisfied. A program loop contains two parts, body of the loop and control statements. 

2. What is the difference between entry-controlled loop and exit-controlled loop? In the entry-controlled loop, the control conditions are tested before the start of the loop execution. If the conditions are not satisfied, then the body of the loop will not be executed. In the case of an exit-controlled loop, the test is performed at the end of the body of loop and therefore the body is executed unconditionally for the first time.

3. What is the difference between a break statement and a continue statement?A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

4. When is a switch statement better than multiple if statements? A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type.

5. Why n++ executes faster than n+1? n++ executes faster than n+1 because n++ want only one instruction for execution where

n+1 want more one instruction for execution.

It (n+1) creates extra memory for adding. Whereas n++ refers to same memory.

6. How many times the below loop will run   main()    {

48

Page 55: C BOOKnewcopy

C Language 4.Looping

     int i;      i = 0;    do    {         --i;          printf (“%d”,i);          i++;   } while (i >= 0)}Output:InfiniteExplanation: In every iteration value of i is decremented and then incremented so remains 0 and hence an Infinite Loop.

7. What would be the output if option = ‘H’? switch (option) {case ‘H’ : printf(“Hello”);case ‘W’ : printf(“Welcome”);case ‘B’ : printf (“Bye”);                 break;          }Output:Hello Welcome ByeExplanation : If option = ‘H’ then the first case is true so “Hello” gets printed but there is no break statement after this case to come out of the switch statement so the program execute all other case statements also and Hello Welcome Bye gets printed.

8. Suppose a, b, c are integer variables with values 5, 6, 7 respectively. What is the  value of the expression?                  ! ((b + c) > (a + 10)) Output:1 Explanation:   1.! ((b + c) > (a + 10))    2.!((6 + 7) > (5+10))   3.!(13 > 15)   13 is less than 15 so it will return False (0 ).    4.!(0).    Not of 0 is 1.

WORKSHOP

‘For’ loop construct: Number series printing1. Print the number series:0,5,10,15,20,25,30,35,402. Print the number series: 2,4,8,16,32,64

49

Page 56: C BOOKnewcopy

C Language 4.Looping

3. Print the number of series: 100,90,80,70,60,50,40,30,20,10,0

Loop Construct: Summation1. Generate Series : 30 24 18 12 6 2. Generate Series : 15 20 25 30 35 40 453. Read 10 numbers and print the sum & average.

Loop Construct : Conditional1. Read 10 numbers and print the total even nos and total odd number.2. Read 2 nos, but keep the biggest no; finally print the biggest no.

Loop Constructs : break & Continue

1. Print the series:1,2,4,8,16,32,….; stop after printing 10 nos.2. Print the series: 1,2,4,8,16,32,…; Stop when reached above 100.3. Read a no; print if it is prime no or not.

While Loop : Pre-determined count1. Print the series: 2,4,6,8,…202. Print the series: 1,10,100,1000,100003. Print the sum of the series: 1,2,4,8,16,32,…1024

While Loops: Undetermined loop—Get an option to stop

1. Read ‘n’ number: Ask the user [y/n] before proceeding to next number. Finall print the sum of all read number.

2. Display the following menu for selection. Then read the option, and do the appropriate action.

3. Add4. Multiply5. Stop6. Choose your option[1-3]

While loops: Undetermined loop—Detect a sentinel value to stop

1. Read ‘n’ numbers; stop reading when zero is input. Finally print the sum of all read numbers.

2. Read age and print; But repeat to ask until an age not lesser that 25 is entered.

50

Page 57: C BOOKnewcopy

C Language 4.Looping

Do-while loops1. Print the series 10,9,8,7….12. Read ‘n’ number; Ask the user [1/2] before proceeding to next number. Finally print

the sum of all read numbers.

51

Page 58: C BOOKnewcopy

C Language 5-Functions and pointers

5. Functions and pointers5.1 Introduction

A function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions. As we noted earlier, using a function is something like hiring a person to do a specific job for you. Sometimes the interaction with this person is very simple; sometimes it’s complex.

5.1.1. Let us now look at a simple C function, actually, we will be looking at two things—a function that calls or activates the function and the function itself.

main( ) { message( ) ; printf ( "\n hai “) ; } message( ) { printf ( "\n hello..." ) ; }

And here’s the output... hello...hai

5.1. 2. If you have grasped the concept of ‘calling’ a function you are prepared to call more than one function. Consider the following example:

main( ) { printf ( "\nI am in main" ) ; italy( ) ; brazil( ) ; argentina( ) ; }italy( ) { printf ( "\nI am in italy" ) ; } brazil( ) { printf ( "\nI am in brazil" ) ; } argentina( )

52

Page 59: C BOOKnewcopy

C Language 5-Functions and pointers

{ printf ( "\nI am in argentina" ) ; }

The output of the above program when executed would be as under: I am in main I am in italy I am in brazil I am in argentina Let’s illustrate with another example. main( )

{ printf ( "\nI am in main" ) ; italy( ) ; printf ( "\nI am finally back in main" ) ; } italy( ) { printf ( "\nI am in italy" ) ; brazil( ) ; printf ( "\nI am back in italy" ) ; } brazil( ) { printf ( "\nI am in brazil" ) ; argentina( ) ; } argentina( ) { printf ( "\nI am in argentina" ) ; }

And the output would look like... I am in main I am in italy I am in brazil I am in argentina I am back in italy I am finally back in main 5.1.3. Here, main( ) calls other functions, which in turn call still other functions. Trace carefully the way control passes from one function to another. Since the compiler always begins the program execution with main( ), every function in a program must be called directly or indirectly by main( ). In other words, the main( ) function drives other functions.

53

Page 60: C BOOKnewcopy

C Language 5-Functions and pointers

Any function can be called from any other function. Even main( ) can be called from other functions. For example,

main( ) { message( ) ; } void message( ) {

printf ( "\nCan't imagine life without C" ) ; main( ) ; }

5.1.4. A function can be called any number of times. For example, main( ) { message( ) ; message( ) ; } message( ) { printf ( "\nJewel Thief!!" ) ; }

5.1.5. The order in which the functions are defined in a program and the order in which they get called need not necessarily are same. For example, main( )

{ message1( ) ; message2( ) ;

} message2( ) { printf ( "\nBut the butter was bitter" ) ; } message1( ) {

printf ( "\nMary bought some butter" ) ; }

However, it is advisable to define the functions in the same order in which they are called. This makes the program easier to understand.

54

Page 61: C BOOKnewcopy

C Language 5-Functions and pointers

5.1.6. A function can be called from other function, but a function cannot be defined in another function.

main( ) {

printf ( "\nI am in main" ) ; void argentina( ) { printf ( "\nI am in argentina" ) ; }

}There are basically two types of functions: Library functions Ex. printf( ), scanf( ) etc. User-defined functions Ex. argentina( ), brazil( ) etc.

5.1.7. Why Use Functions Writing functions avoids rewriting the same code over and over. Using functions it becomes easier to write programs and keep track of what they are

doing. Separating the code into modular functions also makes the program easier to design and

understand.

5.2 Passing Values between FunctionsConsider the following program. In this program, in main( ) we receive the values of a, b and c through the keyboard and then output the sum of a, b and c. However, the calculation of sum is done in a different function called calsum( ). If sum is to be calculated in calsum( ) and values of a, b and c are received in main( ), then we must pass on these values to calsum( ), and once calsum( ) calculates the sum we must return it from calsum( ) back to main( )./* Sending and receiving values between functions */

int calsum(int x,int y,int z);main( ) { int a, b, c, sum ;printf ( "\nEnter any three numbers " ) ;scanf ( "%d %d %d", &a, &b, &c ) ;sum = calsum ( a, b, c ) ;printf ( "\nSum = %d", sum ) ;} calsum ( x, y, z ) {int x, y, z ;

55

Page 62: C BOOKnewcopy

C Language 5-Functions and pointers

int d ; d = x + y + z; return ( d ) ; }

And here is the output... Enter any three numbers 10 20 30 Sum = 60

5.3 Calling Convention Calling convention indicates the order in which arguments are passed to a function when a function call is encountered. There are two possibilities here: (a) Arguments might be passed from left to right. (b) Arguments might be passed from right to left. For example:

int a = 1 ; printf ( "%d %d %d", a, ++a, a++ ) ;

It appears that this printf( ) would output 1 2 3. This however is not the case. Surprisingly, it outputs 3 3 1. This is because C’s calling convention is from right to left. That is, 1 is passed through the expression a++ and then a is incremented to 2. Then result of ++a is passed. That is, a is incremented to 3 and then passed. Finally, latest value of a, i.e. 3, is passed. Thus in right to left order 1, 3, 3 get passed. Once printf ( ) collects them it prints them in the order in which we have asked it to get them printed (and not the order in which they were passed). Thus 3 3 1 gets printed.

5.4 Advanced Features of Functions Following advanced topics would be considered here. (a) Function Declaration and Prototypes (b) Calling functions by value or by reference (c) Recursion

5.4.1 Function Declaration and Prototypes Any C function by default returns an int value. More specifically, whenever a call is made to a function, the compiler assumes that this function would return a value of the type int. If we desire that a function should return a value other than an int, then it is necessary to explicitly mention so in the calling function as well as in the called function. Suppose we want to find out square of a number using a function. The following program segment illustrates how to make square( ) capable of returning a float value.

main( ) {

56

Page 63: C BOOKnewcopy

C Language 5-Functions and pointers

float square ( float ) ; float a, b ; printf ( "\nEnter any number " ) ; scanf ( "%f", &a ) ; b = square ( a ) ; printf ( "\nSquare of %f is %f", a, b ) ; } float square ( float x ) { float y ; y = x * x ; return ( y ) ; }

And here is the output... Enter any number 1.5 Square of 1.5 is 2.250000 Enter any number 2.5 Square of 2.5 is 6.250000

5.4.2 Call by Value and Call by ReferenceThis feature of C functions needs at least an elementary knowledge of a concept called ‘pointers’. So let us first acquire the basics of pointers after which we would take up this topic once again.

5.5 An Introduction to PointersIn our discussion of C pointers, therefore, we will try to avoid this difficulty by explaining pointers in terms of programming concepts we already understand. The first thing we want to do is explain the rationale of C’s pointer notation.

5.5.1 Pointer Notation Consider the declaration, int i = 3 ; This declaration tells the C compiler to: (a) Reserve space in memory to hold the integer value. (b) Associate the name i with this memory location. (c) Store the value 3 at this location. i variable name

value

65524 location

57

5

Page 64: C BOOKnewcopy

C Language 5-Functions and pointers

We see that the computer has selected memory location 65524 as the place to store the value 3. The location number 65524 is not a number to be relied upon, because some other time the computer may choose a different location for storing the value 3. The important point is, i’s address in memory is a number. We can print this address number through the following program:

main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; }

The output of the above program would be: Address of i = 65524 Value of i = 3

Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The expression &i returns the address of the variable i, which in this case happens to be 65524. Hence it is printed out using %u, which is a format specifier for printing an unsigned integer. We have been using the ‘&’ operator all the time in the scanf( ) statement.

The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; }

The output of the above program would be: Address of i = 65524 Value of i = 3 Value of i = 3

The expression &i gives the address of the variable i. This address can be collected in a variable, by saying, j = &i; and since j is a variable that contains the address of i, it is declared as, int *j; this declaration tells the compiler that j will be used to store the

58

Page 65: C BOOKnewcopy

C Language 5-Functions and pointers

address of an integer value. In other words j points to an integer. Here is a program that demonstrates the relationships we have been discussing.

main( ) {

int i = 3 ; int *j ; j = &i ; printf ( "\nAddress of i = %u", &i ) ;

printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of j = %u", &j ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; printf ( "\nValue of i = %d", *j ) ;

} The output of the above program would be: Address of i = 65524 Address of i = 65524 Address of j = 65522 Value of j = 65524 Value of i = 3 Value of i = 3 Value of i = 3 i j

65524 65526

Pointer, we know is a variable that contains address of another variable. Now this variable itself might be another pointer. Thus, we now have a pointer that contains another pointer’s address. The following example should make this point clear. main( ) {

int i = 3, *j, **k ; j = &i ;

k = &j; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of i = %u", *k ) ;

59

5 3 65524

Page 66: C BOOKnewcopy

C Language 5-Functions and pointers

printf ( "\nAddress of j = %u", &j ) ; printf ( "\nAddress of j = %u", k ) ; printf ( "\nAddress of k = %u", &k ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of k = %u", k ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", * ( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; printf ( "\nValue of i = %d", **k ) ;

} The output of the above program would be: Address of i = 65524 Address of i = 65524 Address of i = 65524 Address of j = 65522 Address of j = 65522 Address of k = 65520 Value of j = 65524 Value of k = 65522 Value of i = 3 Value of i = 3 Value of i = 3 Value of i = 3 i j k

65524 65522 65520

Observe how the variables j and k have been declared, int i, *j, **k ; Here, i is an ordinary int, j is a pointer to an int (often called an integer pointer), whereas

k is a pointer to an integer pointer. We can extend the above program still further by creating a pointer to a pointer to an integer pointer. There is no limit on how far can we go on extending this definition.

5.5.2 Back to Function Calls Having had the first try with pointers let us now get back to what we had originally set out to learn—the two types of function calls—call by value and call by reference. Arguments can generally be passed to functions in one of the two ways: (a) Sending the values of the arguments

60

5 3 65524 65522

Page 67: C BOOKnewcopy

C Language 5-Functions and pointers

(b) Sending the addresses of the arguments

5.5.2.1 Call by valueIn the first method the ‘value’ of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. The following program illustrates the ‘Call by Value’.

main( ) { int a = 10, b = 20 ; swapv ( a, b ) ; printf ( "\na = %d b = %d", a, b ) ; } swapv ( int x, int y ) { int t ; t = x ; x = y ; y = t ; printf ( "\n x = %d y = %d", x, y ) ; }

The output of the above program would be:x = 20 y = 10 a = 10 b = 20 Note that values of a and b remain unchanged even after exchanging the values of x and y.

5.5.2.2 Call by reference In the second method (call by reference) the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them. The following program illustrates this fact.

Example 1: main( ) { int a = 10, b = 20 ; swapr ( &a, &b ) ; printf ( "\na = %d b = %d", a, b ) ; } swapr( int *x, int *y )

61

Page 68: C BOOKnewcopy

C Language 5-Functions and pointers

{ int t ;

t = *x; *x = *y; *y = t; }

The output of the above program would be: a = 20 b = 10

5.4.2 Call by Value and Call by Reference

1.Call By Values : Values passed

2. Call By Reference : Address passed

The first type refers to call by value and the second type refers to call by reference.

For instance consider program1

main() { int x=50, y=70; interchange(x,y); printf(“x=%d y=%d”,x,y); }

interchange(x1,y1) int x1,y1; { int z1; z1=x1; x1=y1; y1=z1; printf(“x1=%d y1=%d”,x1,y1); }

Here the value to function interchange is passed by value.

Consider program2

main() { int x=50, y=70; interchange(&x,&y); printf(“x=%d y=%d”,x,y);

62

Page 69: C BOOKnewcopy

C Language 5-Functions and pointers

}

interchange(x1,y1) int *x1,*y1; { int z1; z1=*x1; *x1=*y1; *y1=z1; printf(“*x=%d *y=%d”,x1,y1); }

5.5.3 Recursion In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.Following is the recursive version of the function to calculate the factorial value.

main( ) { int a, fact ; printf ( "\nEnter any number " ) ; scanf ( "%d", &a ) ; fact = rec ( a ) ; printf ( "Factorial value = %d", fact ) ; } rec ( int x ) { int f ; if ( x == 1 ) return ( 1 ) ; else f = x * rec ( x - 1 ) ; return ( f ) ; }

And here is the output for four runs of the program Enter any number 1 Factorial value = 1 Enter any number 2 Factorial value = 2 Enter any number 3Factorial value = 6

63

Page 70: C BOOKnewcopy

C Language 5-Functions and pointers

Let it be clear that while executing the program there does not exist so many copies of the function rec( ). These have been shown in the figure just to help you keep track of how the control flows during successive recursive calls.

from main( )

rec(int x){int f;if(x==1)return(1)elsef=x*rec(x-1);return(f);}to main( )

rec(int x){int f;if(x==1)return(1)elsef=x*rec(x-1);return(f);}

rec(int x){int f;if(x==1)return(1)elsef=x*rec(x-1);return(f);}

EXERCISEWhat would be the output of the following programs? (a)

main( ) { int i = 45, c ; c = multiply ( i * 1000 ) ; printf ( "\n%d", c ) ; } check ( int ch ) { if ( ch >= 40000 ) return ( ch / 10 ) ; else return ( 10 ) ; }

(b)int *call(); void main(){ int *ptr; ptr=call(); clrscr(); printf("%d",*ptr);

64

Page 71: C BOOKnewcopy

C Language 5-Functions and pointers

} int * call(){ int x=25; ++x; return &x; }

(c)void main(){ int *ptr; printf("%u\n",ptr); printf("%d",*ptr); }

(d) int *p;    int *q= (int *)0;#include<stdio.h>int *r=NULL;   What will be output of following c program?

(e)#include<string.h>#include<stdio.h>void main(){

    char *p;        char *q=NULL;         strcpy(p,"cquestionbank");    strcpy(q,"cquestionbank");    clrscr();    printf("%s  %s",p,q);    getch();}

(f) main( ) {

void slogan( ) ; int c = 5 ; c = slogan( ) ; printf ( "\n%d", c ) ;

65

Page 72: C BOOKnewcopy

C Language 5-Functions and pointers

} void slogan( ) {

printf ( "\nOnly He men use C!" ) ; }

(g)main( ) { int i = 5, j = 2 ; junk ( &i, &j ) ; printf ( "\n%d %d", i, j ) ; } junk ( int *i, int *j ) { *i = *i * *i ; *j = *j * *j ; }

(h)

main( ) { int i = 4, j = 2 ; junk ( &i, j ) ; printf ( "\n%d %d", i, j ) ; } junk ( int *i, int j ) { *i = *i * *i ; j = j * j ; }

(i)

main( ) { float a = 13.5 ; float *b, *c ; b = &a ; /* suppose address of a is 1006 */c = b ; printf ( "\n%u %u %u", &a, b, c ) ; printf ( "\n%f %f %f %f %f", a, *(&a), *&a, *b, *c ) ;

66

Page 73: C BOOKnewcopy

C Language 5-Functions and pointers

}

(j)main( ) { int i = 0 ; i++ ; if ( i <= 5 ) { printf ( "\nC adds wings to your thoughts" ) ; exit( ) ; main( ) ; } }

PROGRAMS:1. Write a function to calculate the factorial value of any integer entered through the keyboard. 2. Write a function power (a, b), to calculate the value of a raised to b.3. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89... 4. Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. Call this function from main( ) and print the results in main( ).5. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number: (1) Without using recursion (2) Using recursion 6. Write a program to find the area and perimeter of the circle.

C INTERVIEW QUESTIONS1. What is dangling pointer in c? If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.

2. What is wild pointer in c? Wild pointer:A pointer in c which has not been initialized is known as wild pointer.Example:

67

Page 74: C BOOKnewcopy

C Language 5-Functions and pointers

What will be output of following c program?#include<stdio.h>int main(){

int *ptr;printf("%u\n",ptr);printf("%d",*ptr);return 0;}

Output: Any addressGarbage value3. What is NULL pointer in c?Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment.Examples of NULL pointer:1. int *ptr=(char *)0;2. float *ptr=(float *)0;3. char *ptr=(char *)0;

4. What is Generic pointer in c?void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point to any type of data.Example:void *ptr;Here ptr is generic pointer.

5. What is Far pointer in c programming? The pointer which can point or access whole the residence memory of RAM i.e. which can access all 16 segments is known as far pointer.

6. What is near pointer in c programming? The pointer which can points only 64KB data segment or segment number 8 is known as near pointer.

7. What is huge pointer in c programming? The pointer which can point or access whole the residence memory of RAM i.e. which can access all the 16 segments is known as huge pointer.

8. What is size of void pointer?  

68

Page 75: C BOOKnewcopy

C Language 5-Functions and pointers

Size of any type of pointer in c is independent of data type which is pointer is pointing i.e. size of all type of pointer (near) in c is two byte either it is char pointer, double pointer, function pointer or null pointer.  void pointer is not exception of this rule and size of void pointer is also two byte.

9. What is difference between uninitialized pointer and null pointer?  An uninitialized pointer is a pointer which points unknown memory location while null pointer is pointer which points a null value or base address of segment.

10. What is a const pointer?A const pointer means the pointer which represents the address of one value. So if you declare a pointer inside the function, it doesn't have scope outside the function. If it is also available to the outside function whenever we declare a pointer as const.

11. Declare a pointer which can point printf function in c.int (*ptr)(char const,…);

12. What is a pointer variable? A pointer variable is a variable that may contain the address of another variable or any valid address in the memory.

13. Using the variable a, give definitions for the following: a) An integer

b) A pointer to an integer c) A pointer to a pointer to an integer d) An array of 10 integerse) An array of 10 pointers to integers f) A pointer to an array of 10 integers g) A pointer to a function that takes an integer as an argument and returns an integer h) An array of ten pointers to functions that take an integer argument and return an integer

The answers are: a) int a; // An integer b) int *a; // A pointer to an integer c) int **a; // A pointer to a pointer to an integer d) int a[10]; // An array of 10 integers e) int *a[10]; // An array of 10 pointers to integers f) int (*a)[10]; // A pointer to an array of 10 integers g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer

69

Page 76: C BOOKnewcopy

C Language 5-Functions and pointers

h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer

14. How are pointer variables initialized? Pointer variable are initialized by one of the following two ways - Static memory allocation - Dynamic memory allocation

15. What is a pointer value and address? A pointer value is a data object that refers to a memory location. Each memory location is numbered in the memory. The number attached to a memory location is called the address of the location.

16. What is an argument? Differentiate between formal arguments and actual arguments? Using argument we can pass the data from calling function to the called function. Arguments available in the function definition are called formal arguments. Can be

preceded by their own data types. We use Actual arguments in the function call.

17. What is Function Pointer? Explain with an example? Using function pointer we can do almost anything with function name. We can pass

parameters to a function that is called as pointer. A classic example is the library function qsort(), which takes a pointer to a function. This pointer often is coded as a constant; you might, however, want to code it as a function pointer variable that gets assigned the correct function to sort()½s compare. I have given you a example of Function pointer.

Function named function () is defined which will be called through a function pointer. A function named caller () accepts as parameters a function pointer and an integer, which will be passed as arguments to the function that will be called by caller ().

Example program:#include static void function(int a){ printf("function: %d\n", a); }static void caller(void (*func)(int), int p){ (*func)(p); }int main(void){ caller(function, 10); return 0;}

70

Page 77: C BOOKnewcopy

C Language 5-Functions and pointers

WORKSHOP1. Create a function that accepts a number and prints the square and cube values.2. Create a function that accepts a number prints cube value.3. Create a function that accepts a number and returns its factorial.4. Create a function that accepts a number and returns whether it is a prime number or

not.

71

Page 78: C BOOKnewcopy

C Language 6-Arrays

6. ARRAYS6.1 INTRODUCTIONAn array is a fixed size sequence collection of elements of same data types. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. However big an array its elements are always stored in contiguous memory locations.

6.2 One Dimensional Array: An array with a single subscript is known as one dimensional array.E.g. int number [5];The values to array elements can be assigned as follows.E.g.

number [0] = 35;number [1] = 40;number [2] = 20;

6.2.1 Declaration of Arrays:The general form of array declaration is:

The type specifies the type of element that will be contained in the array, such as int, float, or char and the size indicates the maximum number of elements that can be stored inside the array.E.g.:

float height [50];int group [10];char name [10];

6.2.2 Initialization of Arrays:The general form of initialization of arrays is:

static type arrayname[size]={values}

main( ) { int avg, sum = 0 ; int i ; int marks[30] ; /* array declaration */ for ( i = 0 ; i <= 29 ; i++ ) {

72

Page 79: C BOOKnewcopy

C Language 6-Arrays

printf ( "\nEnter marks " ) ; scanf ( "%d", &marks[i] ) ; /* store data in array */ } for ( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ; /* read data from an array*/ avg = sum / 30 ; printf ( "\nAverage marks = %d", avg ) ; }

There is a lot of new material in this program, so let us take it apart slowly.

6.2.3 Function and Array:6.2.3.1 Passing Array Elements to a Function Array elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function. These two calls are illustrated below: /* Demonstration of call by value */

main( ) { int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ; for ( i = 0 ; i <= 6 ; i++ ) display ( marks[i] ) ; } display ( int m ) { printf ( "%d ", m ) ; }

And here’s the output... 55 65 75 56 78 78 90 Here, we are passing an individual array element at a time to the function display ( ) and getting it printed in the function display ( ). Note that since at a time only one element is being passed, this element is collected in an ordinary integer variable m, in the function display ( )./* Demonstration of call by reference */

main( ) { int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ; for ( i = 0 ; i <= 6 ; i++ )

73

Page 80: C BOOKnewcopy

C Language 6-Arrays

disp ( &marks[i] ) ; } disp ( int *n ) { printf ( "%d ", *n ) ; }

And here’s the output... 55 65 75 56 78 78 90 Here, we are passing addresses of individual array elements to the function display ( ). Hence, the variable in which this address is collected (n) is declared as a pointer variable. And since n contains the address of array element, to print out the array element we are using the ‘value at address’ operator (*).

6.2.3.2 Pointers and Arrays:To be able to see what pointers have got to do with arrays, let us first learn some pointer arithmetic. Consider the following example:

main( ) { int i = 3, *x ; float j = 1.5, *y ; char k = 'c', *z ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of j = %f", j ) ; printf ( "\nValue of k = %c", k ) ; x = &i ; y = &j ; z = &k ; printf ( "\nOriginal address in x = %u", x ) ; printf ( "\nOriginal address in y = %u", y ) ; printf ( "\nOriginal address in z = %u", z ) ; x++ ; y++ ; z++ ; printf ( "\nNew address in x = %u", x ) ; printf ( "\nNew address in y = %u", y ) ; printf ( "\nNew address in z = %u", z ) ; }

Here is the output of the program. Value of i = 3 Value of j = 1.500000

74

Page 81: C BOOKnewcopy

C Language 6-Arrays

Value of k = c Original address in x = 65524 Original address in y = 65520 Original address in z = 65519 New address in x = 65526 New address in y = 65524 New address in z = 65520

This is illustrated in the following program. main( ) { int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ; int *i, *j ; i = &arr[1] ; j = &arr[5] ; printf ( "%d %d", j - i, *j - *i ) ; }

Here i and j have been declared as integer pointers holding addresses of first and fifth element of the array respectively.

Suppose the array begins at location 65502, then the elements arr[1] and arr[5] would be present at locations 65504 and 65512 respectively, since each integer in the array occupies two bytes in memory. The expression j - i would print a value 4 and not 8. This is because j and i are pointing to locations that are 4 integers apart. What would be the result of the expression *j - *i? 36, since *j and *i return the values present at addresses contained in the pointers j and i.

Our next programs show ways in which we can access the elements of this array. main( ) { int num[ ] = { 24, 34, 12, 44, 56, 17 } ; int i ; for ( i = 0 ; i <= 5 ; i++ ) { printf ( "\naddress = %u ", &num[i] ) ; printf ( "element = %d", num[i] ) ; } }

The output of this program would be: address = 65512 element = 24 address = 65514 element = 34 address = 65516 element = 12 address = 65518 element = 44

75

Page 82: C BOOKnewcopy

C Language 6-Arrays

address = 65520 element = 56 address = 65522 element = 17 This method of accessing array elements by using subscripted variables is already known to us.

This method has in fact been given here for easy comparison with the next method, which accesses the array elements using pointers. main( ) { int num[ ] = { 24, 34, 12, 44, 56, 17 } ; int i, *j ; j = &num[0] ; /* assign address of zeroth element */ for ( i = 0 ; i <= 5 ; i++ ) { printf ( "\naddress = %u ", j ) ; printf ( "element = %d", *j ) ; j++; /* increment pointer to point to next location */ } }

The output of this program would be: address = 65512 element = 24 address = 65514 element = 34 address = 65516 element = 12 address = 65518 element = 44 address = 65520 element = 56 address = 65522 element = 17

In this program, to begin with we have collected the base address of the array (address of the 0th element) in the variable j using the statement,

j = &num[0] ; /* assigns address 65512 to j */ When we are inside the loop for the first time, j contains the address 65512, and the value

at this address is 24. These are printed using the statements, printf ( "\n address = %u ", j ) ; printf ( "element = %d", *j ) On incrementing j it points to the next memory location of its type (that is location no.

65514). But location no. 65514 contains the second element of the array, therefore when the printf( ) statements are executed for the second time they print out the second element of the array and its address (i.e. 34 and 65514)... and so on till the last element of the array has been printed

6.3 TWO DIMENSIONAL ARRAYS

76

Page 83: C BOOKnewcopy

C Language 6-Arrays

It is also possible for arrays to have two or more dimensions. The two-dimensional array is also called a matrix. Here is a sample program that stores roll number and marks obtained by a student side by side in a matrix. main( )

{ int stud[4][2] ;

int i, j ; for ( i = 0 ; i <= 3 ; i++ ) { printf ( "\n Enter roll no. and marks" ) ; scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ; } for ( i = 0 ; i <= 3 ; i++ ) printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;

}There are two parts to the program—in the first part through a for loop we read in the values of roll no. and marks, whereas, in second part through another for loop we print out these values. Look at the scanf( ) statement used in the first for loop:scanf ( "%d %d", &stud[i][0],

&stud[i][1] ) ; In stud [i][0] and stud[i][1] the first subscript of the variable stud, is row number which

changes for every student. The second subscript tells which of the two columns are we talking about

The zeroth column which contains the roll no. or the first column which contains the marks.Remember the counting of rows and columns begin col. no. 0 col. no. 1 row no. 0 1234 56 row no. 1 1212 33 row no. 2 1434 80 row no. 3 1312 78

Thus, 1234 is stored in stud [0] [0], 56 is stored in stud [0] [1] and so on. The above arrangement highlights the fact that a two- dimensional array is nothing but a collection of a number of one- dimensional arrays placed one below the other.

6.3.1 Memory Map of a 2-Dimensional Array Let us reiterate the arrangement of array elements in a two-dimensional array of students, which contains roll nos in one column and the marks in the other. The array arrangement shown in Figure 8.4 is only conceptually true. This is because memory doesn’t contain rows and columns. In memory whether it is a one-dimensional or a two-

77

Page 84: C BOOKnewcopy

C Language 6-Arrays

dimensional array the array elements are stored in one continuous chain. The arrangement of array elements of a two-dimensional array in memory is shown below:

s[0][0] s[0][1]

s[1][0] s[1][1] s[2][0] s[2][1]

s[3][0] s[3][1]

1234 56 1212 33 1434 80 1312 78 65508 65510 65512 65512 65516 65518 65520 65522

6.3.2 Pointers and 2-Dimensional Arrays: It can treat parts of arrays as arrays. More specifically, each row of a two-dimensional

array can be thought of as a one-dimensional array. This is a very important fact if we wish to access array elements of a two-dimensional array using pointers. Thus, the declaration, int s [5] [2]; can be thought of as setting up an array of 5 elements, each of which is a one-dimensional array containing 2 integers. We refer to an element of a one-dimensional array using a single subscript.

Similarly, if we can imagine s to be a one-dimensional array then we can refer to its zeroth element as s [0], the next element as s[1] and so on. More specifically, s[0] gives the address of the zeroth one-dimensional array, s[1] gives the address of the first one-dimensional array and so on. This fact can be demonstrated by the following program.

main( ) { int s[4][2] = {

{ 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ; int i ;

for ( i = 0 ; i <= 3 ; i++ ) printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ; }

And here is the output... Address of 0th 1-D array = 65508 Address of 1th 1-D array = 65512 Address of 2th 1-D array = 65516 Address of 3th 1-D array = 65520

6.4 MULTIDIMENSIONAL ARRAY

78

Page 85: C BOOKnewcopy

C Language 6-Arrays

C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The general form of a multidimensional array is Type arrayname[s1][s2][s3]…[sm];

An example of initializing a three-dimensional array int arr[3][4][2] = { { { 2, 4 },{ 7, 8 },{ 3, 4 },{ 5, 6 } }, { { 7, 6 },{ 3, 4 },{ 5, 3 },{ 2, 3 } },

{ { 8, 9 },{ 7, 2 },{ 3, 4 },{ 5, 1 } }, } ;

A three-dimensional array can be thought of as an array of arrays of arrays. The outer array has three elements, each of which is a two-dimensional array of four one-dimensional arrays, each of which contains two integers. In the array declaration note how the commas have been given.

In memory the same array elements are stored linearly as shown in below

0th 2-D array 1st2-D array 2nd 2-D array2 4 7 8 3 4 5 6 7 3 4 5 3 2 3 8 9 7 2 3 4 5 5 1

65478 65494 65510

EXERCISE: What is output of following? (a) main()

{char s[ ]="man";int i;for(i=0;s[ i ];i++)printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}

79

7 6

8 9

2

4

1

2nd 2-D array

1st 2-D array

0th 2-D array 2 4

7 8

3 4

5 6

4

3

3

Page 86: C BOOKnewcopy

C Language 6-Arrays

(b) main()

{char s[ ]="man";int i;for(i=0;s[ i ];i++)printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}

(c) main()

{char s[ ]="man";int i;for(i=0;s[ i ];i++)printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}

(d) main()

{char s[ ]="man";int i;for(i=0;s[ i ];i++)printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);

(e) main( ) { int size ; scanf ( "%d", &size ) ; int arr[size] ; for ( i = 1 ; i <= size ; i++ ) { scanf ( "%d", arr[i] ) ; printf ( "%d", arr[i] ) ; } }

(f)

main( ) { int i, a = 2, b = 3 ; int arr[ 2 + 3 ] ;

80

Page 87: C BOOKnewcopy

C Language 6-Arrays

for ( i = 0 ; i < a+b ; i++ ) { scanf ( "%d", &arr[i] ) ; printf ( "\n%d", arr[i] ) ; } }

(g) main( ) { int array[26], i ; for ( i = 0 ; i <= 25 ; i++ ) { array[i] = 'A' + i ; printf ( "\n%d %c", array[i], array[i] ) ; } }

(h)

main( ) { int sub[50], i ; for ( i = 0 ; i <= 48 ; i++ ) ; { sub[i] = i ; printf ( "\n%d", sub[i] ) ; }

}

(i) main( ) { int a[ ] = { 2, 4, 6, 8, 10 } ; int i ; change ( a, 5 ) ; for ( i = 0 ; i <= 4 ; i++ ) printf( "\n%d", a[i] ) ; } change ( int *b, int n ) { int i ; for ( i = 0 ; i < n ; i++ ) *( b + i ) = *( b + i ) + 5 ;

81

Page 88: C BOOKnewcopy

C Language 6-Arrays

} (j)

main( ) { int a[5], i, b = 16 ; for ( i = 0 ; i < 5 ; i++ ) a[i] = 2 * i ; f ( a, b ) ; for ( i = 0 ; i < 5 ; i++ ) printf ( "\n%d", a[i] ) ; printf( "\n%d", b ) ; } f ( int *x, int y ) { int i ; for ( i = 0 ; i < 5 ; i++ ) *( x + i ) += 2 ; y += 2; }

PROGRAMS:1. Write a program to arrange 5 numbers in ascending order2. Write a program to find largest and smallest number out of 10 numbers using array3. Write a program to enter 15 numbers at a time and display them in reverse order4. Write a program to pick up the largest number from any 5 row by 5 column matrix.6. Write a program to add, subtract and multiply any two 6 x 6 matrices. 7. Write a program to sort all the elements of a 4 x 4 matrix8. Write a program to find average marks obtained by a class of 30 students in a test.9. Write a program to count the number of students belonging to each of following groups of marks 0-9, 10-19, 20-29….10010. Write a program to compute and print a multiplication table for numbers 1 to 511. Write a program to find if a square matrix is symmetric.

C INTERVIEW QUESTIONS1. What is the Array? How to define and declare them?

82

Page 89: C BOOKnewcopy

C Language 6-Arrays

Basically Array are the collection of same data type. It has common name and addressed as a group.Declaration of an Array:We have to declare Array also as a single data object.

int Array[10]; In this array of integers are created. Than first member in the array are addressed as Array [0] and last member has been declared as Array [9].Example:

int Array[MAX_SIZE];int n;for (n = 1; n <= MAX_SIZE; n++){ Array[n] = n;}

2. What are the characteristics of arrays in C?some main characteristics of arrays are given below:1. All entry in array should have same data type.2. Tables can store values of difference data types.

3. When does the compiler not implicitly generate the address of the first element of an array?When array name appears in an expression such as:1. Array as an operand of the size of operator.2. Array as an operand of & operator.3. Array as a string literal initialize for a character array.

4. Difference between arrays and pointers?Arrays automatically allocate space with fixed in size and location, but in pointers above are dynamic. Array is referred directly to the elements. But a pointer refers to address of the elements.

5. What is thrashing? Thrashing is that in which a computer takes the much type to load the data from

secondary memory to main memory or main memory to secondary memory as compared to execution of loaded data.

When we divide memory into pages than thrashing from this is called 'page thrashing'.

6. What is the difference b/n run time binding and compile time binding?

83

Page 90: C BOOKnewcopy

C Language 6-Arrays

When the address of functions are determined a run time then it is called run time or dynamic binding or late binding. While when the address of functions is determined in a compile time then it is called compile time or static binding or early binding.

In compile time binding, memory is allocated during compile time and in runtime binding, memory is allocated during running the program

7. How to differentiate local memory and global memory? Local and global memory allocation is applicable with Intel 80x86 CPUs. Some main difference b/n local and global variables are given below:1. Using local memory allocation we can access the data of the default memory segment, where as with global memory allocation we can access the default data, located outside the segment, usually in its own segment.

8. What is the difference between char *a and char a []? Char a[]; is an variable of array store elements of same data type from above the array a[]

store only characters can't store integers values. Char *a; is a pointer that stores address of the variable. Since pointer *a is a variable it

also have an address.

9. What is the difference between null array and an empty array? Due to difference in memory allocation, Null array has not allocated memory spaces.

Whereas Empty array has memory allocated spaces. In a Null array object are not assign to the variables, where as in an empty array object

are assign to the variables. Suppose, it we want to add some values in both array than in case of Null array first we

have to assign the object to the variables after that we have to add values. Where as in case of Empty array we have to only add the values.

When we declare int* arr[] as global it has only null that means it is an null array. When array has 0 elements is called empty array

10. What is static memory allocation and dynamic memory allocation?Information regarding static memory allocation and dynamic memory allocation are given below:

Static memory allocation:

The compiler allocates the required memory space for a declared variable. Using the address of operator, the reserved address is obtained and assigned to a pointer variable. Most of the declared variables have static memory; this way is called as static memory allocation.

In this memory is assign during compile time.

84

Page 91: C BOOKnewcopy

C Language 6-Arrays

Dynamic memory allocation:

For getting memory dynamically It uses functions such as malloc ( ) or calloc ( ).the values returned by these functions are assigned to pointer variables, this way is called as dynamic memory allocation.

In this memory is assigned during run timeWORKSHOP

1. Read 10 numbers and store in an array. Print the sum of those numbers.2. Read 10 numbers and store in an array – Print the numbers that are 100 and above.3. Read 10 numbers and store in an array. But do not allow duplicates.4. Read a 3 x 2 matrix, and print.5. Read roll no & five subject marks for 3 students and store in an array. Print the rollno and

minimum marks obtained by each student.6. Read roll no & five subject marks for 3 students and store in an array. Print the all student

totals of each subjects.7. Read rollno & five subject marks for 3 students and store in an array. Print the highest

mark among all students and subjects.8. Read 10 numbers and store an array. Then read a number, search for it in the array, and

print its position if found.9. Read 10 numbers and store in an array. Then read a numbers, search for it in the array,

and print no of times it is repeated. 10. Read roll no & percentage for 5 students ad store in an array. Then read a roll no, search

and print his percentage.

85

Page 92: C BOOKnewcopy

C Language 8-Structures

7. STRINGS7.1 What are Strings?

The group of integers can be stored in an integer array; similarly a group of characters can be stored in a character array. Character arrays are also called strings. A string constant is a one-dimensional array of characters terminated by a null (‘\0’). For example, char name[ ] = { 'A', D', V', 'E', 'T', 'E', 'C',’H’ '\0' } ;

Each character in the array occupies one byte of memory and the last character is always ‘\0’. ‘\0’ is called null character. Note that ‘\0’ and ‘0’ are not same. ASCII value of ‘\0’ is 0, whereas ASCII value of ‘0’ is 48. Note that the elements of the character array are stored in contiguous memory locations. The terminating null (‘\0’) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters.

Program to demonstrate printing of a string */ main( ) { char name[ ] = "Klinsman" ; int i = 0 ; while ( i <= 7 ) { printf ( "%c", name[i] ) ; i++; }}

And here is the output... Klinsman

We have initialized a character array, and then printed out the elements of this array within a while loop. Can we write the while loop without using the final value 7? We can; because we know that each character array always ends with a ‘\0’. Following program illustrates this.

main( ) { char name[ ] = "Klinsman" ;

int i = 0 ; while ( name[i] != `\0' ) {

printf ( "%c", name[i] ) ; i++ ;

86

Page 93: C BOOKnewcopy

C Language 8-Structures

} }

And here is the output... Klinsman

The %s used in printf( ) is a format specification for printing out a string. The same specification can be used to receive a string from the keyboardmain( ) {

char name[ ] = "Klinsman" ; printf ( "%s", name ) ;

}

7.2 Pointers and Strings If we want to store “Hello”. We may either store it in a string or we may ask the C

compiler to store it at some location in memory and assign the address of the string in a char pointer. This is shown below:

char str[ ] = "Hello" ; char *p = "Hello" ;

There is a subtle difference in usage of these two forms. For example, we cannot assign a string to another, whereas, we can assign a char pointer to another char pointer. This is shown in the following program.

main( ) { char str1[ ] = "Hello" ; char str2[10] ;

char *s = "Good Morning" ; char *q ; str2 = str1 ; /* error */ q = s ; /* works */

} Also, once a string has been defined it cannot be initialized to another set of characters.

Unlike strings, such an operation is perfectly valid with char pointers. main( )

{ char str1[ ] = "Hello" ; char *p = "Hello" ; str1 = "Bye"; /* error */

p = "Bye"; /* works */}

7.3 Standard Library String Functions

87

Page 94: C BOOKnewcopy

C Language 8-Structures

With every C compiler a large set of useful string handling library functions are provided lists the more commonly used functions along with their purpose.Function Use strlen Finds length of a string strlwr Converts a string to lowercase strupr Converts a string to uppercase strcat Appends one string at the end of another strncat Appends first n characters of a string at the end of anotherstrcpy Copies a string into another strncpy Copies first n characters of one string into another strcmp Compares two strings strncmp Compares first n characters of two strings

strcmpi Compares two strings without regard to case ("i" denotes that this function ignores case)stricmp Compares two strings without regard to case (identical to strcmpi) strnicmp Compares first n characters of two strings without regard to casestrdup Duplicates a string strchr Finds first occurrence of a given character in a string strrchr Finds last occurrence of a given character in a string strstr Finds first occurrence of a given string in another string strset Sets all characters of string to a given character strnset Sets first n characters of a string to a given character strrev Reverses string

This will also illustrate how the library functions in general handle strings. Let us study these functions one by one.

7.3.1 Strlen ( ) This function counts the number of characters present in a string. Its usage is illustrated in

the following program. main( )

{ char arr[ ] = "Coimbatore" ; int len1, len2 ;

len1 = strlen ( arr ) ; len2 = strlen ( "Gandhi puram”) ; printf ( "\nstring = %s length = %d", arr, len1 ) ; printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;

}

88

Page 95: C BOOKnewcopy

C Language 8-Structures

The output would be... string = Bamboozled length = 10 string = Humpty Dumpty length = 12

7.3.2 Strcpy ( ) This function copies the contents of one string into another. The base addresses of the

source and target strings should be supplied to this function. Here is an example of strcpy( ) in action...

main( ) { char source[ ] = "Sayonara" ; char target[20] ; strcpy ( target, source ) ; printf ( "\nsource string = %s", source ) ; printf ( "\ntarget string = %s", target ) ; }

And here is the output... source string = Sayonara target string = Sayonara

7.3.3 Strcat ( ) This function concatenates the source string at the end of the target string. For example,

“Bombay” and “Nagpur” on concatenation would result into a string “BombayNagpur”. Here is an example of strcat( ) at work. main( )

{ char source[ ] = "Folks!" ; char target[30] = "Hello" ; strcat ( target, source ) ; printf ( "\nsource string = %s", source ) ; printf ( "\ntarget string = %s", target ) ;

} And here is the output... source string = Folks! target string = HelloFolks!

Note that the target string has been made big enough to hold the final string. I leave it to you to develop your own xstrcat( ) on lines of xstrlen( ) and xstrcpy( ).

7.3.4 Strcmp ( )

89

Page 96: C BOOKnewcopy

C Language 8-Structures

This is a function which compares two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between the ASCII values of the first non-matching pairs of characters. Here is a program which puts strcmp( ) in action. main( )

{ char string1[ ] = "Jerry" ; char string2[ ] = "Ferry" ; int i, j, k ; i = strcmp ( string1, "Jerry" ) ; j = strcmp ( string1, string2 ) ; k = strcmp ( string1, "Jerry boy" ) ; printf ( "\n%d %d %d", i, j, k ) ;

} And here is the output... 0 4 -32

7.4 Two-Dimensional Array of CharactersIn the last chapter we saw several examples of 2-dimensional integer arrays. Let’s now

look at a similar entity, but one dealing with characters. Here’s the program asks you to type your name.

main( ) {

char masterlist[6][10] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ; int i, flag, a ; char yourname[10] ; printf ( "\nEnter your name " ) ; scanf ( "%s", yourname ) ; flag = 0; for ( i = 0 ; i <= 5 ; i++ ) { a = strcmp ( &masterlist[i][0], yourname ) ;

90

Page 97: C BOOKnewcopy

C Language 8-Structures

if ( a == 0 ) { printf ( "Welcome, you can enter the palace" ) ; flag = 1 ; break ; } } if ( flag == 0 ) printf ( "Sorry, you are a trespasser" ) ;

} And here is the output for two sample runs of this program... Enter your name dinesh Sorry, you are a trespasser Enter your name raman Welcome, you can enter the palace

Instead of initializing names, had these names been supplied from the keyboard, the program segment would have looked like this...

for( i = 0 ; i <= 5 ; i++ ) scanf ( "%s", &masterlist[i][0] ) ; While comparing the strings through strcmp( ), note that the addresses of the strings are

being passed to strcmp( ). As seen in the last section, if the two strings match, strcmp( ) would return a value 0, otherwise it would return a non-zero value.

7.5 Array of Pointers to StringsA pointer variable always contains an address. Therefore, if we construct an array of

pointers it would contain a number of addresses. Example program shows how the names can be stored in the array of pointers. char *names[ ] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ;

In this declaration names [ ] is an array of pointers. It contains base addresses of respective names.

91

Akshay\0 Ram\0 Srinivas\0

Page 98: C BOOKnewcopy

C Language 8-Structures

182 189 195

201 210 216

182 189 195 201 210 21665514 65516 65518 65520 65522 65524

That is, base address of “akshay” is stored in names[0], base address of “parag” is stored in names[1] and so on, let the next program illustrates,/* Exchange names using 2-D array of characters */

main( ) {

char names[ ][10] = {"akshay",

"parag", "raman", "srinivas", "gopal", "rajesh" } ; int i ; char t ; printf ( "\nOriginal: %s %s", &names[2][0], &names[3][0] ) ; for ( i = 0 ; i <= 9 ; i++ ) { t = names[2][i] ; names[2][i] = names[3][i] ; names[3][i] = t ; } printf ( "\nNew: %s %s", &names[2][0], &names[3][0] ) ;

} And here is the output... Original: raman srinivas New: srinivas raman Note that in this program to exchange the names we are required to exchange corresponding characters of the two names. In effect, 10 exchanges are needed to interchange two names.Let us see, if the number of exchanges can be reduced by using an array of pointers to strings. Here is the program...

main( )

92

Gopal\0 Rakesh\ Parag\0

Page 99: C BOOKnewcopy

C Language 8-Structures

{ char *names[ ] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ; char *temp ; printf ( "Original: %s %s", names[2], names[3] ) ; temp = names[2] ;

names[2] = names[3] ; names[3] = temp ; printf ( "\n New: %s %s", names[2], names[3] ) ;

} And here is the output... Original: raman srinivas New: srinivas raman

The output is same as the earlier program. In this program all that we are required to do is exchange the addresses (of the names) stored in the array of pointers, rather than the names themselves. Thus, by effecting just one exchange we are able to interchange names. This makes handling strings very convenient.

7.6 Limitation of Array of Pointers to Strings When we are using a two-dimensional array of characters we are at liberty to either

initialize the strings where we are declaring the array, or receive the strings using scanf( ) function. However, when we are using an array of pointers to strings we can initialize the strings at the place where we are declaring the array, but we cannot receive the strings from keyboard using scanf( ). Thus, the following program would never work out.

main( ) {

char *names[6] ; int i ; for ( i = 0 ; i <= 5 ; i++ ) { printf ( "\n Enter name " ) ; scanf ( "%s", names[i] ) ; }

93

Page 100: C BOOKnewcopy

C Language 8-Structures

} The program doesn’t work because; when we are declaring the array it is containing

garbage values. And it would be definitely wrong to send these garbage values to scanf( ) as the addresses where it should keep the strings received from the keyboard.

ExerciseWhat would be the output of the following programs? (a)

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

(b) main( ) { char s[ ] = "Get organised! learn C!!" ; printf ( "\n%s", &s[2] ) ; printf ( "\n%s", s ) ; printf ( "\n%s", &s ) ; printf ( "\n%c", s[2] ) ; }

(c) main( ) { char s[ ] = "No two viruses work similarly" ; int i = 0 ; while ( s[i] != 0 ) { printf ( "\n%c %c", s[i], *( s + i ) ) ; printf ( "\n%c %c", i[s], *( i + s ) ) ; i++ ; } }

(d)main( ) { char *str1 = "United" ;

94

Page 101: C BOOKnewcopy

C Language 8-Structures

char *str2 = "Front" ; char *str3 ; str3 = strcat ( str1, str2 ) ; printf ( "\n%s", str3 ) ; }

(e) main( ) {int arr[ ] = { ‘A’, ‘B’, ‘C’, ‘D’ } ; int i ; for ( i = 0 ; i <= 3 ; i++ ) printf ( "\n%d", arr[i] ) ; }

(f) main( ) { char arr[8] = "Rhombus" ; int i ; for ( i = 0 ; i <= 7 ; i++ ) printf ( "\n%d", *arr ) ; arr++ ; }

(g)main( ) { char str1[ ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ } ; char str2[ ] = "Hello" ; printf ( "\n%s", str1 ) ; printf ( "\n%s", str2 ) ; }

(h) main( ) { printf ( 5 + "Good Morning " ) ; }

Programs1. Write a c program to print the string from given character2. Write a c program to convert the string from lower case to upper case 3. Write a c program to counting different characters in a string using c program

95

Page 102: C BOOKnewcopy

C Language 8-Structures

4. Write a c program to concatenation of two strings 5. Write a c program to concatenation of two strings using pointer in 6. Write a c program which prints initial of any name7. How to reverse a string in c without using reverse function8. Write a c program to reverse a string using pointers9. Write a c program to String concatenation without using string functions10. Write a c program to compare two strings in c without using Strcmp 11. Write a c program for String copy without using strcpy in c 12. Write a c program to convert string into ASCII values in c programming language:

C interview questions1. What is the difference between String and Array?Array can hold group of element of the same type, and which allocates the memory for each element in the array, if we want we can obtain the particular value from an array by giving index value.Ex: int a[10];A variable holds the values of integer at max 10.String can hold any type of data, but it makes together we can't obtain the particular value of the string.String s="Pra12";

2. What is the difference between memcpy and strcpy? The key difference between memcpy and strcpy are given below:1. Memcpy is used to copy the NULL bytes even if size is not mentioned, where as strcpy is stopped copying when it encounters NULL bytes.2. Memcpy can copy null bytes also if the size of memory is given strcpy stops after the first null byte3. How to convert a string into integer? this program illustrates how to convert string into integer int s(char str[]){int n=0,m;for(int m=0;str[m]>='0' && str[m]<='9';m++)n=10*n+(str[m]-'0');if(mintf("Error String");return 0;}return n;}

96

Page 103: C BOOKnewcopy

C Language 8-Structures

4. Difference between strdup and strcpy? Both copy a string. strcpy wants a buffer to copy into. strdup allocates a buffer using malloc().Unlike strcpy(), strdup() is not specified by ANSI .

5. What is a volatile variable? We cannot modify the variable which is declared to volatile during execution of whole program.Example: Volatile int i = 10; value of i cannot be changed at run time.

6. What is the difference between the functions memmove () and memcpy ()?The arguments of memmove () can overlap in memory. The arguments of memcpy () cannot.

7. What is a file pointer?The pointer to a FILE data type is called as a stream pointer or a file pointer. A file pointer points to the block of information of the stream that had just been opened.

8. Out of fgets () and gets () which function is safe to use and why?fgets () is safer than gets(), because we can specify a maximum input length. Neither one is completely safe, because the compiler can’t prove that programmer won’t overflow the buffer he pass to fgets ().

9. How would you use the functions fseek(), freed(), fwrite() and ftell()?fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i.

fread(s,i1,i2,f) Enter i2 data items, each of size i1 bytes, from file f to string s. fwrite(s,i1,i2,f) send i2 data items, each of size i1 bytes from string s to file f. ftell(f) Return the current pointer position within file f. The data type returned for functions fread,fseek and fwrite is int and ftell is long int.

10. What is a stream?A stream is a source of data or destination of data that may be associated with a disk or other I/O device. The source stream provides data to a program and it is known as input stream. The destination stream receives the output from the program and is known as output stream.

WORKSHOP1. Write a program to concat the two strings2. Write a program to Reverse Strings3. Write a program for Comparing Strings4. Write a program for Palindrome

97

Page 104: C BOOKnewcopy

C Language 8-Structures

5. Write a program for vowel count

98

Page 105: C BOOKnewcopy

C Language 8-Structures

8. STRUCTURES8.1 What is structure?

A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. The general form of a structure is given below:struct <structure name> { structure element 1 ; structure element 2 ; structure element 3 ; ...... ......} ;

The keyword struct introduces a structure declaration, which is a list of declarations enclosed in braces. An optional name called a structure tag may follow the word struct (as with point here). The tag names this kind of structure, and can be used subsequently as shorthand for the part of the declaration in braces. The variables named in a structure are called members.

8.2 Declaring a Structure In our example program, the following statement declares the structure type: struct book

{ char name ; float price ; int pages ;

}This statement defines a new data type called struct book. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages.

Once the new structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as, struct book b1, b2, b3 ;

(1) Struct book {

Char name; float price ; int pages ;

}struct book b1, b2, b3 ;

99

Page 106: C BOOKnewcopy

C Language 8-Structures

(2) struct book {

char name ; float price ; int pages ;

} b1, b2, b3;

(3) struct book { char name[10] ; float price ; int pages ;

} ; struct book b1 = { "Basic", 130.00, 550 } ; struct book b2 = { "Physics", 150.80, 800 } ;

A structure contains a number of data types grouped together. These data types may or may not be of the same type. The following example illustrates the use of this data type.

struct book { char name ; float price ; int pages ; } ; struct book b1, b2, b3 ; main( ) { printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ; scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ; scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ; scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ; printf ( "\nAnd this is what you entered" ) ; printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ; printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ; printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ; }

And here is the output... Enter names, prices and no. of pages of 3 books A 100.00 354 C 256.50 682

100

Page 107: C BOOKnewcopy

C Language 8-Structures

F 233.70 512 And this is what you entered A 100.000000 354 C 256.500000 682 F 233.700000 512

This program demonstrates two fundamental aspects of structures: (a) declaration of a structure (b) accessing of structure elements

Note the following points while declaring a structure type: (a)The closing brace in the structure type declaration must be followed by a semicolon. (b)It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the ‘form’ of the structure. (c)Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined.

8.3 Structure Elements are StoredThe elements of a structure, they are always stored in contiguous memory locations. The following program would illustrate this: /* Memory map of structure elements */

main( ) { struct book { char name ; float price ; int pages ; } ; struct book b1 = { 'B', 130.00, 550 } ; printf ( "\nAddress of name = %u", &b1.name ) ;printf ( "\nAddress of price = %u", &b1.price ) ;printf ( "\nAddress of pages = %u", &b1.pages ) ; }

Here is the output of the program... Address of name = 65518 Address of price = 65519 Address of pages = 65523Actually the structure elements are stored in memory as shown in the Figure

101

Page 108: C BOOKnewcopy

C Language 8-Structures

b1.names b1.price b1.pages‘B’ 130.00 550

65518 65519 65523

8.4 Array of StructuresArray of Structures tells how individual elements of a structure variable are referenced. In

our sample program, to store data of 100 books we would be required to use 100 different structure variables from b1 to b100, which is definitely not very convenient. A better approach would be to use an array of structures. Following program shows how to use an array of structures./* Usage of an array of structures */

main( ) { struct book { char name ; float price ; int pages ; } ; struct book b[100] ; int i ; for ( i = 0 ; i <= 99 ; i++ ) { printf ( "\nEnter name, price and pages " ) ; scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ; } for ( i = 0 ; i <= 99 ; i++ ) printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ; } linkfloat( ) { float a = 0, *b ; b = &a ; /* cause emulator to be linked */ a = *b ; /* suppress the warning - variable not used */ }

8.5 Uses of StructuresThey can be used for a variety of purposes like:

Changing the size of the cursor Clearing the contents of the screen Placing the cursor at an appropriate position on screen

102

Page 109: C BOOKnewcopy

C Language 8-Structures

Drawing any graphics shape on the screen Receiving a key from the keyboard Checking the memory size of the computer Finding out the list of equipment attached to the computer Formatting a floppy Hiding a file from the directory Displaying the directory of a disk Sending the output to printer Interacting with the mouse

Exercise:(a)

main( ) { struct gospel

{ int num ; char mess1[50] ; char mess2[50] ; } m ; m.num = 1 ; strcpy ( m.mess1, "If all that you have is hammer" ) ; strcpy ( m.mess2, "Everything looks like a nail" ) ; /* assume that the strucure is located at address 1004 */ printf ( "\n%u %u %u", &m.num, m.mess1, m.mess2 ) ;

}(b)

struct virus { char signature[25] ; char status[20] ; int size ; } v[2] = { "Yankee Doodle", "Deadly", 1813,

"Dark Avenger", "Killer", 1795 } ;

(c)

103

Page 110: C BOOKnewcopy

C Language 8-Structures

main( ) { int i ; for ( i = 0 ; i <=1 ; i++ ) printf ( "\n%s %s", v.signature, v.status ) ; }

(d) struct s { char ch ; int i ; float a ; } ;

(e) main( ) { struct s var = { 'C', 100, 12.55 } ; f ( var ) ; g ( &var ) ; } f ( struct s v ) {

printf ( "\n%c %d %f", v -> ch, v -> i, v -> a ) ; }struct gospel {

int num ; char mess1[50] ; char mess2[50] ;

} m1 = { 2, "If you are driven by success", "make sure that it is a quality drive" } ; (f)

main( ) { struct gospel m2, m3 ;

m2 = m1 ; m3 = m2 ; printf ( "\n%d %s %s", m1.num, m2.mess1, m3.mess2 ) ;

104

Page 111: C BOOKnewcopy

C Language 8-Structures

}

Programs:1. Create a structure to specify data on students given below: Roll number, Name, Department, Course, year of joining Assume that there are not more than 450 students in the collage. (a) Write a function to print names of all students who joined in a particular year. (b) Write a function to print the data of a student whose roll number is given.2. Write a C program to implement average of students using Structure 2 Write a C program to implement the same using Structure with Array 3 Write a C program to implement the same using Structure with Function 4 Write a C program to Implement Structure the same using with Pointers

C interview questions1. What is a structure?Structure constitutes a super data type which represents several different data types in a single unit. A structure can be initialized if it is static or global.

2. What is a 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. Here a single area of memory contains values of different types at

3. Is that possible to pass a structure variable to a function/ If so, explain the detailed ways?yes it is possible to pass structure variable to a function

struct emp{int eno;};void disp(struct emp e){printf(e.eno);}void main(){struct emp e;e.eno=10;disp(e);}

4. What is the difference between a structure and a union?

105

Page 112: C BOOKnewcopy

C Language 8-Structures

A union is essentially a structure in which all of the fields overlay each other; you can only use one field at a time. (You can also cheat by writing to one field and reading from another, to inspect a type's bit patterns or interpret them differently, but that's obviously pretty machine-dependent.) The size of a union is the maximum of the sizes of its individual members, while the size of a structure is the sum of the sizes of its members. (In both cases, the size may be increased by padding.

5. 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.Array1-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.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.

6. What are the advantages of using Unions?Major advantages of using unions are:(i) Efficient use of memory as it does not demand memory space for its all members rather it require memory space for its largest member only.(ii) Same memory space can be interpreted differently for different members of the union. 

7. How are Structure passing and returning implemented by the complier?When structures are passed as argument to functions, the entire structure is typically pushed on the stack. To avoid this overhead many programmer often prefer to pass pointers to structure instead of actual structures. Structures are often returned from functions in a location pointed to by an extra, compiler-supported ‘hidden’ argument to the function.

8. What is the similarity between a Structure, Union and enumeration?All of them let the programmer to define new data type.

9. Can a Structure contain a Pointer to itself?Yes such structures are called self-referential structures.

106

Page 113: C BOOKnewcopy

C Language 8-Structures

10. Why can’t we compare structures?There is no single, good way for a compiler to implement structure comparison which is consistent with C’s low-level flavour. A simple byte-by-byte comparison could found on random bits present in unused “holes” in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures.

11. How are structure passing and returning implemented?When structures are passed as arguments to functions, the entire structure is typically pushed onthe stack, using as many words as are required. Some compilers merely pass a pointer to the structure, though they may have to make a local copy to preserve pass-by-value semantics.Structures are often returned from functions in a location pointed to by an extra, compiler-supplied “hidden” argument to the function. Some older compilers used a special, static location for structure returns, although this made structure-valued functions non-reentrant, which ANSI C disallows. 12. Can we initialize unions?ANSI Standard C allows an initialize for the first member of a union. There is no standard wayof initializing any other member (nor, under a pre-ANSI compiler, is there generally any way ofinitializing a union at all).

13. Why doesn’t struct x {…}; x the struct; work?C is not C++. Typedef names are not automatically generated for structure tags.

14. What are bit fields?Bit Field is used to make packed of data in a structure. Using bit fields we can communicate Disk drives and OS at a low level. Disk drives have many registers, if want to packed together in only one register we have to use bit fields.

15. What is the use of bit fields in a structure declaration?A bit field is a set of adjacent bits with a single implementation.Syntax:struct { unsugned int is_keyword : 1; unsigned is_extern :1; unsigned is_static : 1 ; } flags ;flags.is_extern = flags.is_static = 1 ;

WORKSHOP

107

Page 114: C BOOKnewcopy

C Language 8-Structures

1) Write a program to get the employee details and print it(Use Structures)

2) Write a program to get company details & employee details .Print the details(Use Nested Structures)

3) Write a program to get employee details and print it(Use Pointers as tag name)

108

Page 115: C BOOKnewcopy

C Language 9-File

9.FILE

9.1 INTRODUCTION

In this chapter we learn File Operations, using fopen, fwrite, and fread, fprintf, fscanf, fgetc and fputc.

For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed.

For example:

FILE *fp;

Fopen

To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode);In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected.

9.2 FILE OPERATIONS

There are different operations that can be carried out on a file.

a) Creation of a new fileb) Opening an existing filec) Reading from a filed) Writing to a filee) Moving to a specific location in a filef) Closing a file

Example//Reading content from a file# include<stdio.h># include<conio.h>void main (){

109

Page 116: C BOOKnewcopy

C Language 9-File

FILE *p;char ch;clrscr();fp=fopen(“pr.c”,”r”);while(1){ch = fgetc(fp);if(ch==EOF) break;printf(“%c”,ch);}fclose(fp);

}

fopen modesThe allowed modes for fopen are as follows:

r - open for readingw - open for writing (file need not exist)a - open for appending (file need not exist)r+ - open for reading and writing, start at beginningw+ - open for reading and writing (overwrite file)a+ - open for reading and writing (append if file exists)

Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer.

Here's a simple example of using fopen:

FILE *fp;fp= fopen("c:\\test.txt", "r");This code will open test.txt for reading in text mode.

FcloseWhen you're done working with a file, you should close it using the function

int fclose(FILE *a_file);

110

Page 117: C BOOKnewcopy

C Language 9-File

fclose returns zero if the file is closed successfully.

An example of fclose is

fclose(fp);

Reading and writing with fprintf, fscanf fputc, and fgetcTo work with text input and output, you use fprintf and fscanf, both of which are similar to printf and scanf except that you must pass the FILE pointer as first argument.

For example:

FILE *fp;

fp=fopen("c:\\test.txt", "w");

fprintf(fp, "Testing...\n");

It is also possible to read (or write) a single character at a time this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file:

int fgetc (FILE *fp);

Notice that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you're at the very end of the file, you can't get a character value in this case, fgetc will return "EOF", which is a constant that indicates that you've reached the end of the file. example using fgetc .

The fputc function allows you to write a character at a time

int fputc( int c, FILE *fp );

Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF.

String I/O in Files

Reading or writing strings of characters from and to files is as easy as reading and writing

111

Page 118: C BOOKnewcopy

C Language 9-File

individual characters.Here is a an example program that writes strings to a file using

the function fputs().

Example 1

It receives strings from keyboard and writes them to file

# include<stdio.h>

# include<stdlib.h>

# include<string.h>

void main()

{

FILE *fp;

char s[80];

fp=fopen(“pt.txt”,”w”);

if(fp==NULL)

{

puts(“Cannot open file”);

exit(1);

}

printf(“\n Enter a few lines of text\n”);

while(strlen(gets(s)>0)

{

fputs(s,fp);

fputs(“\n”,fp);

fclose(fp);

112

Page 119: C BOOKnewcopy

C Language 9-File

}

113

Page 120: C BOOKnewcopy

C Language 9-File

Example 2

This program reads & writes text in to the file according to the choice made by the user

#include<stdio.h>

#include<conio.h>

void main()

{

FILE *f1;

char c;

int op;

clrscr();

f1=fopen("abc.txt","a+");

while(5)

{

clrscr();

printf("\n Type 1 for reading and 2 for writing and 3 for exit \n");

scanf("%d",&op);

if(op==1)

{

rewind(f1);

printf("\n The file 'abc' has the matter of following\n ");

while(!feof(f1))

{

c=getc(f1);

putchar(c);

}

114

Page 121: C BOOKnewcopy

C Language 9-File

}

else if(op==2)

{

printf("\n Finish yr message with symbol 'n' \n");

while( (c=getchar())!=EOF)

putc(c,f1);

}

else

break;

getch();

}

fclose(f1);

getch();

}

9.3 RECORD I/O IN FILES

This program illustrates the use of structures for writing records of employees

# include<stdio.h># include<conio.h>void main(){FILE *fp;char another=‘Y;struct emp{char name[40];int age;float bs;};struct emp e;

115

Page 122: C BOOKnewcopy

C Language 9-File

fp=fopen(“EMPLOYEE.DAT“,”w”);

if( fp ==NULL)

{

puts(“Cannot open file”);

exit(1);

}

while(another==’Y’)

{

printf(“\n Enter Name, Age and Basic salary:”);

scanf(“%s %d %f”,e.name,&e.age,&e.bs);

fprintf(fp,”%s %d %f \n”,e.name,e.age,e.bs);

printf(“Add another record”Y/N”);

fflush(stdin);

another =getche();

}

fclose(fp);

}

}

WORKSHOP

1.Write a program to write Content in to a file

2.Write a program to Read & Write Content to a file

3.Write a program which writes content to a file using structures

116

Page 123: C BOOKnewcopy

C Language Solution

SOLUTION

SOLUTION SET-1

//1)Read a bill no : print its next 2 bill numbers.

# include<stdio.h>

# include<conio.h>

void main()

{

int billno,n1,n2;

clrscr();

printf("\n Enter The Bill No:: \n");

scanf("%d",&billno);

n1=billno;

n2=n1+1;

printf("\n The Next Two Bill Nos Are %d \t %d::",n1,n2);

getch();

}

//2) Read two nos : Swap them and print

# include<stdio.h>

# include<conio.h>

void main()

{

int a,b,temp;

clrscr();

printf("\n Enter The A and B values\n");

117

Page 124: C BOOKnewcopy

C Language Solution

scanf("%d",&a);

scanf("%d",&b);

temp=a;

a=b;

b=temp;

printf("\n The A& B Values After Swapping Are :: %d \t %d\n",a,b);

getch();

}

//3)Read miles: Print in Kilometers

# include<stdio.h>

# include<conio.h>

void main()

{

float m,km;

clrscr();

printf("Enter The Miles !!!\n");

scanf("%d",&m);

km=m*1.6;

printf("Distance In Terms of KILOMETRES %d\n",km);

getch();

}

//4) Given total months, find out the no of years and months.

# include<stdio.h>

# include<conio.h>

118

Page 125: C BOOKnewcopy

C Language Solution

void main()

{

int tmon,yrs,mn;

clrscr();

printf("\n Enter The Total Months\n");

scanf("%d",&tmon);

yrs=tmon/12;

mn=tmon%12;

printf("\n The No. Of Yrs is %d No: of Months is %d\n",yrs,mn);

getch();

}

//5)Given year and months, find out the months.

# include<stdio.h>

# include<conio.h>

void main()

{

int yr,mn;

clrscr();

printf("\n Enter The No: Of Yrs \n");

scanf("%d",&yr);

printf("\n Enter The No: Of Months \n");

scanf("%d",&mn);

119

Page 126: C BOOKnewcopy

C Language Solution

m=(yr*30)+mn;

printf("\n The Total No:of Months Is %d\n",m);

getch();

}

# include<stdio.h>

# include<conio.h>

// 6) Given opening stock, purchase qty and sales qty find out the stock of the item.

void main()

{

int opstk,pur,salesqty,sthand;

clrscr();

printf("Enter The Opening Stock!!!\n");

scanf("%d",&opstk);

printf("Enter The Purchase Quantity \n");

scanf("%d",&pur);

printf("Enter The Sales Quantity \n");

scanf("%d",&salesqty);

sthand =(opstk+pur)-salesqty;

printf("The Present Stock Is %d\n",sthand);

getch();

}

//7) Given annual premium and no of years, calculate the total amount paid.

#include<stdio.h>

#include<conio.h>

void main()

120

Page 127: C BOOKnewcopy

C Language Solution

{

long int anprem,totno,tamtpaid;

clrscr();

printf("Enter The AnnualPremium Amount\n");

scanf("%ld",&anprem);

printf("Enter The Total No of Years \n");

scanf("%ld",&totno);

tamtpaid =anprem*totno;

printf("The Total Amount After Years %ld\n",tamtpaid);

getch();

}

//8) Given basic salary and no of days absent, find the gross salary. Add DA 40%. Deduct Rs.300 for insurance. Print the net salary payable.

#include<stdio.h>

# include<conio.h>

void main()

{

float bs,da,ins,wd,na,m,days,pd,daamt,insamt=300,pds;

int totsal,per_day_sal;

clrscr();

printf("\n\n Enter The Basic Salary !!!!\n");

scanf("%f",&bs);

da =0.4;

printf("Enter The No. Of Days Absent\n");

121

Page 128: C BOOKnewcopy

C Language Solution

scanf("%f",&na);

printf("Enter The No Of Month\n");

scanf("%f",&m);

if(m==1 || m==3 || m == 5 || m==7 || m==9 || m==11)

days =31;

else if(m==2 || m==4 || m==6|| m==8)

days =30;

else

days =28;

wd=days-na;

pds=bs/days;

per_day_sal=pds*wd;

daamt=da*bs;

totsal=(daamt+per_day_sal)-insamt;

printf("\nThe TOTAL SALARY IS %d\n",totsal);

getch();

}

//9.Given the Rate per Dozen, and no of items purchased, calculate the purchase value.

# include<stdio.h>

# include<conio.h>

void main()

{

int ratedz,purqtydz,tot;

122

Page 129: C BOOKnewcopy

C Language Solution

clrscr();

printf("\n Enter The Rate per Dozen \n");

scanf("%d",ratedz);

printf("\n Enter The Purchase Quantity \n");

scanf("%d",purqtydz);

tot=(ratedz*purqtydz);

printf("\n The TOTAL IS %d\n",tot);

getch();

}

//10) Given years and months print the total no of days.(Assume 30 days/month,365 days/year)

# include<stdio.h>

# include<conio.h>

void main()

{

int yr,mn,totdays;

clrscr();

printf("\n Enter The Years \n");

scanf("%d",&yr);

printf("\n Enter The Months \n");

scanf("d",&mn);

totdays =(yr*12)+(mn*30) ;

printf("\n The Total No: Of Days Is %d\n",totdays);

getch();

}

123

Page 130: C BOOKnewcopy

C Language Solution

SOLUTION SET-2

//1) Read length & breath: print whether it is square or a rectangular.

# include<stdio.h>

# include<conio.h>

void main()

{

int len,br;

clrscr();

printf("\n Enter The Length and Breadth \n");

scanf("%d",&len);

scanf("%d",&br);

if(len==br)

printf("\n It's a Square \n");

else

printf("\n It's a Rectangle\n");

getch();

}

//2) Read 3 nos; Count the negative numbers and print.

# include<stdio.h>

# include<conio.h>

//Negative no count:

void main()

{

int a[3],countneg=0;

124

Page 131: C BOOKnewcopy

C Language Solution

clrscr();

printf("\n Enter The Number\n");

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

{

scanf("%d",&a[i]);

if(a[i]<0)

{

printf("It's a Negative Number\n");

countneg=countneg+1;

}

}

printf("\n The Count Of Negetaive Number is %d\n",countneg);

getch();

}

//3)Read an applicants age; print whether his age is between 22 nad 28 or not.

# include<stdio.h>

# include<conio.h>

void main()

{

int age;

clrscr();

printf("\n Enter The Age \n");

scanf("%d",&age);

if(age>=22 && age <=28)

printf("\n Age Is between 22 and 28\n");

125

Page 132: C BOOKnewcopy

C Language Solution

getch();

}

//4)Read a character; print if it is a vowel or not.

# include<stdio.h>

# include<conio.h>

void main()

{

char c;

clrscr();

printf("\n Enter The Character\n");

scanf("%c",&c);

if(c=='a'|| c=='e'|| c=='i'|| c=='o'|| c== 'u')

{

printf("It's a Vowel \n");

}

else

printf("\n It's Not Vowel \n");

getch();

}

SOLUTION SET-3

//1) Read a no; print if it is a zero, positive or negative number.

# include<stdio.h>

# include<conio.h>

126

Page 133: C BOOKnewcopy

C Language Solution

void main()

{

int a;

clrscr();

printf("\n Enter The Number\n");

scanf("%d",&a);

if(a==0)

printf("It's Value Is Zero\n");

else if(a>0)

printf("It's a Positive Number\n");

else if(a<0)

printf("It's a Negative Number\n");

getch();

}

//2) Read two nos ; print if both are equal. Otherwise print the biggest.

# include<stdio.h>

# include<conio.h>

void main()

{

int a,b;

clrscr();

printf("\n Enter The A and B Values\n");

scanf("%d %d",&a,&b);

if(a>b)

printf("\n A is Greater \n");

127

Page 134: C BOOKnewcopy

C Language Solution

else

printf("\n B is Greater\n");

getch();

}

//3)Read three nos; print the biggest number.

# include<stdio.h>

# include<conio.h>

void main()

{

int a,b,c;

clrscr();

printf("\n Enter The A and B and C Values\n");

scanf("%d %d %d",&a,&b,&c);

if(a>b && a>c)

printf("\n A is Greater Than B and C\n");

else if(b>a && b>c)

printf("\n B is Greater Than A and C \n");

else

printf("\n C is Greater\n");

getch();

}

//4)Read an option 1 or 2; if 1 Read a no; Print if it is an odd or even number; If 2 Read a no; print if it is a positive or negative number.

# include<stdio.h>

# include<conio.h>

128

Page 135: C BOOKnewcopy

C Language Solution

void main()

{

int a;

clrscr();

printf("\n Enter The Number\n");

scanf("%d",&a);

if(a==0)

printf("It's Value Is Zero\n");

else if(a>0)

printf("It's a Positive Number\n");

else if(a<0)

printf("It's a Negative Number\n");

getch();

}

SOLUTION SET-4

1)Read a weekday number[1 to 7]; Print weekdays name.

# include<stdio.h>

# include<conio.h>

void main()

{

int ch,w;

clrscr();

printf("\n Enter The Choice 1-7 to represent Week day Names\n");

129

Page 136: C BOOKnewcopy

C Language Solution

scanf("%d",&ch);

if(ch==1)

printf("\n Sunday \n");

else if(ch==1)

printf("\n monday\n");

else if(ch==2)

printf("\n Tuesday\n");

else if(ch==3)

printf("\n Wednesday\n");

else if(ch==4)

printf("\n Thursday \n");

else if(ch==5)

printf("\n Friday \n");

else if (ch==6)

printf("\n Saturday\n");

getch();

}

//2)Read a percentage of marks; Grade it. A grade :80-100%, B grade:60-70%, C grade:40-59%, D grade:0-39%.

# include<stdio.h>

# include<conio.h>

130

Page 137: C BOOKnewcopy

C Language Solution

void main()

{

int sub1,sub2,sub3,per;

clrscr();

printf("\n Enter The Subject1 MarK !!!\n");

scanf("%d",&sub1);

printf("\n Enter The Subject2 Mark !!!\n");

scanf("%d",&sub2);

printf("\n Enter The Subject3 Mark !!!\n");

scanf("%d",&sub3);

per=((sub1+sub2+sub3)/3);

if(per>=80 && per<=100)

printf("\n Grade A...\n");

else if(per>=60 && per<=70)

printf("\n Grade B... \n");

else if(per>=40 && per<=69)

printf("\n C Grade \n");

else if(per>=0 && per<=39)

printf("\n D grade\n");

getch();

}

//3)Read a purchase value; Calculate and print the discount amount based on following condition.

No discount for purchase less than Rs.1000.00.

2% Discount for purchase upto Rs.2,000.00

131

Page 138: C BOOKnewcopy

C Language Solution

5% Discount for purchase upto Rs.5,000.00

8% Discount for purchase above Rs.5000.00

# include<stdio.h>

# include <conio.h>

void main()

{

int pur;

float disamt;

clrscr();

printf("\n Enter The Purchase Value \n");

scanf("%d",&pur);

if(pur<1000)

printf("\n No Discount !!!!\n");

else if (pur>=1000 && pur <2000)

{

disamt =(pur*0.02);

printf("\n The Discount Amount Is %f\n",disamt);

}

else if (pur>=2000 && pur<5000)

{

disamt =(pur*0.05);

printf("\n The Discount Amount Is %f\n",disamt);

}

else if (pur>=5000)

{

132

Page 139: C BOOKnewcopy

C Language Solution

disamt =(pur*0.08);

printf("\n The Discount Amount Is %f\n",disamt);

}

getch();

}

SOLUTION SET-5

//1) Read a month number[1 to 12]; print month name.

# include<stdio.h>

# include<conio.h>

void main()

{

int ch;

clrscr();

printf("\n Enter The Month Number \n");

scanf("%d",&ch);

switch(ch)

{

case 1:

printf("\n January !!!\n");

break;

case 2:

printf("\n Febrary !!!\n");

break;

case 3:

133

Page 140: C BOOKnewcopy

C Language Solution

printf("\n March !!!\n");

break;

case 4:

printf("\n April \n");

break;

case 5:

printf("\n May \n");

break;

case 6:

printf("\n June \n");

break;

case 7:

printf("\n July \n");

break;

case 8:

printf("\n August \n");

break;

case 9:

printf("\n September \n");

break;

case 10:

printf("\n October \n");

break;

case 11:

printf("\n November \n");

134

Page 141: C BOOKnewcopy

C Language Solution

break;

case 12:

printf("\n December \n");

break;

}

getch();

}

//2) Read a month number[1 to 12]; print if it is first/second/third/fourth quarter.

# include<stdio.h>

# include<conio.h>

void main()

{

int ch;

clrscr();

printf("\n Enter The Month Number \n");

scanf("%d",&ch);

switch(ch)

{

case 1:

case 2:

case 3:

{

printf("\n First Quarter !!!\n");

break;

}

135

Page 142: C BOOKnewcopy

C Language Solution

case 4:

case 5:

case 6:

{

printf("\n Second Quarter !!!\n");

break;

}

case 7:

case 8:

case 9:

{

printf("\n Third Quarter !!!\n");

break;

}

case 10:

case 11:

case 12:

{

printf("\n Fourth Quarter!!! \n");

break;

}

}

getch();

}

136

Page 143: C BOOKnewcopy

C Language Solution

//3Read two nos; Display the following menu for selection. Then read the option, and do the appropriate action.

f. Addg. Multiplyh. Dividei. Do Nothingj. Choose Your Option[1-4]:________

# include<stdio.h>

# include<conio.h>

void main()

{

int ch,a,b,c;

clrscr();

printf ("\n Enter The Choice 1->ADD 2->Multiply 3->Divide 4->Nothing !!!\n");

scanf("%d",&ch);

printf("\n Enter The A & B Values \n");

scanf("%d %d" ,&a,&b);

switch(ch)

{

case 1:

{

c=a+b;

printf("\n The Addition Performed !!! %d\n",c);

break;

}

case 2:

{

137

Page 144: C BOOKnewcopy

C Language Solution

c=a-b;

printf("\n The Subtraction Performed !!! %d\n",c);

break;

}

case 3:

{

c=a*b;

printf("\n The Multiplication Performed !!! %d\n",c);

break;

}

default:

printf("\n Nothing !!!\n");

}

getch();

}

SOLUTION SET-6

1)Print the number series: 5,10,15,20,25,30,35,40

# include<stdio.h>

# include<conio.h>

void main()

{

int i;

clrscr();

138

Page 145: C BOOKnewcopy

C Language Solution

for(i=0;i<=40;)

{

i=i+5;

printf(" \t %d",i);

}

getch();

}

//2)Print the number series: 8,12,16,20,24,28,32,36,40 …

# include <stdio.h>

# include<conio.h>

void main()

{

int i,j=1;

clrscr();

for(i=2;i<=64;)

{

i=i+2;

j=2*i;

if(j==64)

break;

printf("\t%d",j);

}

getch();

}

139

Page 146: C BOOKnewcopy

C Language Solution

//3 Print the number of series: 100,90,80,70,60,50,40,30,20,10,0

# include <stdio.h>

# include<conio.h>

void main()

{

int i;

clrscr();

for(i=100;i>=0;)

{

printf("\t%d",i);

i=i-10;

}

getch();

}

SOLUTION SET-7

1) Generate the series : 30 24 18 12 6

# include <stdio.h>

# include<conio.h>

//30 24 18 12 6

void main()

{

int i;

clrscr();

for(i=30;i>=6;)

140

Page 147: C BOOKnewcopy

C Language Solution

{

printf("\t %d",i);

i=i-6;

}

getch();

}

//2)Generate Series 15 20 25 30 35 40 45

# include<stdio.h>

# include<conio.h>

// 15 20 25 30 35 40

void main()

{

int i;

clrscr();

for(i=15;i<=40;)

{

printf("\t %d",i);

i=i+5;

}

getch();

}

//3)Read 10 numbers and print the sum & average.

#include<stdio.h>

#include<conio.h>

void main()

141

Page 148: C BOOKnewcopy

C Language Solution

{

int i,a[10],n,sum=0;

float avg;

clrscr();

printf("Enter The No\n");

scanf("%d",&n);

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

{

scanf("%d",&a[i]);

sum=sum+a[i];

}

avg=sum/n;

printf("The Average Is %f\n",avg);

getch();

}

SOLUTION SET-8

//1)Read 10 numbers and print the total even nos and total odd number.

# include<stdio.h>

# include<conio.h>

void main()

{

int num[9],i,counte=0,countod=0;

clrscr();

printf("\n Enter The 10 Numbers\n");

142

Page 149: C BOOKnewcopy

C Language Solution

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

{

scanf("%d",&num[i]);

}

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

{

if( ( (num[i])%2 )==0)

{

counte=counte+1;

}

else if( (num[i])%2 !=0 )

{

countod=countod+1;

}

}

printf("The Count Of Odd Numbers Is %d\n",countod);

printf("The Count Of EVEN Numbers Is %d\n",counte);

getch();

}

//2)Read 2 nos, print the biggest no.

# include<stdio.h>

# include<conio.h>

void main()

{

int a,b;

143

Page 150: C BOOKnewcopy

C Language Solution

clrscr();

printf("\n Enter The A and B Values\n");

scanf("%d %d",&a,&b);

if(a==b)

printf("\n Both Values Are Equal\n");

else if(a>b)

printf("\n A is Greater \n");

else

printf("\n B is Greater\n");

getch();

}

SOLUTION SET-9

//1)Print the series:2,4,8,16,32,….; stop after printing 200 nos.

# include<stdio.h>

# include<conio.h>

//2 4 16 32 ...1024

void main()

{

long int i;

clrscr();

for(i=2;i<=1024;)

{

144

Page 151: C BOOKnewcopy

C Language Solution

printf("\t %ld",i);

i=i*2;

if(i==200)

break;

}

getch();

}

//2)Print the series:2,4,8,16,32,…; Stop when reached above 100.

# include<stdio.h>

# include<conio.h>

//2 4 16 32 ...1024

void main()

{

long int i;

clrscr();

for(i=2;i<=1024;)

{

printf("\t %ld",i);

i=i*2;

if(i==100)

break;

}

getch();

}

145

Page 152: C BOOKnewcopy

C Language Solution

//3)Read a no; print if it is prime no or not.

//Write a program to find the prime numbers

#include<stdio.h>

# include<conio.h>

void main()

{

int n, c = 2;

printf("Enter a number to check if it is prime\n");

scanf("%d",&n);

for ( c = 2 ; c <= n - 1 ; c++ )

{

if ( n%c == 0 )

{

printf("%d is not prime.\n", n);

break;

}

}

if ( c == n )

printf("%d is prime.\n", n);

getch();

}

SOLUTION SET-10

//1)Print the series: 2,4,6,8,…20

# include<stdio.h>

146

Page 153: C BOOKnewcopy

C Language Solution

# include<conio.h>

//2 4 6 8 20

void main()

{

int i;

clrscr();

for(i=2;i<=20;)

{

printf("\t %d",i);

i=i+2;

}

getch();

}

//2) Print the series: 1,10,100,1000,10000

# include<stdio.h>

# include<conio.h>

//1 10 100 1000 10,000

void main()

{

long int i;

clrscr();

for(i=1;i<=10000;)

{

printf("\t %ld",i);

147

Page 154: C BOOKnewcopy

C Language Solution

i=i*10;

}

getch();

}

SOLUTION SET-11

//1) Read ‘n’ number: Ask the user [1/2] before proceeding to next number. Finall print the sum of all read number.

#include<stdio.h>

# include<conio.h>

void main()

{

int i,sum=0,a[15],n,num;

int w ;

clrscr();

printf("\n Enter The No of Items To be Entered ");

scanf("%d",&n);

printf("\n Enter 1 to continue or 2 to exit\n");

scanf("%d",&w);

if(w==1)

{

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

{

scanf("%d",&num);

sum=sum+num;

148

Page 155: C BOOKnewcopy

C Language Solution

}

}

else if(w==2)

exit(0);

printf("\n Sum Is %d\n",sum);

getch();

}

//2) Display the following menu for selection. Then read the option, and do the appropriate action.

a. Addb. Multiplyc. Stopd. Choose your option[1-3]

# include<stdio.h>

# include<conio.h>

void main()

{

int ch,a,b,c;

clrscr();

printf ("\n Enter The Choice 1->ADD 2->Multiply 3->Stop !!!\n");

scanf("%d",&ch);

printf("\n Enter The A & B Values \n");

scanf("%d %d" ,&a,&b);

switch(ch)

{

149

Page 156: C BOOKnewcopy

C Language Solution

case 1:

{

c=a+b;

printf("\n The Addition Performed !!! %d\n",c);

break;

}

case 2:

{

c=a*b;

printf("\n The Subtraction Performed !!! %d\n",c);

break;

}

case 3:

{

exit(0);

}

default:

printf("\n Nothing !!!\n");

}

getch();

}

SOLUTION SET-12

//1)Read ‘n’ numbers; stop reading when zero is input. Finally print the sum of all read numbers.

# include<stdio.h>

150

Page 157: C BOOKnewcopy

C Language Solution

# include<conio.h>

//read 10 num sum of read numbers stop if zero is input

void main()

{

int a[10],i,sum=0;

clrscr();

printf("\n Enter The Number's One By One\n");

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

{

scanf("%d",&a[i]);

if(a[i]==0)

break;

sum=sum+a[i];

}

printf("\n The Total Is %d\n",sum);

getch();

}

//2)Read age and print; But repeat to ask until an age not lesser that 25 is entered.

# include<stdio.h>

# include<conio.h>

//read age until lesser than 25

void main()

{

int a[10],i;

clrscr();

151

Page 158: C BOOKnewcopy

C Language Solution

printf ("\n Enter The Age ->10 Values\n");

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

{

scanf("%d",&a[i]);

if(a[i]<25)

{

printf("\n The Age Is Below 25\n");

break ;

}

else

printf("The Age Is %d\n",a[i]);

}

getch();

}

SOLUTION SET -13

//1)Print the series 10,9,8,7….1

# include<stdio.h>

# include<conio.h>

//Generate series 10 9 8 7 ...1

void main()

{

int i;

clrscr();

for(i=10;i>=1;)

152

Page 159: C BOOKnewcopy

C Language Solution

{

printf("\t %d",i);

i=i-1;

}

getch();

}

//2) Print the multiplication table for 2,3, &4

# include <stdio.h>

# include <conio.h>

void main()

{

int r, c, y, n ;

clrscr() ;

r = 1 ;

printf("Enter a number up to which you want tables: ");

scanf("%d", &n);

printf("\n\nThe multiplication table for first %d numbers is :\n\n", n) ;

do

{

c = 1 ;

do

{

y = r * c ;

printf("%5d", y) ;

153

Page 160: C BOOKnewcopy

C Language Solution

c = c + 1 ;

} while(c <= 10) ;

printf("\n\n") ;

r = r + 1 ;

} while(r <= n) ;

getch() ;

}

SOLUTION SET-14

//1)Read 10 numbers and store in an array. Print the sum of those numbers.

# include<stdio.h>

# include<conio.h>

//read 10 num, sum of read numbers

void main()

{

int a[10],i,sum=0;

clrscr();

printf("\n Enter The Number's One By One\n");

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

{

scanf("%d",&a[i]);

sum=sum+a[i];

}

printf("\n The Total Is %d\n",sum);

getch();

154

Page 161: C BOOKnewcopy

C Language Solution

}

//2) Read 10 numbers and store in an array – Print the numbers that are 100 and above.

# include<stdio.h>

# include<conio.h>

void main()

{

int a[10];

int i,j;

clrscr();

printf("\n Enter The Values One By One \n");

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

{

scanf("%d",&a[i]);

}

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

for(j=i+1;j<=10;j++)

if(a[i]>=100)

{

printf("\n Element Greater Than 100 is %d \n",a[i]);

break;

}

getch();

}

155

Page 162: C BOOKnewcopy

C Language Solution

//3) Read 10 numbers and store in an array. But do not allow duplicates.

# include<stdio.h>

# include<conio.h>

void main()

{

int a[10];

int i,j;

clrscr();

printf("\n Enter The Values One By One \n");

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

{

scanf("%d",&a[i]);

}

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

{

for(j=i+1;j<=10;j++)

{

if(a[i]==a[j])

{

printf("\n DUPLICATE VALUES ARE PRESENT \n");

break;

}

}

}

getch();

156

Page 163: C BOOKnewcopy

C Language Solution

}

//4) Read 5 numbers and store in an array. Check if any number is similar.Don’t Repeat

similar Nos

# include<stdio.h>

# include<conio.h>

//Do Not Allow Repeated Values

void main()

{

int a[10];

int i,j;

clrscr();

printf("\n Enter The Values One By One \n");

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

{

scanf("%d",&a[i]);

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

{

if(a[i]==a[j-1])

{

i=i-1;

printf("\n DO NOT REPEAT SIMILAR NUMBER\n");

break;

}

}

157

Page 164: C BOOKnewcopy

C Language Solution

}

getch();

}

SOLUTION SET-15

//1)Read a 3 x 2 matrix, and print.

# include<stdio.h>

# include<conio.h>

void main()

{

int a[3][2];

int i,j;

clrscr();

//Reading

printf("\n Enter Array Elements One By One \n");

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

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

scanf("%d\n",&a[i][j]);

//Printing

printf("\n The Array Elements Are ::\n");

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

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

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

getch();

158

Page 165: C BOOKnewcopy

C Language Solution

}

//2)Read roll no & five subject marks for 3 students and store in an array. Print the rollno and minimum marks obtained by each student.

# include<stdio.h>

# include<conio.h>

// MIN PERCENTAGE MARK

void main()

{

int i,phy,chem,mat,tot,temp;

float avg,std[10],j;

clrscr();

for( i=1;i<=5;i++)

{

printf("\n Enter The Marks for Student No :: %d\n",i);

scanf("%d",&phy);

scanf("%d",&chem);

scanf("%d",&mat);

tot=phy+chem+mat ;

avg=tot/3;

std[i]=avg;

}

printf("\n Enter Student Roll No For Which Percentage Is To Be Displayed...\n");

scanf("%f",&j);

159

Page 166: C BOOKnewcopy

C Language Solution

printf("\n PERCENTAGE TO BE DISPLAYED %f\n",std[j]);

// MIN MARKS DISPLAYED

for(i=1;i<=5;i++)

for(j=i+1;j<=5;j++)

if(std[i]<std[j])

{

temp=std[i];

std[i]=std[j];

std[j]=temp;

}

printf("\n THE MIN PERCENTAGE IS %f \n",std[5]);

getch();

}

//3)Read roll no & five subject marks for 3 students and store in an array. Print the all student totals of each subjects.

# include<stdio.h>

# include<conio.h>

// TOTAL MARK

void main()

{

int i,phy,chem,mat,tot,temp;

int avg,std[10],j;

160

Page 167: C BOOKnewcopy

C Language Solution

clrscr();

for( i=1;i<=5;i++)

{

printf("\n Enter The Marks for 5 Student No NumberWise :: %d\n",i);

scanf("%d",&phy);

scanf("%d",&chem);

scanf("%d",&mat);

tot=phy+chem+mat ;

std[i]=tot;

}

printf("\n Enter Student RollNo For Which Total Is To Be Displayed...\n");

scanf("%d",&j);

printf("\n TOTAL OF ROLLNO %d IS %d\n",j,std[j]);

getch();

}

//4)Read rollno & five subject marks for 3 students and store in an array. Print the highest mark among all students and subjects.

# include<stdio.h>

# include<conio.h>

// MAX MARK

void main()

{

int i,phy,chem,mat,tot,temp;

float avg,std[10],j;

161

Page 168: C BOOKnewcopy

C Language Solution

clrscr();

for( i=1;i<=5;i++)

{

printf("\n Enter The Marks for Student No :: %d\n",i);

scanf("%d",&phy);

scanf("%d",&chem);

scanf("%d",&mat);

tot=phy+chem+mat ;

avg=tot/3;

std[i]=avg;

}

printf("\n Enter Student Roll No For Which Percentage Is To Be Displayed...\n");

scanf("%f",&j);

printf("\n PERCENTAGE TO BE DISPLAYED %f\n",std[j]);

// MAX MARKS DISPLAYED

for(i=1;i<=5;i++)

for(j=i+1;j<=5;j++)

if(std[i]>std[j])

{

temp=std[i];

std[i]=std[j];

std[j]=temp;

}

printf("\n THE MAX PERCENTAGE IS %f \n",std[5]);

getch();

162

Page 169: C BOOKnewcopy

C Language Solution

}

SOLUTION SET-16

//1)Read 10 numbers and store an array. Then read a number, search for it in the array, and print its position if found.

# include<stdio.h>

# include<conio.h>

//Find position

void main()

{

int a[10],num;

int i,j;

clrscr();

printf("\n Enter The Values One By One \n");

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

{

scanf("%d",&a[i]);

}

printf("\n Enter The Number\n");

scanf("%d",&num);

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

{

if(a[i]==num)

{

printf("\n FOUND THE NUMBER \n");

printf("\n THE POSITION IS %d \n",i);

163

Page 170: C BOOKnewcopy

C Language Solution

}

}

getch();

}

//2)Read 10 numbers and store in an array. Then read a numbers, search for it in the array, and print no of times it is repeated.

# include<stdio.h>

# include<conio.h>

// No of times values are Repeated

void main()

{

int a[10],count=0;

int i,j;

clrscr();

printf("\n Enter The Values One By One \n");

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

{

scanf("%d",&a[i]);

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

{

if(a[i]==a[j-1])

{

i=i-1;

164

Page 171: C BOOKnewcopy

C Language Solution

printf("\n REPEATED NUMBER\n");

count =count+1;

break;

}

}

}

printf("The No of Times Values Are Repeated %d\n",count);

getch();

}

//3)Read roll no & percentage for 5 students ad store in an array. Then read a roll no, search and print his percentage.

# include<stdio.h>

# include<conio.h>

// MAX MARK

void main()

{

int i,phy,chem,mat,tot,temp;

float avg,std[10],j;

clrscr();

for( i=1;i<=5;i++)

{

printf("\n Enter The Marks for Student No :: %d\n",i);

scanf("%d",&phy);

scanf("%d",&chem);

165

Page 172: C BOOKnewcopy

C Language Solution

scanf("%d",&mat);

tot=phy+chem+mat ;

avg=tot/3;

std[i]=avg;

}

printf("\n Enter Student Roll No For Which Percentage Is To Be Displayed...\n");

scanf("%f",&j);

printf("\n Percentage Displayed for the above Mentioned RollNo Is %f\n",std[j]);

getch();

}

SOLUTION SET-17

//1) Write a program to concat the two strings

# include<stdio.h>

# include<conio.h>

# include<string.h>

void main()

{

char s1[45],s2[45];

clrscr();

printf(“Enter The String1\n”);

scanf(“%s”,s1);

printf(“Enter The String2\n”);

scanf(“%s”,s2);

strcat(s1,s2);

166

Page 173: C BOOKnewcopy

C Language Solution

printf(“The Output String Is %s\n”,s1);

getch();

}

//2) Write a program to Reverse Strings

# include <stdio.h>

# include<conio.h>

# include<string.h>

void main()

{

char s1[45];

clrscr();

printf(“Enter The String\n”);

scanf(“%s”,s1);

strrev(s1);

printf(“The Reversed String %s\n”,s1);

getch();

//3)Write a program for Comparing Strings

# include<stdio.h>

# include<conio.h>

# include<string.h>

void main()

{

char s1[45],s2[45];

clrscr();

167

Page 174: C BOOKnewcopy

C Language Solution

printf(“Enter The String1\n”);

scanf(“%s”,s1);

printf(“Enter The String2\n”);

scanf(“%s”,s2);

if(strcmp(s1,s2)==0)

printf(“The Two Strings Are Equal\n”)

else

printf(“Two Strings Are Not Equal\n”);

getch();

}

//4)Write a program for Palindrome

# include<stdio.h>

# include<conio.h>

# include<string.h>

void main()

{

char s1[45],s2[45];

clrscr();

printf(“Enter The String1\n”);

scanf(“%s”,s1);

strcpy(s2,s1);

strrev(s2);

if(strcmp(s1,s2)==0)

printf(“It’s a palindrome\n”);

else

168

Page 175: C BOOKnewcopy

C Language Solution

printf(“It’s Not a palindrome..\n”);

getch();

}

//5)Write a program for vowel count

# include<stdio.h>

# include<conio.h>

void main()

{

char c;

int count=0;

clrscr();

printf("\n Enter The Character\n");

scanf("%c",&c);

if(c=='a'|| c=='e'|| c=='i'|| c=='o'|| c== 'u')

{

printf("It's a Vowel \n");

count = count+1;

}

else

printf("\n It's Not Vowel \n");

printf("\n The count of vowel is %d\n",count);

getch();

}

169

Page 176: C BOOKnewcopy

C Language Solution

SOLUTION SET-18

//1) Create a function that accepts a number and prints the square and cube values.

//Square & cube

# include<stdio.h>

# include<conio.h>

int num,rr,n2,rr1,k1;

void main()

{

clrscr();

printf("\n Enter The Number\n");

scanf("%d",&num);

rr=cube(num);

rr1=sq(num);

printf("\n The Cube Of Given Number Is %d\n",rr);

printf("\n The Square Of Given Number Is %d\n",rr1);

getch();

}

int cube(int n1)

{

n2=(n1*n1*n1);

return n2;

}

int sq(int k)

{

170

Page 177: C BOOKnewcopy

C Language Solution

k1=(k*k);

return k1;

}

//2) Create a function that accepts a number prints cube value.

//cube

# include<stdio.h>

# include<conio.h>

int num,rr,n2;

void main()

{

clrscr();

printf("\n Enter The Number\n");

scanf("%d",&num);

rr=cube(num);

printf("\n The Cube Of Given Number Is %d\n",rr);

getch();

}

int cube(int n1)

{

n2=(n1*n1*n1);

return n2;

}

171

Page 178: C BOOKnewcopy

C Language Solution

//3)Create a function that accepts a number and returns its factorial.

# include<stdio.h>

# include<conio.h>

//Program To Find the Factorial of a number

int num,i,k,fact=1,n1,rr;

void main()

{

clrscr();

printf("Enter The Number For Which Factorial is to b Calculated\n");

scanf("%d",&num);

rr=funct(num);

printf("The Factorial Of Given No is %d\n",rr);

getch();

}

int funct(int nr)

{

n1=nr;

for(k=1;k<=num;k++)

{

fact = fact *n1;

n1=n1-1;

}

172

Page 179: C BOOKnewcopy

C Language Solution

return fact;

}

4)Create a function that accepts a number and returns whether it is a prime number or not.

#include<stdio.h>

# include<conio.h>

void main()

{

clrscr();

primnum();

getch();

}

primnum()

{

int n, c = 2;

printf("Enter a number to check if it is prime\n");

scanf("%d",&n);

for ( c = 2 ; c <= n - 1 ; c++ )

{

if ( n%c == 0 )

{

printf("%d is not prime.\n", n);

break;

}

}

173

Page 180: C BOOKnewcopy

C Language Solution

if ( c == n )

printf("%d is prime.\n", n);

return 0;

}

SOLUTION SET-19

//1) Write a program to get the employee details and print it(Use Structures)

# include<stdio.h>

# include<conio.h>

struct emp

{

char name[45];

int no;

float sal;

};

struct emp e1;

void main()

{

clrscr();

printf("Enter The Name :\n");

scanf("%s",e1.name);

printf("Enter The No:\n");

scanf("%d",&e1.no);

printf("Enter The Salary :\n");

scanf("%f",&e1.sal);

174

Page 181: C BOOKnewcopy

C Language Solution

disp();

getch();

}

disp()

{

printf("The Name Is : %s\n",e1.name);

printf("The No Is : %d\n",e1.no);

printf("The Salary Is : %f\n",e1.sal);

return 0;

}

//2) Write a program to get company details & employee details .Print the details(Use Nested Structures)

# include<stdio.h>

# include<conio.h>

struct comp

{

char name[45];

char addr[45];

struct sales

{

char spname[45];

int no ;

float sal;

}s1;

175

Page 182: C BOOKnewcopy

C Language Solution

}c1;

void main()

{

clrscr();

printf("Enter The Company Name :\n");

scanf("%s",c1.name);

printf("Enter The Company Address:\n");

scanf("%s",c1.addr);

printf("Enter The Sales Person Name :\n");

scanf("%s",c1.s1.spname);

printf("Enter The Sales Person No:\n");

scanf("%d",&c1.s1.no);

printf("Enter The Salary:\n");

scanf("%f",&c1.s1.sal);

disp();

getch();

}

disp()

{

printf("The Company Name Is :%s\n",c1.name);

printf("The Company Address: %s\n",c1.addr);

printf("The Sales Person Name : %s\n",c1.s1.spname);

printf("The Sales Person No: %d\n",c1.s1.no);

printf("The Salary: %f\n",c1.s1.sal);

176

Page 183: C BOOKnewcopy

C Language Solution

return 0;

}

//3) Write a program to get employee details and print it(Use Pointers as tag name)

#include<stdio.h>

# include<conio.h>

struct emp

{

int no;

float sal;

};

struct emp *e1;

void main()

{

clrscr();

printf("Enter The No:\n");

fflush(stdin);

scanf("%d",&e1->no);

printf("Enter The Salary :\n");

scanf("%f",&e1->sal);

disp();

getch();

}

disp()

177

Page 184: C BOOKnewcopy

C Language Solution

{

printf("The No Is : %d\n",e1->no);

printf("The Salary Is : %f\n",e1->sal);

return 0;

}

SOLUTION SET-20

// 1.Write a program to write content in to a file

# include<stdio.h>

# include<stdlib.h>

# include<string.h>

void main()

{

FILE *fp;

Char s[80];

fp=fopen(“pt.txt”,”w”);

if(fp==NULL)

{

puts(“Cannot open file”);

exit(1);

}

printf(“\n Enter a few lines of text\n”);

while(strlen(gets(s)>0)

{

fputs(s,fp);

178

Page 185: C BOOKnewcopy

C Language Solution

fputs(“\n”,fp);

fclose(fp);

}

//2) .Write a program to Read & Write content to a file

#include<stdio.h>

#include<conio.h>

void main()

{

FILE *f1;

char c;

int op;

clrscr();

f1=fopen("abc.txt","a+");

while(5)

{

clrscr();

printf("\n Type 1 for reading and 2 for writing and 3 for exit \n");

scanf("%d",&op);

if(op==1)

{

rewind(f1);

printf("\n The file 'abc' has the matter of following\n ");

while(!feof(f1))

{

c=getc(f1);

179

Page 186: C BOOKnewcopy

C Language Solution

putchar(c);

}

}

else if(op==2)

{

printf("\n Finish yr message with symbol 'n' \n");

while( (c=getchar())!=EOF)

putc(c,f1);

}

else

break;

getch();

}

fclose(f1);

getch();

}

//3) Write a program which writes content to a file using structures

//Structure & Files

# include<stdio.h>

# include<conio.h>

void main()

{

FILE *fp;

char another=‘Y;

struct emp

180

Page 187: C BOOKnewcopy

C Language Solution

{

char name[40];

int age;

float bs;

};

struct emp e;

fp=fopen(“EMPLOYEE.DAT“,”w”);

if( fp ==NULL)

{

puts(“Cannot open file”);

exit(1);

}

while(another==’Y’)

{

printf(“\n Enter Name, Age and Basic salary:”);

scanf(“%s %d %f”,e.name,&e.age,&e.bs);

fprintf(fp,”%s %d %f \n”,e.name,e.age,e.bs);

printf(“Add another record”Y/N”);

fflush(stdin);

another =getche();

}

fclose(fp);

}

}

181

Page 188: C BOOKnewcopy

C Language Solution

182