Vous êtes sur la page 1sur 41

C & Data Structures

Unit II

History of C
C is a programming language developed at AT&Ts Bell Laboratories of USA in 1972. It was designed and written by Dennis Ritchie. By 1960, computer languages had come into existence, almost each for specific purpose. Example, COBOL used for Commercial Applications, FORTRAN for Engineering and Scientific Applications and so on. At this stage, people started thinking why not single language which an program all possible applications. Therefore, a committee formed and came up with language called ALGOL 60. It is too abstract, too general. So, it was not popular. A new language called Combined Programming Language(CPL) was developed at Cambridge University. CPL turned out to be so big, having so many features, that it was hard to learn and difficult to implement. Basic Combined Programming Language(BCPL) aimed to solve this problem bring CPL down to its basic good features. But unfortunately it turned out to be too less powerful and too specific Around the same time a language called B was written by Ken Thompson at AT&Ts Bell Labs. Ritchie inherited the features of B and BCPL, add some of his own and developed C.

Applications of C
C is perfectly suited for both systems programming suited for both systems programming and application programming. It is exclusively used for developing General Applications Database Systems Spread Sheets Graphic Packages CAD/CAM applications Word Processors Scientific/Engineering applications

Advantages of C
Various advantages of C are Machine independence : C codes can be compiled on different machines and they produce the same output when executed. Economy of expression : C is compact and coherent programming language. The code is quite cryptic and so, small length of codes can perform complex tasks. Operator richness : C supports a wide range of operators to handle arithmetic and logical calculations. Data structures : There are several ways to store data in C, which allows easy access to data.

Starting of C
Instead of straight-away learning how to write programs, we must first know what alphabets, numbers and special symbols are used in C, then how using these constants, variables and keywords are constructed Page 1

C & Data Structures

Unit II

and finally how are these combined to form an instruction A group of instruction would be combined later on to form a program. This is illustrated as follows Alphabets Digits Special Symbols Keywords Identifiers Variables Constants

Instructions

Program

Note : Keywords, Identifiers, Variables, constants can also be termed as C Tokens.

C Character Set
A character denotes any alphabet, digit or special symbol used to represent information. Following table shows the valid Alphabets, numbers and special symbols allowed in C Alphabets Digits Special symbols A,B,Z , a,b,z 0,1,2,3,4,5,6,7,8,9 ~!@#%^&*( )_ -+=| \{ } [ ] : ; < > . , ? /

Keywords
Keywords are the words whose meaning has already been explained to the compiler. The keywords are reserved words. The keywords cannot be used as variable names. There are 32 keywords available in C. auto case const default double enum float for if long register short static switch union void break char continue do else extern far goto int near return signed struct typedef unsigned while

Identifiers
Identifiers allow us to name data and other objects in the program. Each identified object in the computer is stored at a unique address. Without identifiers, we would have to know and use objects addresses. Different programming languages use different syntactical rules. Good identifier names are descriptive but short. C allows names to be up to 63 characters long. If the names are longer than 63 characters, then only the first 63 are used. Few rules of identifiers in C are as follows 1. First character must be alphabetic character or underscore. 2. Must contain only of alphabetic characters, digits or underscores. 3. First 63 characters of an identifier are significant. 4. Cannot duplicate a keyword. C is case sensitive language. This means that even though two identifiers are spelled the same, if the case of each corresponding letter doesnt match, C thinks of them as different names. Under this rule num, Num, NUM are three different identifiers Valid Names a //Valid but poor style student _name _aSystemName _Bool //Boolean System Id INT_MIN //System Defined Value $sum 2names Sum-salary stdt Nmber int Invalid Names //$ is illegal // First char is digit // contains hypen // Contains spaces // keyword

Constants
Constants are data values that cannot be changed during the execution of program. Page 2

C & Data Structures

Unit II

Constant Representations We use certain symbols to represent constants. They can be classified as follows i) ii) iii) iv) v) Boolean Constants Character Constants Integer Constants Real Constants String Constants

Boolean Constants A Boolean constants can take only two values. The values are true and false. A Boolean value can have only one of the two values 0 (false) and 1 (true). To use Boolean constants, we should include stdbool.h library.

Character Constants A Character constant is either a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Maximum length of a character constant can be 1 character. Ex. A, 5, = In addition to the character, we can also use a backslash(\) before the character. The backslash is known as the escape character. The escape character says that what follows is not the normal character but something else. \n \b \ \ \\ \0 \? \t Integer Constants An integer constant must have at least one digit It must not have a decimal point It could be either positive or negative. If no sign precedes an integer constant it is assumed to be positive. No commas or blanks are allowed within an integer constant. The allowable range for integer constants is -32768 to +32767. New Line Back Line Single Quote Double Quotes Backslash Null Question Mark horizontal tab

Ex: 426, -7605, +782 Real Constants Page 3

C & Data Structures

Unit II

Real constants often called as Floating Point constants. The real constants can be written in two forms, Fractional form and Exponential form. Rules for decimal form: A real constant must have at least one digit. It must have a decimal point. It could be positive or negative. Default sign is positive. No commas or blanks are allowed with in real constant.

Ex: 426.0, -32.76, +67.98 The exponential form of representation consists of two parts. The part appearing before e is called mantissa, where as the part following e is called exponent. Rules for exponential form: The mantissa part and the exponential part should be separated by letter e. The mantissa part may be positive or negative. Default sign in positive. Decimal point is allowed in the mantissa part. The exponent part must have at least one digit which may be positive or negative. Default sign in positive. The decimal point is not allowed in the exponent part. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38

Ex: +3.2e5, 3.2e-5, -4e7, -5e-6 String Constants String constants are sequence of characters enclosed within a double quote marks. The string may be combination of all kinds of symbols.

Ex. Hell0, 12345, a, a#5 Coding Constants We code constants in three ways in our programs. They are as follows : (i) (ii) (iii) Literal Constants. Defined Constants Memory Constants

Literal Constants A literal is an unnamed constant used to specify data. If we know that the data cannot be changed, then we can simply code the data value itself in a statement. Literals are coded as a part of statement. Ex : 3x + y = 20 , here 3, 20 are called literal constants.

Page 4

C & Data Structures Defined Constants A constant can be designated by using preprocessor command define.

Unit II

The define command are placed at the beginning of the program, although they are legal anywhere.

Ex: #define MAX 50 Considering above example, while the preprocessing is being performed, each defined name MAX in the program is replaced by value 50. Memory Constants Memory constants use a C type qualifier const to indicate that the data cannot be changed. const data_type identifier = value; ex : const int a = 10; The format is

Variables
Variables are names given to locations in the memory of computer where different constants are stored. These locations can contain integer, real, character or string constants. The variable value keeps on changing during the execution of program. Rules: A variable length varies from compiler to compiler. Generally most of compilers support upto 8 characters. The first character in variable name must be an alphabet. The variable should not be a keyword. Variable name must be without spaces and no other special character except underscore ( _ ) is permitted. Variable names may be combination of upper and lower characters. Ex. suM is not same as sum.

Ex: sum, total_sum, avg_2009 etc

Data Types
All C compilers support a variety of data types. This enables the programmer to select the appropriate data type as per the need of the application. The basic data types are 1. Character 3. Long 1. Character Data Type Character data type occupies 1 byte of memory. i.e. 8bits of memory is occupied. Keyword used to represent character data type is char. Range of char varies from -128 to 127. Control string used for char is %c. When printed using %d control string, corresponding ASCII number is printed. Page 5 2. Integer 4. Float 5. Double

C & Data Structures

Unit II

Few Points on Character Data type : Character data type supports only ASCII character set. ASCII stands for American Standard Code for Information Interchange. ASCII character set consists of English alphabets, digits and special symbols a total of 128 characters. To support non-English languages C99 standard created the wide character data type wchar_t. Ex : wchar_t ch; wchar_t occupies 2 byes of memory i.e. 16 bits of memory.

Note :Size of character data type is machine dependent and varies form computer to computer.

2. Integer Data Type Integer data type occupies 2 bytes of memory i.e. 16 bits of memory is occupied. Keyword used to represent integer data type is int. Range of int varies from -32,768 to 32,767. Control string used for int is %d.

3. Long Data Type Long data type occupies 4 bytes of memory i.e. 32bits of memory is occupied. Keyword used to represent long data type is long or long int. Range of long varies from -2147483648 to 2147483647 Control string used for long is %ld

4. Float Data Type Float data type occupies 4 bytes of memory i.e. 32bits of memory is occupied. Keyword used to denote float data type is float. Ranges of float varies from -3.4e38 to 3.4e38 Control string used for float is %f

5. Double Data Type Float data type occupies 8 bytes of memory i.e. 64bits of memory is occupied. Keyword used to denote double data type is double. Range of double varies from -1.7e-308 to 1.7-308 Control sting used for double is %lf

Note : Character, integer, long can further classified into signed and unsigned data types. Unsigned data types accept only positive data.

Quick Reference of Data Types Data Type Page 6 Size (in Range Control String

C & Data Structures Bytes) 1 1 2 2 4 4 4 8

Unit II

Char Unsigned char Int Unsinged int Long Unsigned long Float Double

-128 to 127 0 to 255 -32,768 to 32767 0 to 655655 -2147483648 to 2147483647 0 to 4294967295 3.4e-38 to 3.4e3.08 1.7e-308 to 1.7e+308

%c %c %d or %i %u %ld %lu %f or %g %lf

Other Data Types 1. Boolean Data Type a) With the release of C99, the C language incorporated a Boolean data type. b) The Boolean type, is referred by keyword bool, range of bool is 0(false) and 1(true). c) To support Boolean data type we should include header file stdbool.h Ex : bool b=1; 2. Imaginary Data Type a) C defines an imaginary type. It is referred by keyword imaginary. b) An imaginary number is used extensively in engineering and mathematics. c) An imaginary number is a real number multiplied with the square root of -1. d) The imaginary type can be float imaginary, double imaginary, long double imaginary. e) Most C implementations do not support the imaginary type. 3. Complex Data Type a) C defines complex data type, which is implemented by most compilers. b) A complex number is a combination of both real and an imaginary number. c) The complex type can be float complex, double complex, long double complex. d) The size needs to be the same in both the real and the imaginary part. e) To support complex data type we should include header file complex.h Ex : double complex x = 3 + 4 * I;

C Instructions
There are many instruction types. Basic two types of instructions in C: 1. Type Declaration Instruction to declare the type of variables used in C program. 2. Input/ Output Instruction to perform the function of supplying input data to a program and obtaining the output results from it. Type Declaration Instruction The variables must be declared before they are used in the program. Declaration provides two things. i) Compiler obtains variable name. ii) It tells to the compiler data type of variable being declared and helps in allocating memory Page 7

C & Data Structures Syntax: data_type variable_name Example char ch; int age; float salary; // Variable named ch of character data type is declared // variable named age of integer data type is declared // variable named salary of float data type is declared

Unit II

The variables can be assigned or initialized using an operation =. The declaration and initialization can also be done in same line. Example: 1) int a; a = 10; 2)

declaration of variable a of integer data type Initialization of variable a

int a=10; declaration and initialization of variable a

Note : Variables are not initialized automatically. When variables are defined, they usually contain garbage values.

Overview of Streams
In C, data is input to and output from a stream. A Stream is a source or destination of data. It is associated with a physical device, such as a terminal or with a file stored in auxillary memory. C uses two forms of streams : text and binary. A text stream consists of a sequence of characters divided into lines with each line terminated by new line. A binary stream consists of a sequence of data values such as integer, real, or complex using memory representation. A terminal keyboard and monitor can be associated only with a text stream only. A file may consist of text stream or binary stream

Input / Output Instruction Mostly used output statement is printf() and mostly used input statement is scanf(). Both printf() and scanf() are functions, which are used to write and read all types of data values respectively. a) printf() statement The output formatting function is printf().The printf() function prints all types of data values to the console. It can be written in two forms i) printf( string); The string written in the function will be outputted on the console. Ex.: printf( Hai);

ii) printf( control string, arg1, arg2..argn);

Page 8

C & Data Structures

Unit II

The printf() function takes set of data values, converts them to a text stream sing formatting instructions contained in a format control string. The format control string indicates the data types i.e. %c for character, %d for integer, %f for float etc. The arguments represent the variable name. Ex: printf(%c%d%f,ch,sum,avg); Output Formatting Styles using printf() A width modifier may be used to specify the minimum number of positions in the output. It is very useful to align output in columns. Ex : %3d means 3 print positions for integer If floating point numbers is being printed, then we may specify the number of decimal places to be printed with the precision modifier. The precision modifier has the format .m where m is the number of decimal digits. Ex : %8.3f means 7 print positions for float in which there are 3 digits after point i.e. nnnn.ddd Note : If no precision is specified, printf() prints six decimal positions. b) scanf() statement The scanf() functions reads all the data type values. It is used for runtime assignment of variables. The syntax is as follows scanf(control string,&arg0, &arg1..&argn); Control string indicates the data types and the arguments represent the variable name. & is called address operator. &arg0 indicates the address of the variable. Ex : scanf(%c%d%f,&ch,&sum, &avg);

C Program Structure
Program is the collection of instructions in a particular format. Each C program contains a number of building blocks. The structure of C program is as follows Include Header File Section Global Declaration Section // Comments main() { //Comments Declaration Part Executable Part -------} User Defined Functions

Page 9

C & Data Structures

Unit II

a) Include header file section : A C program depends upon some header files for function definition that used in the program. Each header file by default has a extension .h. The file should be included using #include directive. Ex. #include<stdio.h> or #include stdio.h b) Global declaration section : This section declares some variables that are used in more than one function. These variables are known as global variables c) Function main() : Every C program must contain main() function. Empty parentheses after main are necessary. The function main() is the starting point of every C Program. The execution always begin with the function main(). The program execution starts from starting brace { and ends with ending brace }. Between two braces the programmer should write the executable code. d) Declaration part : The declaration part declares all variables that are used in the executable part. Initialization can also be done in this section. e) Executable part : This part contains single statement or set of statements for execution. All the statements must be enclosed between braces. f) User-defined functions: The functions defined by the user are called user-defined functions. This portion is defined after main() function. This portion is not compulsory. g) Comments : Comments are not necessary in the program. However, to understand the flow of program, programmer can include comments in the program. These are useful for documentation. The comments can be single line or multiple line. These comments are not executed. Single line comments can be written by using two slashes(//) Ex : //This is a single line comment Multiple line comments can be written by enclosing them between /* and */ symbols. Ex : /* It is a very common type of commenting multiple lines of documentation*/ Programming Rules All statements should be written in lowercase letters. Uppercase letters are only used for symbolic constants. Blank spaces may me inserted between the words. This improves the readability of statements. Every statements must end with a semi-colon (;) The opening and closing braces should be balanced.

Sample C Programs 1. /*Program to print Welcome on the screen */ void main() { Page 10

C & Data Structures printf(Welcome to C Programming); } Output : Welcome to C Programming 2./* Program to print the values stored after initialization */ void main() { char grade= A; int sum = 533; float avg = 88.3; printf(Sum = %d, Average = %f, Grade = %c, sum, avg, grade); } Output : Sum = 533, Average = 88.3, Grade = A

Unit II

3./*Program to read the values during execution and print them */ void main() { char grade; int sum; float avg; printf(Enter the sum, avg, grade values); scanf(%d%f%c,&sum,&avg,&grade); printf(Sum = %d, Average = %f, Grade = %c, sum, avg, grade); } Output: Enter the sum, avg, grade values 533 88.3 A Sum = 533, Average = 88.3, Grade = A

Operators
To perform different kinds of operations, C uses different of operators. An operator indicates an operation to be performed on data that yields a values. C provides different types of operators 1) Arithmetic Operators 2) Relational Operators 3) Logical Operators 4) Assignment Operators 5) Conditional Operators 6) Bitwise Operators 7) Increment and decrement operator 8) Others Operators

1) Arithmetic Operators
C provides five arithmetic operators, they are Operator + * / Page 11 Meaning Addition Subtraction Multiplication Division

C & Data Structures % Expression m+n mn m*n m/n m%n Value 15 (11+4) 7 (11- 4) 44 (11 * 4) 2 (11/4) 3 (11%4) Modulus

Unit II

Example: Suppose m and n are integer variables whose values are 11 and 4 respectively

If both operands represent integer quantities, the result of integer division is always integer, that is the decimal part of the result is always truncated. Example: Suppose a and b are floating variables whose values are 12.5 and 10.0 respectively Expression a +b a -b a * b a /b cannot be used with float quantities. Example: Suppose a and b are floating and integer variables respectively whose values are 14.5 and 10 respectively Expression a +b a - b a*b a/b Value 24.5 4.5 145.0 1.45 (14.5 + 10) (14.5 10) (14.5 * 10) (14.5 / 10) Value 22.5 2.5 1.25 (12.5 + 10.0) (12.5 10.0) (12.5 / 10.0)

125.00 (12.5 * 10.0)

If both operands represent float quantities, the result of float division is always float. The modulus operator

If one operand represent integer quantity and other represent float quantity, the result is always float. The modulus operand cannot be used with integer and float combination.
Precedence( Priority of operators)

* / % + -

Higher Precedence Lower Precedence

--- They are applied from Left to Right --- They are applied from Left to Right

Example : If a=10, b = 16 and c=5 then find the value of n if n= a b / 4 + c * 2 3 . Solution : n = 10 16 / 4 + 5 * 2 3 Step1 n = 10 4 + 5 * 2 3 Step 2 n = 10 4 + 10 3 Step 3 n = 6 + 10 3 Step 4 n = 16 3 Step 5 n = 13
/*Program to demonstrate arithmetic operators */ Page 12

C & Data Structures #include <stdio.h> void main() { int a , b; printf("Enter two numbers :"); scanf("%d%d", &a, &b); printf(" Sum = %d", (a+b)); printf(" Difference = %d", (a - b)); printf(" Product = %d", (a*b)); printf(" Division = %d", (a/b)); printf(" Modulus = %d",(a%b)); } Output : Enter two numbers : 25 10 Sum = 35 Difference = 15 Product = 250

Unit II

Divison = 2

Modulus = 5

2) Relational Operators
C supports following 6 relational operators Operator > >= < < = == != Meaning Greater than Greater than or equal Lesser than Lesser than or equal Equal Not Equal

Each of these relational operators require two operands and can be combined together to form relational expressions, which represent conditions that are either true or false. The resulting expressions are of type integer, since in C true is represented by integer value 1 and false is represented by integer value 0. Precedence of Operators > >= < <= == != High Priority ---- The operator will be evaluated from Left to Right Low Priority ---- The operator will be evaluated from Left to Right

Examples: Suppose a is an integer whose value is 10. b is floating variable whose value is 2.5 i.e. a= 10, b=2.5 Expression a>5 (a + b) < 12 b * 6 >= a + b a / 5 <= b a a * a == 10 b + a != 5 Value 1 0 1 0 0 1 Explanation 10>5 is true (10+2.5)<12 i.e. 12.5<12 is false 2.5 * 6 >= 10+2.5 i.e. 15.0 >=12.5 is true 10 / 5 <= 2.5 10.0 i.e. 2 <= -7.5 is false 10 * 10 = =10 i.e. 100 == 10 is false 2.5 + 10.0 != 5 i.e. 12.5 != 5 is true

/*Program to demonstrate relational operators*/ void main() { printf( 5>2 is %d,5>2); printf(\n 5>=2 is %d,5>=2); Page 13

C & Data Structures printf(\n printf(\n printf(\n printf(\n 5<2 is %d,5<2); 5<=2 is %d,5<=2); 5==2 is %d,5==2); 5!=2 is %d,5!=2);

Unit II

} Output 5>2 is 1 5>=2 is 1 5<2 is 0 5<=2 is 0 5 == 2 is 0 5 != 2 is 1

3) Logical Operators
In addition to the relational operators discussed, C supports three logical operators that act upon logical expressions. These are Operator && || ! Meaning Logical AND Logical OR Logical NOT

Thus logical operators can be used to form more complex conditions that are either true or false. &&(AND) Operator 1. Evaluates true when both the relational expression are true. 2. Evaluates false when any one of the relational expression is false. The following is truth table for AND operator Condition1 False (0) False (0) True (1) True (1) ||(OR) Operator 1. Evaluates false when both the relational expression are false. 2. Evaluates true when any one of the relational expression is true. The following is truth table for OR operator Condition1 False (0) False (0) True (1) True (1) !(NOT) Operator This is a unary operator that negates the value of a relational or logical expression. 1. Evaluates true when the relational expression is false. Page 14 || || || || Condition2 False (0) True (1) False (0) True (1) = = = = Output False (0) True (1) True (1) True (1) && && && && Condition2 False (0) True (1) False (0) True (1) = = = = Output False (0) False (0) False (0) True (1)

C & Data Structures 2. Evaluates false when the relational expression is true. Condition ! ! False (0) True (1) = = Output True (1) False (0)

Unit II

Precedence of Operators ! && || then Expression (a>b) &&(b>5) (a>b) || (b>5) ! (a>b) 4) Assignment Operator Operator = += -= *= /= Meaning assign add and assign subtract and assign multiply and assign divide and assign Value 0 1 0 Explanation (10>2.5) && (2.5>5) i.e. true && false = false (10>2.5)|| (2.5>5) i.e. true || false = true (10>2.5) is true. i.e NOT true = false High Priority Low Priority ------This operator evaluates from right to left These operators evaluates from left to right This operator evaluates from left to right. Medium Priority---

Example : Suppose a is an integer variable whose value is 10, is a floating-point variable whose value is 2.5

These operators execute from right to left. The right side expression is evaluated and assigned to left variable. Example: Let a, b, c, d are integer variables whose values are 10, 12, 14, 16 respectively Expression x=10; a+=10 b-=5 c*=b d/=4 Output --20 7 70 4 Explanation Value 10 is assigned to variable x a = a+ 10 i.e. 10+10 = 20 b = b 5 i.e 12 5 = 7 c = c * b i.e. 14 * 5 = 70 d = d / 4 i.e 16 / 4 = 4

/*Program to demonstrate usage of assignment operators*/ void main() { int a=7,b=5,c=2,d=3,e=60; printf(Before operation a=%d, b=%d, c=%d, d=%d, e=%d,a,b,c,d,e); a=10; b+=a; c-=a; d*=b; e/=b; prinf(\nAfter operation a=%d, b=%d, c=%d, d=%d, e=%d,a,b,c,d,e); } Page 15

C & Data Structures Output Before operation a=7, b=5, c=2, d=3, e=6 After operation a=10, b=15, c= - 8 , d=45, e=4 5) Conditional Operator

Unit II

C offers a ternary operator pair ? : that can be used to carry out simple conditional operations. The syntax is as follows expression 1 ? expression 2 : expression 3 where expression 1 is logical expression, while expression 2 and expression 3 can be constants, identifiers or other complex expressions. When a conditional operator is used, expression 1 is first evaluated. If expression 1 is true then expression 2 is evaluated. If expression 1 is false then expression 3 is evaluated. Example : (a> b) ? 5 : 10 If the expression a>b is true then output is 5 else output is 10

/* Program to find the largest of two numbers using conditional operator*/ #include<stdio.h> void main() { int num1, num2, max,min; printf(Enter two numbers); scanf(%d%d,&num1, &num2); max = (num1 >num2) ? num1 : num2; printf(\nLargest Number = %d,max); min = (num1 < num2) ? num1 : num2; printf(\nSmallest Number = %d,min); } Output Enter two numbers : 6 7 Largest Number = 7 Smallest Number = 6 6) Bit wise Operator C supports six bit wise operators. These operators can operate only on an integer operands such as int, char, short, long int etc. These do not work with float operands like float, double . Operator >> << & | ~ ^ Meaning Right Shift Left Shift Bitwise AND Bitwise OR Ones Complement (Bitwise NOT) Exclusive OR

Example: Let a, b are integer variables whose values are 8,3 respectively. Then Representation of 8 is 0000 0000 0000 1000 Representation of 3 is 0000 0000 0000 0011 1) a >> b i.e. 8 >> 3 means right shift three bits in representation of 8 0000 0000 0000 0001 Therefore 8 >>3 = 1 Page 16

C & Data Structures 2) a << b i.e. 8 << 3 means left shift three bits in representation of 8 0000 0000 0100 0000 Therefore 8 << 3 = 64 3) a & b i.e. 8 & 3 0000 0000 0000 1000 0000 0000 0000 0011 ------------------------------0000 0000 0000 0000 8 3 8&3 = 1

Unit II

4) a | b i.e. 8 | 3 0000 0000 0000 1000 0000 0000 0000 0011 --------------------------------0000 0000 0000 1011 5) a ^ b i.e. 8 ^ 3 0000 0000 0000 1000 0000 0000 0000 0011 -------------------------------0000 0000 0000 1011 6) ~a i.e. ~8 0000 0000 0000 1000 1111 1111 1111 0111 7) Increment and Decrement Operator C includes two useful operators, which are generally not found in other computer languages developed prior to C. Operator ++ -To be precise x = x+1 can be written as x++; x = x 1 can be written as x- -; Example : If a = 5, then a++ =6 i.e. a= a+1 = 5+1 If a = 6, then a - - = 5 i.e. a = a 1 = 6 1 Both the operators may either precede or follow the operand i.e. x = x+1 can be written as x++ or ++x x = x 1 can be written as x - - or - - x Here, x++ is known as post increment operator ++x is known as pre increment operator x - - is known as post decrement operator - - x is known as pre decrement operator. Meaning increment by 1 decrement by 1 8 ~8 8 3 8 ^ 3 = 11 8 3 8 |3 = 11

Page 17

C & Data Structures

Unit II

The difference between pre- and post- fixing the operator is useful when if used in an expression. When the operator precedes the operand, C performs the increment or decrement before using the value of the operand. Ex: If x =5 and y = + + x then y = 6 and x = 6 If x = 8 and y = - - x then y = 7 and x = 7 When the operator follows the operand, the value of operand is used before incrementing or decrementing the operand value. Ex: If x =5 and y = x + + then y = 5 and x = 6 If x = 8 and y = x - - then y = 8 and x = 7

1. /* Program to show the affect of increment operator as suffix */ #include <stdio.h> void main() { int a, z, x = 10, y = 20; z = x * y ++; a= x*y; printf(" z =%d, a = %d", z , a); } Output : z =200, a= 210 2. /*Program to show effect of increment operator as a prefix */ #include <stdio.h> void main() { int a, z, x = 10, y = 20; z = x * ++y ; a= x * y; printf(" z =%d, a = %d", z , a); } Output : z =210, a= 210

8) Other Operators
a) Comma Operator (,) The comma operator is used to separate two or more expressions. The comma operator has the lowest priority among all the operators. Example : a=10, b, c=a+b; b) sizeof() operator The sizeof() operator is used to find the size occupied by a particular data type. Sizeof() is a function which takes a single parameter. It returns an integer value Syntax : sizeof(data_type) Ex : sizeof(int) /*Program to illustrate usage of sizeof() operator */ void main() { Page 18

C & Data Structures

Unit II

printf( Integer = %d, Float = %d, Character = %d,sizeof(int), sizeof(float), sizeof(char)); } Output Integer = 2, Float = 4, Character = 1 c) Unary Plus (+) and Unary Minus (-) Operators + and - can also be used with single operand. + is used to indicate positive sign. - is used to indicate negative sign. Ex : +7 indicates positive 7 - 7 indicates negative 7

d) Address operator (&) & symbol is termed as address operator. It is used in mostly used in scanf() statement. The address operator is used to get the memory address location of an identifier. Ex. &a indicates address of operator /*Program to demonstrate usage of address operator*/ void main() { int a; float b; printf(Address of a = %u,&a); printf(Address of b = %u,&b); } Output Address of a = 65524 Address of b = 65520

Expressions
An expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action to be taken. An operand is an object on which an operation is performed. Expressions may be complex or simpler. A simpler expression contains only one operator. A complex expression contains more than one operator. Expressions can be divided into six categories 1) Primary Expressions 2) Postfix Expressions 3) Prefix Expressions 4) Unary Expressions 5) Binary Expressions 6) Ternary Expressions Primary Expression

Page 19

C & Data Structures

Unit II

A primary expression consists of only one operand with no operator. In C, the operand in primary expression may be a name, a constant or a parenthesized expression. Primary expression is evaluated first in a complex expression. Name : A name is any identifier for a variable, a function or any other object in language. a program. 5 123.98 A Hai Parenthetical Expressions : Any value enclosed in parentheses must be reducible to a single value and is therefore a primary expression. This includes any of the complex expressions when they are enclosed in parentheses. (2 * 3 + 5) Postfix Expression The postfix expression consists of one operand followed by one operator. Syntax : operand operator There are several postfix expressions. Few of them are function call, postfix increment and postfix decrement. Ex : printf(), a++, a- Function calls are postfix expressions. The function name is the operand and the operator is the parentheses that follow the name. The parentheses may contain arguments or be empty. When present, the arguments are part of the operators.
Note : ++, - - can be called as postfix operators when used in postfix expression

s12

price

calc INT_MAX

Literal Constants : A constant is a piece of data whose value cant change during the execution of the

(a=10+b)

Prefix Expression The prefix expression consists of one operator followed by one operand. Syntax : operator operand Examples for prefix expressions are prefix increment and prefix decrement. Ex : ++a, - - a
Note : ++, - - can be called as prefix operators when used in prefix expression

Unary Expressions The unary expression, like a prefix expression, consist of one operator and one operand. Although prefix expressions and unary expressions look the same, they belong to different expression categories because the prefix expression needs a variable as the operand while the unary expression can have an expression or a variable as the operand. Syntax : operator operand Example for unary expressions are positive/negative sign, sizeof operator, Logical NOT operator, etc Ex : +5, -7, sizeof(int), !a, ~10, &c Note : Unary Plus (+), Unary Minus ( -), Logical NOT (!), ones complement (~), address (&), sizeof() are called as unary operators. Page 20

C & Data Structures Binary Expressions

Unit II

Binary expressions are the combinations of two operands and an operator in between them. Syntax : operator operand operator Arithmetic expressions, relational expressions, logical and expression, logical OR expression, assignment expression etc are examples of binary expressions Ex. a+b, a b, a * b, a/ b, a%b, a>b, a<b, a>=b, a<=b, a==b, a!=b, a&&b, a||b, a&b, a|b, a^b, a<<b, a>>b, a=b, a+=b, a=-b, a*=b, a/=b, a%=b
Note : Addition(+), subtraction (-), multiplication (*), division (/), modulus (%), less than (<), less than equal to (<=), greater than (>), greater than equal to (>=), equal to (==), not equal to (!=), Bitwise AND (&), Bitwise OR (|), Bitwise XOR(^), Logical AND(&&), Logical OR(||), assignment (=) are called binary operators.

Ternary Expression Ternary Expression is an expression which consists of three operands and a pair of operator. Condition expression is an example for ternary expression. Ex: (a>b) ? a: b
Note : Conditional operator(?:) is called ternary operator

Precedence and Associativity


Precedence is used to determine the order in which different operators in a complex expression are evaluated. Associativity is used to determine the order in which operators with the same precedence are evaluated in a complex expression. Precedence is applied before associativity to determine the order in which expressions are evaluated. Associativity is then applied, if necessary. The following table determines the Precedence and associativity of operators.
Operators () [] -> . + ++ -! _ * & * / % + << >> < <= > >= == != Operation Function Call Array expression Structure Operator Structure Operator Unary Plus Unary Minus Increment Decrement Logical NOT Ones complement Pointer Operator Address Operator Multiplication Division Modular Division Addition Subtraction Left Shift Right Shift Less than Less than or equal Greater than Greater than or equal Equality Not Equality Associativity Left to Right Precedence 1

Right to Left

Left to Right Left to Right Left to Right

3 4 5

Left to Right Left to Right

6 7

Page 21

C & Data Structures


& ^ | && || ?: = += -= *= /= &= |= ^= <<= >>= , Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Operator Assignment Operator Comma Operator Left to Right Left to Right Left to Right Left to Right Left to Right Right to Left Right to Left Left to Right 8 9 10 11 12 13 14 15

Unit II

Side Effect A side effect is an action that results from the evaluation of an expression. For example, in an assignment, C first evaluates the expression on the right of the assignment operator and then places the value in the left variable. Changing the value of the left variable is called side effect. Example expression without side effects a*4+b/2c*b Example expression with side effects - - a * (3 + b) / 2 c ++ * b

Type Conversion
If we write an expression that involves two different data types, to perform these evaluations, one of the types must be converted. There are two types of type conversions. a) Implicit Type Conversion b) Explicit Type Conversion Implicit Type Conversion When the types of the two operands in a binary expression are different, C automatically converts one type to another. This is known as implicit type conversion. For implicit type conversion, C has several complicated rules. In C, we can assign a rank to the integral and floating-point arithmetic types. Example : bool (Rank 1), char (rank 2), int (rank 3), long (rank 4), float (long 5), double (rank 6) Let us consider a simple assignment involves an assignment operator and two operands. Depending on the difference in the rank, C tries to either promote or demote the right expression to make it the same rank as the left variable. Promotion occurs if the right expression has lower rank. There is normally no problem with promotion. Example of promotions char int c= A; i= 124; // value of i is 65 // value of d is 124.0

double d = 345.236; i = c; d = i;

Demotion occurs if the right expression has higher rank. It may or may not create problems. When an integer or a real is assigned to a variable of type character, the least significant byte of the number is converted

Page 22

C & Data Structures

Unit II

to a character and stored. When a real is stored in an integer, the fraction part is dropped. However, if the integral part is larger than the maximum value that can be stored, the results are invalid and unpredicatable. Examples of demotions are char c = A; int k = 65; c=k+1; Explicit Type Conversion Rather than let the compiler implicitly convert data, we can convert data from one type to another ourself using explicit type conversion. value. Ex: (float) a/10 avg = (float) (sum/6) // converting the a to float data type // converting the result value into float Explicit conversion uses the unary cast operator, which has a precedence of 14. To cast data from one type to another, we specify the new type in parenthesis before the //value of c is b

Decision Control Statements


A program is nothing but the execution of sequence of one or more instructions. In the monolithic program the sequences of instructions are executed in the same order as they appear in the program. In practical applications, there are a number of situations where one has to change the order of the execution of statements based on the conditions. This involves decision making condition to see whether a particular condition is satisfied or not. The conditions can be placed in the program using decision making statements. C Language supports the control statements as listed below 1) The simple if Statement 2) The if else Statement 3) The nested if Statement 4) The if else - if Statement 5) The switch() case Statement 1) Simple if C uses the keyword if to execute a set of command lines or one command line when the logical condition is true. It has only one option. The set of statements are executed when the logical condition is true. Syntax : if(condition) { Statements; } Example: 1. /* Program to check whether the entered number is less than 10 */ #include<stdio.h> void main() { int num; printf("Enter a number :"); Page 23

C & Data Structures scanf("%d",&num); if(num<10) printf("Number is less than 10"); } Output Enter a number : 9 Number is less than 10 or Enter a number : 11

Unit II

(Here no output is blank as the condition is false)

2. /* Program to check the eligibility to vote */ #include<stdio.h> void main() { int age; printf(Enter your age :); scanf(%d,&age); if(age >= 18) printf(You are eligible for voting); } Output Enter your age : 19 You are eligible for voting (or) Enter your age : 16 (Here output is blank as the condition is false) 2) If. Else Statement The if..else statement takes care of true as well as false conditions. It has two blocks. One block is for if and other block is for else. If the condition is true, the if block statements are executed, and if the condition is false, else block statements are executed. Syntax: if(condition) { Statements; } else { Statements; } 1. /* Program to find the largest of two numbers using if..else statement*/ #include <stdio.h> void main() { int a,b; printf("Enter two number :"); scanf("%d%d",&a, &b); if(a>b) printf("Largest Number = %d",a); else printf("Largest Number = %d",b); } Output Enter two numbers : 20 14 Largest Number = 20 2. /* Program to find the given number is even or odd */ #include <stdio.h> void main() Page 24

C & Data Structures { int num; printf("Enter a number :"); scanf("%d",&num); if(num%2==0) printf("Even number"); else printf("Odd number");

Unit II

} Output Enter a number : 9 Odd number

3./*Program to verify whether given character is vowel or not*/ #include <stdio.h> void main() { char ch; printf("Enter an alphabet (a-z):"); scanf("%c",&ch); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u') printf("Vowel"); else printf("Not Vowel"); } Output Enter an alphabet(a-z) : e Vowel 4./* Program to check entered year is a leap year or not */ #include<stdio.h> void main() { int leap; printf("Enter year :"); scanf("%d", &leap); if(leap%4 == 0) printf("%d is a leap year",leap); else printf("%d is not a leap year",leap); } Output: Enter year : 2003 2003 is not a leap year 3) Nested If Statement Syntax : if(condition 1) { if(condition 2) { statements; } else { statements; } } else { if(condition 3) { statements; Page 25

C & Data Structures } else { } } 1. /* Program to find the largest #include <stdio.h> void main() { int a,b,c; printf("Enter three numbers scanf("%d%d%d",&a, &b, &c); if(a>b) { if(a>c) { printf("Largest } else { printf("Largest } } else { if(b > c) { printf("Largest } else { printf("Largest } } } Output Enter three numbers : 20 24 16 Largest Number = 24 4 If.. Else.. If Statement of three numbers using nested if */ statements;

Unit II

:");

Number = %d",a);

Number = %d", c);

Number = %d",b);

Number = %d", c);

In this kind of statements number of logical conditions are checked for executing various statements. Ifelseif can be chained with one another. If the condition is false control passes to else block where condition again checked with the if statement. This process continues if there is no if statement in the last else block. If one of the if statement satisfies the condition, other else..if will not be executed. Syntax: if(condition 1) { statements; } else if(condition 2) { statements; } ...... else { statements; Page 26

C & Data Structures } 1. /* Program to find the largest of three numbers */ #include <stdio.h> void main() { int a,b,c; printf("Enter three numbers :"); scanf("%d%d%d",&a, &b, &c); if(a>b && a>c) printf("Largest Number = %d",a); else if(b>a && b>c) printf("Largest Number = %d",b); else printf("Largest Number = %d", c); } Output Enter three numbers : 20 24 16 Largest Number = 24

Unit II

2. /* Program to find the average of six subjects and display the results as follows AVERAGE RESULT >70 Distinction >60 and <70 First Division >50 and <60 Second Division >40 and <50 Third Division <40 Fail */ void main() { int m1,m2,m3,m4,m5,m6, sum = 0; float avg; printf("Enter 6 subject marks :"); scanf("%d%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5,&m6); sum= m1+m2+m3+m4+m5+m6; avg = sum/6; printf("Total : %d\n Average : %f",sum,avg); if(avg>=70) printf(Distinction); else if(avg>=60 && avg<70) printf("\nFirst Division"); else if(avg>=50 && avg<60) printf("\nSecond Division"); else if(avg>=40 && avg<50) printf("\nThird Division"); else printf("\nFail"); getch(); } Output Enter 6 subject marks : 40 50 60 70 80 90 Total : 390 Average : 65.000000 First Division 3./Program to calculate energy bill. Read the starting and ending meter reading. The charges are as follows : No. of units consumed Rate per Unit <100 1.50 100 200 2.00 200 300 2.50 > 300 3.00 */ Page 27

C & Data Structures void main() { int initial, final, consumed; float bill; printf("Enter Initial & final Readings :"); scanf("%d%d",&initial, &final); consumed = final - initial; if(consumed>0 && consumed <=100) bill = consumed * 1.50; else if(consumed>100 && consumed<=200) bill = consumed * 2.00; else if(consumed>200 && consumed <=300) bill = consumed * 2.50; else bill = consumed * 3.00; printf("Bill Amount = %f", bill); getch(); } Output Enter Initial & Final Readings : 40 90 Bill Amount = 75.000000 5) Switch Case

Unit II

Switch is a multi-way decision-maker that tests whether an expression matches one of a number of alternate values and braches accordingly. In the program, if there is a possibility to make a choice from a number of options, this structured selection is useful. The switch() statement is useful for writing menu driven program. The switch statement requires only one argument of any data type, which is checked with number of case options. The switch statement evaluates expression and then looks for its value among the case constants. If the value matches with case constant, this particular case statement is executed. If not, default is executed. Points to Remember switch, case, and default are keywords. Every case statement terminates with : No semicolon is used after switch statement. The break statement is used to exit from current case structure. If no break statements are given all the cases following it will be executed

Syntax : switch (expression) { case case case constant_value : constant_value : constant_value : . Page 28 statement; break; statement; break; statement; break;

C & Data Structures default : } Sailent Features 1. Each case labeled by integer or character constant. 2. Cases and default may occur in any order. 3. Cases must all be different. statement;

Unit II

4. After the code for one case is done, execution falls through to the next unless you take explicit action to escape.

1./* Program to print the number between 0 and 9 in words using switch case*/ #include<stdio.h> void main() { int num; printf("Enter a number (0-9) :"); scanf("%d",&num); switch(num) { case 0 : printf("\n ZERO"); break; case 1 : printf("\n ONE"); break; case 2 : printf("\n TWO"); break; case 3 : printf("\n THREE"); break; case 4 : printf("\n FOUR"); break; case 5 : printf("\n FIVE"); break; case 6 : printf("\n SIX"); break; case 7 : printf("\n SEVEN"); break; case 8 : printf("\n EIGHT"); break; case 9 : printf("\n NINE"); break; default : printf("\nWrong choice"); } } Output Enter a number : 4 FOUR 2. /* Program to check given alphabet is vowel or consonant */ #include<stdio.h> void main() { char ch; printf("Enter a character (a-z or A-Z) :"); scanf("%c",&ch); switch(ch) Page 29

C & Data Structures { case case case case case case case case case case 'a' 'e' 'i' 'o' 'u' 'A' 'E' 'I' 'O' 'U' : : : : : : : : : :

Unit II

default

printf("\nVowel"); break; : printf("\nConsonant");

} } Output : Enter an character (a-z or A Z) : Consonant

3./* Program to provide arithmetic functions by using switch */ #include<stdio.h> void main() { int a,b,ch; printf("\n MENU\n 1. Addition \n 2.Subtraction \n 3.Multiplication\n 4.Division\n 5.Remainder "); printf("Enter two numbers :"); scanf("%d%d",&a, &b); printf("\n Enter your choice :"); scanf("%d",&ch); switch(ch) { case 1 : printf("Addition = %d", (a+b)); break; case 2 : printf("Subtraction = %d", (a-b)); break; case 3 : printf("Multiplication = %d", (a*b)); break; case 4 : printf("division = %d", (a/b)); break; case 5 : printf("Remainder = %d", (a%b)); break; default : printf("Selected Wrong Choice"); } } Output Menu 1.Addition 2.Subtraction 3.Multiplication 4.Division 5.Remainder Enter two numbers : 33 Enter your choice : 4 Remainder = 3 Nested switch() Case Page 30 10

C & Data Structures C supports the nested switch() statements. The inner switch() can be a part of an outer switch().

Unit II

The inner and outer switch() case constants may be same. No conflict arises even if they are same. Few differences between switch() and if() are as follows: switch() case The switch() can only test for equality i.e. only one constant values are applicable. No two case statements have identical constants in the same switch Character constants are automatically converted to integers. nested if() statement The if can evaluates relational or logical expressions. Same conditions may be repeated number of times. Character constants are automatically converted to integer.

Repetition Statements (Loops)


Loop is defined as a block of statements which are repeatedly executed for certain number of times. Steps in Loop 1. Loop Variable : It a variable used in the loop. 2. Initialization : It is the first step in which starting and final value is assigned to the loop variable. 3. Condition : Each time the updated value is checked by the condition. 4. Incrimination/ Decrimination : It is the numerical value added or subtracted to the variable in each round of the loop. The C language supports three types of loop control statements. They are 1. The for loop 2. The while loop 3. The do while loop

The for Loop


The for loop allows to execute a set of instructions until a certain condition is satisfied. Condition may be predefined or open-ended. Syntax : for(initialize counter; { Statements; } Explanation : The initialize counter sets a loop to an initial value. This statement is executed only once. The test condition is a relational expression that determines the number of iterations desired or it determines when to exit from the loop. The for loop continues to execute as long as conditional test is test condition; re-evaluation parameter)

Page 31

C & Data Structures

Unit II

satisfied. When the condition becomes false the control of the program exits from the body of the for loop and executes next statement after the body of the loop. The re-evaluation parameter decides how to make changes in the loop. The body of the loop may contain either a simple statement or multiple statements. In case there is only one statement after for loop braces may not be necessary. In such a case only one statement is executed till the condition is satisfied. It is good practice to use braces even for single statement following the for loop. Various Forms of for loop Syntax 1) for (;;) 2) for (a=0; a<=20; ) 3) for (; a<=10; a++) 4) for(a=1; ; a++) 5) for( a=1; a<10; a++)

Output Infinite Loop Infinite Loop Blank Infinite Loop Prints 1 to 9

Remarks No arguments a is neither increased decreased a is not initialized No condition is specified a is increased from 1 to 9

or

1./* Program to print 1 to 10 numbers */ #include<stdio.h> void main() { int i; for(i=1; i<=10; i++) printf(%d\t,i); } Output 1 2 3 4 5 6 7 8 9 10 2./* Program to find sum of 1 to 100 numbers */ void main() { int i, sum=0; for(i=1; i<=100; i++) sum = sum + i; printf(Sum = %d,sum); } Output Sum = 5050 3./* Program to find sum of even and odd numbers of n numbers*/ void main() { int i,esum=0,osum=0,num; printf("Enter the number :"); scanf("%d",&num); for(i=2; i<=num; i=i+2) esum = esum + i; for(i=1; i<=num; i=i+2) osum = osum + i; printf("Even Sum = %d\tOdd Sum = %d",esum,osum); } Output Enter the number : 10 Even Sum = 30 Odd Sum = 25 4./* Program to print multiplication table for a given number */ void main() Page 32

C & Data Structures { int i,num,pro; printf("Enter a number :"); scanf("%d",&num); for(i=1; i<=10; i++) { pro=num*i; printf("%d x %d = %d\n",num,i,pro); }

Unit II

} Output Enter a number : 5 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50 5. /*Program to find the square root of n numbers where n is a given number */ #include<math.h> void main() { int i,num; printf("Enter a number :"); scanf("%d",&num); for(i=1; i<=num; i++) { printf("%d\t%f\n",i,sqrt(i)); }

} Output Enter a number : 5 1 1.000000 2 1.414214 3 1.732051 4 2.000000 5 2.236068

6./* Program to find the value of where X = 1 + 1/4 + 1/9 + 1/16 + 1/n2 . Y = 1 + 1/8 + 1/27 + 1/64 + 1/n3 Prompt the user to enter the value */ #include<math.h> void main() { int i,n; float x=0,y=0; printf("Enter a number :"); scanf("%d",&n); for(i=1; i<=n; i++) { x = x +(1/pow(i,2)); y = y +(1/pow(i,3)); } printf("x = %f\t y=%f",x,y); } Output Enter a number : 2 Page 33

C & Data Structures x = 1.250000 y = 1.125000

Unit II

Nested for Loop


We can also use loop within loops. In nested for loops one or more for statements are included in the body of the loop. In other words C allows multiple for loops in the nested forms. The number of iterations in this type of structure will be equal to the number of iterations in the outer loop multiplied by the number of iterations in the inner loop. 1./*Program to print prime numbers from 1 to 20 */ void main() { int i,j,flag; clrscr(); for(j=2; j<20; j++) { flag=0; for(i=2; i<j; i++) { if(j%i==0) flag++; } if(flag==0) printf("%d",i); } } Output 2 3 5 7 11 13 17 19 2./* Program to print the following pattern * ** *** */ void main() { int i,j; for(i=1; i<=3; i++) { for(j=1; j<=i; j++) { printf("*"); } printf("\n"); } } Output * ** *** 3./* Program to print the following pattern 1 12 123 1234 */ void main() { int i,j; for(i=1; i<=4; i++) { for(j=1; j<=i; j++) Page 34

C & Data Structures { printf("%d",j); } printf("\n");

Unit II

} } Output 1 12 123 1234

4./* Program to print the following pattern 4444 333 22 1 */ void main() { int i,j; for(i=4; i>=1; i--) { for(j=1; j<=i; j++) { printf("%d",i); } printf("\n"); }

} Output 4444 333 22 1

5./*Program to simulate a digital clock */ #include<dos.h> void main() { int h,m,s; clrscr(); for(h=0; h<=23; h++) { clrscr(); for(m=0; m<=59; m++) { clrscr(); for(s=0; s<=50; s++) { clrscr(); printf("hh mm ss\n%d sleep(1); } } } } Output hh mm ss 0 0 0 Page 35

%d

%d",h,m,s);

C & Data Structures

Unit II

The while Loop


Another kind of loop structure in C is the while loop. The syntax is as follows Syntax : while(test- condition) { Statements; } The test condition may be any expression. The loop statements will be executed till the condition is true i.e. the test condition is evaluated and if the condition is true, then the body of the loop is executed. When the condition becomes false the execution will be out of the loop. The block of loop may contain a single statement or a number of statements. The braces are needed only if the body of the loop contains more than one statement. However, it is a good practice to use braces even if the body of the loop contains only one statement.

Steps of while loops 1. The test condition is evaluated and if it is true, the body of the loop is executed. 2. On execution of the body, test condition is repetitively checked and if it is true the body is executed. 3. The process of execution of the body will be continue till the test condition becomes false. 4. The control is transferred out of the loop. 1./* Program to print 1 to 10 numbers */ void main() { int i=1; while(i<=10) { printf("%d ",i); i++; } } Output 1 2 3 4 5 6 7 8 9 10 2. /* Program to find the sum of digits in a given number */ void main() { int n,k,sum=0; clrscr(); printf("Enter a number :"); scanf("%d",&n); while(n>0) { k= n%10; sum = sum+k; n = n/10; } printf("sum of digits = %d",sum); } Output Enter a number : 568 Sum of digits = 19 Page 36

C & Data Structures

Unit II

3. /*Program to print the reverse of a given number */ void main() { int n,k,rev=0; clrscr(); printf("Enter a number :"); scanf("%d",&n); while(n>0) { k= n%10; rev = (rev*10)+k; n = n/10; } printf("Reverse Number = %d",rev); } Output Enter a number : 5896 Reverse Number = 6985 4. /* Program to find factorial of a given number */ void main() { int n,i,fact=1; clrscr(); printf("Enter a number :"); scanf("%d",&n); if(n==0 || n==1) fact = 1; while(n>1) { fact = fact * n; n - -; } printf("Factorial = %d",fact); } Output Enter a number : 5 Factorial = 120 5. /* Program to print Fibonacci series */ void main() { int n,i=1,fnm1=0,fnm2=1,fnm; clrscr(); printf("Enter series number :"); scanf("%d",&n); printf("Fibonacci Series : 0 1 "); while(i<=n) { fnm = fnm1 + fnm2; printf("%d ",fnm); fnm1=fnm2; fnm2=fnm; i++; } } Output Enter series number : 6 Fibonacci Series : 0 1 1 2 3 5 8 13 Page 37

C & Data Structures 6./*Program to convert binary number to equivalent decimal number*/ #include<math.h> void main() { long n; int x,y=0,p=0; printf("Enter a binary number :"); scanf("%ld",&n); while(n!=0) { x=n%10; if(x>1 || x<0) { printf("Invalid Number"); break; } y=y+x*pow(2,p); n=n/10; p++; } printf("\nEquivalent Decimal = %d",y); } Output Enter a binary number : 1100 Equivalent decimal number : 12

Unit II

The do while Loop


The syntax of do- while is as follows do { Statements; } while(condition); The difference between the while and do-while loop is in the place where the condition is to be tested. In while loops the condition is tested first and then executes the body of loop if the condition is true. Where as in the do-while, the condition is checked at the end of the loop. The do-while loop will execute at least one time even if the condition is false initially. The do-while executes until the condition becomes false. 1./*Program to print 1 to 10 numbers*/ void main() { int i=1; do { printf("%d ",i); i++; }while(i<=10); } Output 1 2 3 4 5 6 7 8 9 10 2./* Program to check whether given number is prime or not */ void main() { int i=2,n,count=0; clrscr(); printf("Enter a number :"); Page 38

C & Data Structures scanf("%d",&n); do { if(n%i==0) count++; i++; }while(i<n); if(count==0) printf("Prime Number"); else printf("Not Prime Number"); getch();

Unit II

} Ouptut Enter a number : 5 Prime Number

3. /* Program to find the perfects squares from 1 to 100 */ #include<math.h> void main() { int i=1,y; float x; clrscr(); do { x = sqrt(i); y = floor(x); if(x == y) { printf("%5d",i); } i++; }while(i<=100); } Output 1 4 9 16 25 36 49 64 81 100 Note: The do-while can be used with multiple while statement loop. The sample format of do-while with multiple while statement is as follows Syntax : do while(condition) { statements; } while(condition);

The break Statement


The keyword break allows the programmers to terminate the loop. The break skips from loop or block in which it is defined. The control then automatically goes to the first statement after the loop or block. The Page 39

C & Data Structures

Unit II

break can be associated with the conditional statements like switch. The break can be used to stop the infinite loop execution. We can also use break statements in the nested loops. If we use statement in the innermost loop then the control of the program is terminated only from the inner most loop. /*Program to print 1 to 10 numbers using break and infinite for loop */ void main() { int i=1; clrscr(); for(;;) { printf("%d ",i); i++; if(i>10) break; } } Output 1 2 3 4 5 6 7 8 9 10

The continue Statement


The continue statement is exactly opposite to break. The continue statement is used for continuing next iteration of loop statements. When it occurs in the loop it does not terminate, but it skips the statements after this statement. It is useful when we want to continue the program without executing any part of the program.

The goto Statement


The goto statement does not require any condition. This statement passes control anywhere in the program i.e. control is transferred to another part of the program without testing any condition. The user has to define goto statement as follows : goto label ; where label name must start with any character. Label is the position where the control is to be transferred.

The return Statement


The return statement transfers control from a function back to the activator of the function. For the function main, control is transferred back to the operating system. The syntax of return is as follows return expression; expression is not mandatory in the syntax. Simple return also works. /* Program to check whether given number is even or odd using goto and return */ void main() { int x; clrscr(); printf("Enter a number :"); scanf("%d",&x); if(x%2==0) goto even; else goto odd; even : Page 40

C & Data Structures printf("Even number"); return;

Unit II

odd :

printf(Odd number); } Output Enter a number : 6 Even number -o0o-

Page 41

Vous aimerez peut-être aussi