0% found this document useful (0 votes)
836 views187 pages

C BOOKnew

This document provides an overview of constants, variables, and data types in the C programming language. It discusses C character sets and tokens, including keywords, identifiers, and various types of constants. The main data types in C are described, including integer, floating point, and character types. Rules for defining variables and declaring variable types are presented. Storage classes like automatic, external, static, and register are also introduced. The chapter concludes with an exercise on the covered topics.

Uploaded by

Mani Kandan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
836 views187 pages

C BOOKnew

This document provides an overview of constants, variables, and data types in the C programming language. It discusses C character sets and tokens, including keywords, identifiers, and various types of constants. The main data types in C are described, including integer, floating point, and character types. Rules for defining variables and declaring variable types are presented. Storage classes like automatic, external, static, and register are also introduced. The chapter concludes with an exercise on the covered topics.

Uploaded by

Mani Kandan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 187

EMBEDDED C

EMBEDDED C
CONTENTS Ch.No. Index Page No.
1 1 1 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 4 5 5 6 6 6 7 7 7 11 16 16 16 16 17 17

1. Constants, Variables Data Types 1.1 Introduction 1.2 Character Set 1.2.1 Letters 1.2.2 Digits 1.2.3 Special Characters 1.2.4 White Spaces 1.3 C Tokens 1.3.1 Keywords 1.3.2 Identifiers 1.3.3 Constants 1.3.3.1 Integer Constants 1.3.3.2 Real Constants 1.3.3.3 Single Character Constants 1.3.3.4 String Constants 1.3.3.5 Backslash Character Constants 1.4 Variables 1.4.1 Definition 1.4.2 Rules for Defining Variables 1.5 Data Types 1.5.1 Introduction 1.5.2 Integer Types 1.5.3 Floating Point Types 1.5.4 Character Types 1.6 Declaration of Variables 1.6.1 User-Defined Type Declaration 1.7 Storage Class Exercise Workshop 2. Operators 2.1 Introduction 2.2 Operators of C 2.2.1 Arithmetic Operators 2.2.1.1 Integer Arithmetic 2.2.1.2 Real Arithmetic

2.2.1.3 Mixed-Mode Arithmetic 2.2.2 Relational Operators 2.2.3 Logical Operators 2.2.4 Assignment Operators 2.2.5 Increment and Decrement Operators 2.2.6 Conditional Operator 2.2.7 Bitwise Operators 2.2.8 Special Operators 2.2.8.1 The Comma Operator 2.2.8.2 The Size of Operator 2.2.9 Hierarchy of Operations Exercise Workshop

17 18 18 19 19 20 20 22 23 23 23 24

3. Control Structure Introduction 3.2 Branching The If Statement 3.2.1 Simple If Statement 3.2.2 The If....Else Statement 3.2.3 Nested If...Else Statement 3.2.4 The Else If Ladder 3.3 Switch Case Statement 3.4 The Conditional Operator 3.5 Go to Statement Workshop 4. Looping 4.1 4.2 4.3 4.4 4.5 4.6 Exercise Workshop

27 27 28 28 30 31 32 34 37 37

Introduction The While Statement The Do...While Statement The For Loop The Break Statement The Continue Statement

41 41 41 42 43 44 45 48

5. Pointers and Functions 5.1 Introduction 5.2 Passing value between functions

53 53 56

5.3 Calling Convention 5.4 Advanced Features of Functions 5.5 An Introduction to Pointers Exercise workshop 6. Arrays 6.1 Introduction 6.2 One Dimensional Array 6.2.1 Declaration of Arrays 6.2.2 Initialization of Arrays 6.2.3 Function and Arrays 6.3 Two-Dimensional Arrays 6.4 Multidimensional Array Exercise Workshop 7. Strings 7.1 Introduction 7.2 Pointers and Strings 7.3 Standard Library functions and Strings 7.4 Two dimensional array of characters 7.5 Array of pointers to strings 7.6 Limitations of Array of pointers to strings Exercise Workshop 8. Structures 8.1 Introduction 8.2 Declaring with structures 8.3 Structure elements are stored 8.4 Array of structures 8.5 Uses of Structures Exercise

57 57 58 65

73 73 73 73 73 74 75 80 83

87 87 88 89 91 92 94 97

100 100 100 102 103 103 104

Workshop 9.Files 9.1Introduction 9.2File operation 110 110

9.3Record I/O in Files


Workshop

C Language

1-constants, variables & data types

Chapter 1 1. CONSTANTS, VARIABLES&DATA TYPES


1.1 INTRODUCTION
A 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 SET


C characters are grouped into the following categories. 1. Letters 2. Digits 3. Special Characters 4. White Spaces Note: The compiler ignores white spaces unless they are a part of a string constant. 1.2.1 Letters Uppercase A.Z Lowercase a..z 1.2.2 Digits All 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

C Language

1-constants, variables & data types

1.2.4 White Spaces Blank Space Horizontal Tab Carriage Return New Line Form Feed

1.3 C TOKENS
In 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

C Language

1-constants, variables & data types

auto
float switch typedef short signed size of static

double break case extern unsigned void volatile while

int else enum union continue default do struct

char long register const for goto if case

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 CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a Program. CONSTANTS

Numeric constants

Character constants

Integer Constants

Real Single constants

character constants

String constants

1.3.3.1 Integer Constants


An integer constant refers to a sequence of digits; there are three types integers, namely, decimal, octal, and hexa decimal.

C Language

1-constants, variables & data types

Decimal Constant Decimal integer consist of set of digits, 0 through 9, preceded by an optional + or - sign E.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 Constant An 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 Constants


A single character constants contains a single character enclosed within a pair of Single quote marks. E.g.: 5 X ;

1.3.3.4 String Constants


A 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 ?.!

C Language

1-constants, variables & data types

1.3.3.5 Backslash Character Constants 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 VARIABLES
1.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 TYPES 1.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.

C Language

1-constants, variables & data types

PRIMARY DATA TYPES

INT

CHAR

FLOAT

int short int long int

unsigned int unsigned short int unsigned long int

signed char unsigner char

float double long double

1.5.2 Integer Types


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

1.5.3 Floating Point Types


Type float double long double Size(bits) 32 64 80 Range 3.4E-38 to 3.4E+38 1.7E-308 to 1.7E+308 3.4E-4932to 1.1E+4932

1.5.4 Character Types


Type char unsigned char Size (bits) 8 8
6

Range -128 to 127 0 to 255

C Language

1-constants, variables & data types

1.6 DECLARATION OF VARIABLES


The syntax is Data-type v1, v2..vn; E.g.: 1.int count; 2. double ratio, total;

1.7 STORAGE CLASSES


Its 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 Default initial value Scope Life Memory An unpredictable value, which is often called a garbage value Local to the block in which the variable is defined 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 unpredictable Note: The keyword for this storage class is auto, and not automatic.
7

C Language

1-constants, variables & data types

1.7.2 STATIC VARIABLES:


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 Scope Life Zero Local to the block in which the variable is defined 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... 0 static 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.

C Language

1-constants, variables & data types

main() { increment(); increment(); increment(); } increment(); { auto int i=0; printf(%d,i); i=i+1; } Output 1 1 1

main() { increment(); increment(); increment(); } increment(); { static int i=0; printf(%d,i); i=i+1; } Output 1 2 3

In the above example, when variable i is auto, each time increment ( ) is called it is reinitialized 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 Default initial value Scope Life

Memory Zero Global As long as the program execution doesnt 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:
9

C Language

1-constants, variables & data types

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; 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 = 0 As 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 machines 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 Default initial value

CPU register Garbage value

10

C Language

1-constants, variables & data types

Scope Life

Local to the block in which the variable is defined. 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


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 dont 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 dont 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. teamsvictory Plot # 3 2015_DDay

11

C Language

1-constants, variables & data types

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 ) ; } main( ) { int p, q ; printf ( "Enter values of p and q" ) ; scanf ( " %d %d ", &p,&q ) ; printf ( "p = %d q =%d", p, q ) ; }

(c)

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 vector 2.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.
12

C Language

1-constants, variables & data types

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 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 class 1) Persistent storage of a variable retains the latest value 2) The value is globally available Disadvantages of external storage class 1) The storage for an external variable exists even when the variable is not needed 2) The side effect may produce surprising output 3) Modification of the program is difficult 4) Generality of a program is affected.

6. Can static variables be declared in a header file? You cant 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

13

C Language

1-constants, variables & data types

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 */ 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.
14

C Language

1-constants, variables & data types

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

15

C Language

2-Operators

2. OPERATORS
2.1 INTRODUCTION In 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 C
C 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 operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment and Decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators

2.2.1 ARITHMETIC OPERATORS


The 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.

16

C Language

2-Operators

2.2.1.1 Integer Arithmetic


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 = -2 14 % -3 = 2

2.2.1.2 Real Arithmetic


An 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 Arithmetic


When 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

17

C Language

2-Operators

(c)

main( ) { 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 OPERATORS


Comparisons 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 OPERATORS


C has the following three logical operators. && (logical AND)
18

C Language

2-Operators

|| (logical OR) ! (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 OPERATORS


The 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 statement o x=x+(y+1);

Shorthand assignment operator:


Statementwith shorthand operator a + =1 a-=1 a *= n + 1 a /= n + 1 a %= b Statement with simple assignment operator a=a+1 a=a1 a = a * (n+1) a = a / (n+1) 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 OPERATORS
C 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
19

C Language

2-Operators

Programs for increment/Decrement operation (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 + --a printf (\n%d%d, y, a); getch(); }

The output is of y=24, a=7

2.2.6 CONDITIONAL OPERATOR


A 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; else x = b;

2.2.7 BITWISE OPERATORS


Operator & | ^ << >> ~ Program for Bitwise operator:
20

Meaning Bitwise AND Bitwise OR Bitwise XOR Shift left Shift right Ones complement

C Language

2-Operators

(a)

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

} } And here is the output of the above program... Decimal 0 is same as binary 00001111 Ones 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.
21

C Language

2-Operators

main( ) { 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 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 (e)

(d)

2.2.8 SPECIAL OPERATORS


C 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 Operator


22

C Language

2-Operators

The 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. 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 Operations


Priority 1st Operators * % / Description Multiplication,modular division,division

2nd

+-

Addition,subtraction

3rd

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: +

23

C Language

2-Operators

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: (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. Rajeshs 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
24

C Language

2-Operators

expressions and then simple expressions. Additionally, most of todays 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 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/7 If 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%7 The 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?


25

C Language

2-Operators

let, x = 1. Then answer will be. main() { int x=1,y; y = x++ + ++x; printf("/n%d",y); } 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 constructor Two major differences between copy constructor and assignment are: (i) Copy constructor doesnt 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

26

C Language

3-The Control Structure

3. The Control Structure


We 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 Branching
Branching 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 programs flow; the programs 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,

27

C Language

3-The Control Structure

General Form:
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 statement ii) if....else statement iii) Nested if......else statement iv) else if ladder

3.2.1 Simple If Statement:


The general form of a simple if statement is as follows,

General form
if (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,

28

C Language

3-The Control Structure

Flowchart

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"); }

29

C Language

3-The Control Structure

3.2.2 The If....Else Statement:


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

General Form
if (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");
30

C Language

3-The Control Structure

scanf(%d,&number); 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,

31

C Language

3-The Control Structure

Flowchart:

Sample code: Write a program to find the biggest of three numbers


if(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

32

C Language

3-The Control Structure

General Form

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:

33

C Language

3-The Control Structure

Sample Code:
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); else printf(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; }

34

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
35

C Language

3-The Control Structure

I am in default If you want that only case 2 should get executed, we didnt 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" ) ;
36

C Language

3-The Control Structure

break ; 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 doesnt 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 is


Expression 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; else average = 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.
37

C Language

3-The Control Structure

First let us understand the goto statement, its syntax and functionality. 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 jump Program: 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 Construct 1) 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.

38

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.00 5% Discount for purchase upto Rs.5,000.00 8% 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. Add b. Multiply c. Divide d. Do Nothing e. Choose Your Option[1-4]:________

39

C Language

3-The Control Structure

40

C Language

4.Looping

4. Looping
4.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:

Test expression

true

code

false

41

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:

code true

Test expression

false 42

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:

43

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:
start

code

break code

end

Sample Code:
44

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:
start

code

continue

code

end

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

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... 12 21

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( )
46

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


47

C Language

4.Looping

printf ( "\n%d", i ) ; i++; } (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++; }

PROGRAMS 1. 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 statement 4. Write a c program to find the largest of three numbers using nested if 5. 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 marks 7. 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)
48

C Language

4.Looping

9. Write a program to produce the following output: 1 1 2 1 2 3 1 2 3 4 1 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 continue 12. 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.

49

C Language

4.Looping

6. How many times the below loop will run main() { int i; i = 0; do { --i; printf (%d,i); i++; } while (i >= 0) } Output:Infinite Explanation: 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 Bye Explanation : 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.

50

C Language

4.Looping

WORKSHOP For loop construct: Number series printing 1. Print the number series:0,5,10,15,20,25,30,35,40 2. Print the number series: 2,4,8,16,32,64 3. Print the number of series: 100,90,80,70,60,50,40,30,20,10,0 Loop Construct: Summation 1. Generate Series : 30 24 18 12 6 2. Generate Series : 15 20 25 30 35 40 45 3. Read 10 numbers and print the sum & average. Loop Construct : Conditional 1. 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 count 1. Print the series: 2,4,6,8,20 2. Print the series: 1,10,100,1000,10000 3. Print the sum of the series: 1,2,4,8,16,32,1024 While Loops: Undetermined loopGet 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. Add 4. Multiply 5. Stop 6. Choose your option[1-3]

51

C Language

4.Looping

While loops: Undetermined loopDetect 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. Do-while loops 1. Print the series 10,9,8,7.1 2. Read n number; Ask the user [1/2] before proceeding to next number. Finally print the sum of all read numbers.

52

C Language

5-Functions and pointers

5. Functions and pointers


5.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 its complex. 5.1.1. Let us now look at a simple C function, actually, we will be looking at two thingsa function that calls or activates the function and the function itself. main( ) { message( ) ; printf ( "\n hai ) ; } message( ) { printf ( "\n hello..." ) ; } And heres 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" ) ; }
53

C Language

5-Functions and pointers

argentina( ) { 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 Lets 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
54

C Language

5-Functions and pointers

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. 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" ) ; }
55

C Language

5-Functions and pointers

However, it is advisable to define the functions in the same order in which they are called. This makes the program easier to understand. 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 Functions


Consider 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 ) ; }
56

C Language

5-Functions and pointers

calsum ( x, y, z ) { int x, y, z ; 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 Cs 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

57

C Language

5-Functions and pointers

square of a number using a function. The following program segment illustrates how to make square( ) capable of returning a float value. main( ) { 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 Reference


This 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 Pointers


In 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 Cs 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.
58

C Language

5-Functions and pointers

i
5

variable name value location

65524

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, is 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 Cs 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
59

C Language

5-Functions and pointers

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 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
3 5 65524

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 pointers address. The following example should make this point clear. main( ) {
60

C Language

5-Functions and pointers

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 ) ; 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
3 5 65524

k
65522

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

61

C Language

5-Functions and pointers

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 learnthe two types of function callscall 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 (b) Sending the addresses of the arguments

5.5.2.1 Call by value


In 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.

62

C Language

5-Functions and pointers

Example 1: main( ) { int a = 10, b = 20 ; swapr ( &a, &b ) ; printf ( "\na = %d b = %d", a, b ) ; } swapr( int *x, int *y ) { 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); }

63

C Language

5-Functions and pointers

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); } 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 ) ; }
64

C Language

5-Functions and pointers

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 3 Factorial value = 6 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) else f=x*rec(x-1); return(f); } rec(int x) { int f; if(x==1) return(1) else f=x*rec(x-1); return(f); }

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

EXERCISE
What 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 ) ; }
65

C Language

5-Functions and pointers

(b) int *call(); void main(){ int *ptr; ptr=call(); clrscr(); printf("%d",*ptr); } 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);
66

C Language

5-Functions and pointers

getch(); } (f) main( ) { void slogan( ) ; int c = 5 ; c = slogan( ) ; printf ( "\n%d", c ) ; } 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; }
67

C Language

5-Functions and pointers

(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 ) ; } (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.

68

C Language

5-Functions and pointers

C INTERVIEW QUESTIONS
1. 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: 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 address Garbage value 3. 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.

69

C Language

5-Functions and pointers

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? 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 integers e) 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
70

C Language

5-Functions and pointers

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 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 ().

71

C Language

5-Functions and pointers

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; } WORKSHOP 1. 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.

72

C Language

6-Arrays

6. ARRAYS
6.1 INTRODUCTION
An 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] ; for ( i = 0 ; i <= 29 ; i++ ) {

/* array declaration */

73

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 heres 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++ )
74

C Language

6-Arrays

disp ( &marks[i] ) ; } disp ( int *n ) { printf ( "%d ", *n ) ; } And heres 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
75

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
76

C Language

6-Arrays

address = 65518 element = 44 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

77

C Language

6-Arrays

6.3 TWO DIMENSIONAL 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 programin 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 1234 1212 1434 1312 col. no. 1 56 33 80 78

row no. 0 row no. 1 row no. 2 row no. 3

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.

78

C Language

6-Arrays

The array arrangement shown in Figure 8.4 is only conceptually true. This is because memory doesnt contain rows and columns. In memory whether it is a one-dimensional or a twodimensional 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 onedimensional 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 onedimensional 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

79

C Language

6-Arrays

6.4 MULTIDIMENSIONAL ARRAY


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.
2nd 2-D array 1 2-D array 0 2-D array
th st

8 7 6 4 3 3

9 2 4 1

2 7 3 5

4 8 4 6

In memory the same array elements are stored linearly as shown in below 0th 2-D array 2 4 7 8 65478 1st2-D array 6 7 3 4 5 65494 2nd 2-D array 9 7 2 3 4 5 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]);
80

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( ) {
81

C Language

6-Arrays

int i, a = 2, b = 3 ; int arr[ 2 + 3 ] ; 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 ) {
82

C Language

6-Arrays

int i ; for ( i = 0 ; i < n ; i++ ) *( b + i ) = *( b + i ) + 5 ; } (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 order 2. Write a program to find largest and smallest number out of 10 numbers using array 3. Write a program to enter 15 numbers at a time and display them in reverse order 4. 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 matrix 8. 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.100 10. Write a program to compute and print a multiplication table for numbers 1 to 5 11. Write a program to find if a square matrix is symmetric.

83

C Language

6-Arrays

C INTERVIEW QUESTIONS 1. What is the Array? How to define and declare them? 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'.

84

C Language

6-Arrays

6. What is the difference b/n run time binding and compile time binding? 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.
85

C Language

6-Arrays

In this memory is assign during compile time. 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 time WORKSHOP 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.

86

C Language

8-Structures

7. STRINGS
7.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] ) ;
87

C Language

8-Structures

i++ ; } } 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 keyboard main( ) { 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 */}

88

C Language

8-Structures

7.3 Standard Library String Functions


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 another strcpy 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 stricmp strnicmp strdup strchr strrchr strstr strset strnset strrev Compares two strings without regard to case ("i" denotes that this function ignores case) Compares two strings without regard to case (identical to strcmpi) Compares first n characters of two strings without regard to case Duplicates a string Finds first occurrence of a given character in a string Finds last occurrence of a given character in a string Finds first occurrence of a given string in another string Sets all characters of string to a given character Sets first n characters of a string to a given character 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 ) ;
89

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( ).

90

C Language

8-Structures

7.3.4 Strcmp ( )
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 theyre 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 Characters


In the last chapter we saw several examples of 2-dimensional integer arrays. Lets now look at a similar entity, but one dealing with characters. Heres 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++ ) {
91

C Language

8-Structures

a = strcmp ( &masterlist[i][0], yourname ) ; 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 Strings


A 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.

92

C Language

8-Structures

Akshay\0

Ram\0

Srinivas\0

182
Gopal\0

189 201
Rakesh\ 210 0

195
Parag\0

216 201 65520 210 65522 216 65524

182 65514

189 65516

195 65518

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.

93

C Language

8-Structures

Let us see, if the number of exchanges can be reduced by using an array of pointers to strings. Here is the program... main( ) { 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++ ) {
94

C Language

8-Structures

printf ( "\n Enter name " ) ; scanf ( "%s", names[i] ) ; } } The program doesnt 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.

Exercise What 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++ ; } }

95

C Language

8-Structures

(d) main( ) { char *str1 = "United" ; 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 " ) ; }

96

C Language

8-Structures

Programs
1. Write a c program to print the string from given character 2. 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 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 name 7. How to reverse a string in c without using reverse function 8. Write a c program to reverse a string using pointers 9. Write a c program to String concatenation without using string functions 10. 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 questions
1. 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 byte 3. 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;
97

C Language

8-Structures

} return n; } 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 cant prove that programmer wont 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.

98

C Language

8-Structures

WORKSHOP 1. Write a program to concat the two strings 2. Write a program to Reverse Strings 3. Write a program for Comparing Strings 4. Write a program for Palindrome 5. Write a program for vowel count

99

C Language

8-Structures

8. STRUCTURES
8.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 ;

100

C Language

8-Structures

(2)

struct book { char name ; float price ; int pages ; } b1, b2, b3; 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 ) ; }

(3)

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

C Language

8-Structures

C 256.50 682 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 Stored


The 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 = 65523
102

C Language

8-Structures

Actually the structure elements are stored in memory as shown in the Figure b1.names b1.price b1.pages B 130.00 550 65518 65519 65523

8.4 Array of Structures


Array 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 Structures


They can be used for a variety of purposes like: Changing the size of the cursor Clearing the contents of the screen
103

C Language

8-Structures

Placing the cursor at an appropriate position on screen 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 };

104

C Language

8-Structures

(c) 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 ;
105

C Language

8-Structures

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

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 questions
1. 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); }
106

C Language

8-Structures

4. What is the difference between a structure and a union? 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 machinedependent.) 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. Array 1-It is a collection of data items of same data type. 2-It has declaration only 3-.There is no keyword. 4- Array name represent the address of the starting element. Structure 1-It is a collection of data items of different data type. 2- It has declaration and definition 3- keyword struct is used 4-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.

107

C Language

8-Structures

9. Can a Structure contain a Pointer to itself? Yes such structures are called self-referential structures. 10. Why cant we compare structures? There is no single, good way for a compiler to implement structure comparison which is consistent with Cs 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 on the 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, compilersupplied 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 way of initializing any other member (nor, under a pre-ANSI compiler, is there generally any way of initializing a union at all). 13. Why doesnt 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 ;
108

C Language

8-Structures

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

109

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) b) c) d) e) f) Creation of a new file Opening an existing file Reading from a file Writing to a file Moving to a specific location in a file Closing a file Example //Reading content from a file # include<stdio.h> # include<conio.h> void main () { FILE *p;
110

C Language

9-File

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

fopen modes The allowed modes for fopen are as follows: r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists) 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. Fclose When you're done working with a file, you should close it using the function int fclose(FILE *a_file); fclose returns zero if the file is closed successfully. An example of fclose is
111

C Language

9-File

fclose(fp); Reading and writing with fprintf, fscanf fputc, and fgetc To 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 individual characters.Here is a an example program that writes strings to a file using the function fputs().

112

C Language

9-File

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); }

113

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

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

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 recordY/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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

C Language

Solution

//3Read two nos; Display the following menu for selection. Then read the option, and do the appropriate action. f. g. h. i. j. Add Multiply Divide Do Nothing 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

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

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

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

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

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

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

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

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

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

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

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

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. b. c. d. Add Multiply Stop 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

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

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

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

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

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

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

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

C Language

Solution

} //4) Read 5 numbers and store in an array. Check if any number is similar.Dont 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

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

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

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

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

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

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

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

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

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

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

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(Its a palindrome\n); else
168

C Language

Solution

printf(Its 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

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

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

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

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

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

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

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

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

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

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

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

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 recordY/N); fflush(stdin); another =getche(); } fclose(fp); } }

181

C Language

Solution

182

You might also like