Вы находитесь на странице: 1из 68

2.

1 HISTORY OF C LANGUAGE
ALGOL was the first computer language to use a block structure. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) at University of Cambridge primarily, for writing system software. In 1970, Ken Thompson created a language using many features of BCPL and called it B. B was used to create early versions of UNIX operating system at Bell Laboratories. Both BCPL and B were type less system programming languages. The major milestones in Cs development as a language are listed in Figure 2.1.

Figure 2.1 Development of C Language C was developed by Dennis Ritchie at Bell Laboratories in 1972. It was evolved from ALGOL, BCPL, and B. C uses many concepts of these languages and new features like data types. UNIX operating system was coded almost entirely in C. To assure that the C language remains standard, in 1973, American National Standards Institute (ANSI) appointed a technical committee to define a standard for C. The committee approved a version of C in 1989 which is now known as ANSI C. It was then approved by the International standards Organization (ISO) in 1990. The standard was updated in 1999. Prior to C, there are two broad types of languages: Applications languages: Basic and COBOL, which are portable but inefficient. Systems languages: Low Level and Assembly language, which are efficient but non portable.

2.1.1 CHARACTERISTICS OF C LANGUAGE


The increasing popularity of C is due to its various features: C language is well suited for structured modular programming. Program divided in to sub modules. C is a robust language with rich set of built-in functions and operators.
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 1

Programs written in C are efficient and fast. This is due to its variety of data types. It is many times faster than BASIC. For example, if a program to increment a variable from 0 to 1000 takes about one second in C while it takes more than 30 seconds in BASIC. C is highly portable (code written in one machine can be moved to other). C is highly flexible. C allows access to the machine at bit level (using Low level bitwise programming). C supports pointer implementation. Extensive use of pointers for memory, array, structures and functions.

2.2 STRUCTURE OF A C PROGRAM


A C program can be viewed as a group of building blocks, called functions. A function is a subroutine that includes one or more statements designed to perform a specific task. Figure 2.2 show the general structure of C program. Preprocessor directives User-defined functions prototype Global declaration section main() { // Local Declarations // Executable statements } User-defined functions Figure 2.2 General Structure of C program The preprocessor directives provide instructions to the preprocessor, to include functions from the system library, to define the symbolic constants and macro. The prototype of the user-defined functions (function declaration) is specified after the preprocessor directives. The variables that are used in common by more than one function are called Global Variables and are declared in global declaration section. This section can have declarations for all the user-defined functions. Every C program must have one main() function. This function contains two parts: declaration part and executable part. The declaration part declares all the

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 2

Variables used in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing braces. The closing brace of the main function is the logical end of the program. The executable portion of the main function will have three types of statements: Input, Output and Processing statements. All the statements in the declaration and Executable parts end with a semicolon. C program can have any number of user-defined functions and they are generally placed immediately after the main () function, although they may appear in any order. All sections except the main () function may be absent when they are not required. C is a case sensitive language. Comments are enclosed within /* and */. C program can be documented using these comment lines. /************************************************ * File Name: Hello.c * * Description: Simple C Program * * Author: B V Rajesh * * Date: 17/11/10 * ************************************************/ #include<stdio.h> int main() { /* Display text on monitor */ printf(" Hello World "); /* Return a success code to the Operating System */ return 0; } /* End of Hello.c */ OUTPUT

Explanation to Example C Program #include <stdio.h> It is a directive to C preprocessor. # (pound sign) line processed by preprocessor before the program is compiled tells preprocessor to include contents of stdio.h file in the program. stdio.h standard input/output header file, Contains
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 3

information & declarations about functions. In this case, the printf library function not part of C programming language. /* comments */ Ignored by the C compiler. int main(){return 0;} int is the return type of function return 0; Returns 0 to operating system. Indicates that program executed successfully. main Every program consists of 1 or more functions. Must have a main function. {} body of function = left & right brackets (block).

2.3 CREATING AND RUNNING C PROGRAM


There are four steps in the creation and running of C program: 1. 2. 3. 4. Writing and Editing Programs Compiling Programs Linking Programs Executing Programs

Writing and Editing Programs The software used to write programs is known as a text editor. A text editor helps us enter, change, and store data. Depending on the editor on our system, we could use it to write letters, create reports, or write programs. After complete a program, we save our file to disk. This file will be input to the compiler, it is known as a source file. Always source file should be created along with filename.c extension (Example Hello.c). Compiling Programs The C program (code) in a source file stored on the disk must be translated into machine language. This job is done by the compiler. It does two separate programs: The preprocessor and translator. The preprocessor reads the source code and prepares it for the translator. While preparing the code, it scans for special instructions known as preprocessor commands. These commands tell the preprocessor to look special code libraries, make substitutions in the code, and in other ways prepare the code for translation into machine language.
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 4

Figure 2.3 Crating and running C Program After preprocessor has prepared the code for compilation, the translator does the actual work of converting the program into machine language. The translator reads the translation unit and writes the resulting object module, contains code in machine language (Hello.obj) to a file that can then be combined with other precompiled units to form the final program. Linking Programs If a source file contains library functions or functions defined in other source files, the linker combines these functions with main (), to create an executable file (Hello.exe).

2.4 C FUNDAMENTALS
Basic elements of C language constitute Character set, Identifiers, variables, keywords, and C tokens.

2.4.1 CHARACTER SET

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 5

Character set defines the characters that are used to form words, numbers and expressions. The characters in C are grouped into the following categories: 1. 2. 3. 4. Letters Digits Special Characters White spaces

Letters

Digits 0123456789 Special Characters " () * + - / : =! & $ ; < > % ? , .#@{}[]\| White Spaces Blank Space Horizontal tab carriage return new line Form Feed

2.4.2 KEYWORDS
Keywords are also known as reserve words, have standard and predefined meanings in C. These keywords can be used only for their intended purpose and they cannot be used as programmer-defined identifiers. Keywords serve as basic building blocks for program statements. All keywords must be written in lowercase. ANSI C supports 32 keywords. Table 2.1 shows the list of keywords. auto case const default double enum float goto int register short sizeof struct typedef break char else extern for if long return signed static switch union void while

unsigned continue volatile do

Table 2.1 ANSI C Keywords

2.4.3 IDENTIFIERS
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 6

Identifiers are names given to various programming elements such as variables, constants, and functions. It should start with an alphabet, followed by the combinations of alphabets and digits. No special character is allowed except underscore (_). An Identifier can be of arbitrarily long. Some implementation of C recognizes only the first 8 characters and some other recognize first 32 Characters. The following are the rules for writing identifiers in C: 1. 2. 3. 4. 5. First character must be alphabetic character or underscore. Must consist only of alphabetic characters, digits, or underscore. Should not contain any special character, or white spaces. Should not be C keywords. Case matters (that is, upper and lowercase letters). Thus, the names count and Count refer to two different identifiers.

Table 2.2 shows examples of legal and illegal C identifiers. Identifier Percent y2x5__fg7h annual profit _1990_tax savings#account double 9winter Legality Legal Legal Illegal: Contains White space Legal but not advised Illegal: Contains the illegal character # Illegal: Is a C keyword Illegal: First character is a digit 2.2 Examples of legal and illegal C identifiers

2.4.4 C TOKENS
In a passage of text, individual words and punctuation marks are called tokens. The compiler splits the program into individual units, are known as C tokens. C has six types of tokens as shown in Figure 2.4. C programs are written using these tokens and the syntax of C language.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 7

Figure 2.4 C tokens and examples For our first program (Hello.c), the tokens are shown in the Figure 2.5.

mai ( ) { printf ( "Hello World" ) ; } n


Figure 2.5 C tokens for Hello.c program

2.4.5 VARIABLES
When you want to process some information, you can save the values temporarily in variables. A variable is a data name that may be used to store a data value. The value represented by the identifier may be changed during the execution of the program. Variable names must be chosen in such a way that it should be a valid identifier satisfying all the basic conditions. Variable names are case sensitive (ex: variable EMPNAME is different from variable empname). The variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program. Rules for writing variable names are same as identifier naming rules. Examples:
Valid: sum Invalid:

student_sal 1area

tot_sec temp%

marks1 emp name

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 8

2.5 DATA TYPES


Data types are used to indicate the type of value represented or stored in a variable, the number of bytes to be reserved in memory, the range of values that can be represented in memory, and the type of operation that can be performed on a particular data value. ANSI C supports 3 categories of data types: 1. User Defined data types 2. Built-in data types 3. Derived data types Figure 2.6 shows different categories of data types.

Figure 2.6 Different Categories of Data types Built-in Data types Built-in data types are also known as primary or Fundamental or Basic or Primitive data types. C uses the following basic data types
int char float double

integer quantity character (stores a single character) single precision real (floating point) number double precision real (floating point) number

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 9

Integer Data Type Integers are whole numbers with a range of values supported by a particular machine. The keyword int is used to specify an integer variable. Generally integer occupy one word of storage, and since the word sizes if machine vary(typically, 16 or 32 bits) the size of an integer that can be stored depends on the computer. 16-bit integer can have values in the range of - 32768 to 32767 (-2^15 to 2^15-1). One bit is used for sign. For 32-bit integer can have values in the range of -2147483648 to 2147483647. Character Data Type The shortest data type is character. The keyword char is used to declare a variable of a character type. It is stored in 1 byte in memory. Corresponding integer values for all characters are defined in ASCII code (American Standard Code for Information Interchange). For example, character constant a has an int value 97, b - 98, A - 65 etc. Character can have values in the range of -128 to 127. The floating Point Data Type The data type float represents a floating point number (also called a real number). The keyword float is used to declare a variable of the type float. The float type variable is usually stored in 32 bits, with 6 digits of precision. float can have values in the range of 3.4E-38 to 3.4 E+38. The double Data Type A floating point number can also be represented by the double data type. The data type double is stored on most machines in 8 bytes which is about 15 decimal places of accuracy. To declare a variable of the type double, use the keyword double. double can have values in the range of 1.7E-308 to +1.7E+308. Void Data type Defines an empty data type which can then be associated with some data types. It is useful with pointers.
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 10

Big and small numbers Scientific notation is often used to write a big or small numbers. A number is written as the combination of the mantissa, which is followed by the prefix e or E, and the exponent. For example, 87000000 = 8.7e7 - 550 = -5.5e2 0.00000000031 = 3.1e-10. Note: float and double data types are used to store fractional values. The difference between float and double is in terms of the precision. Type Modifiers The basic data types may have various modifiers (or qualifiers) preceding them, except type void. A modifier is used to alter the meaning of the base data type to fit the needs of various situations more precisely. The list of modifier is given below.

The modifiers signed, unsigned, long short may be applied to integer base types. We can apply unsigned and signed to characters. Long may also be applied to double. The difference between signed and unsigned integers is in the way highorder bit (sign bit) of the integer is interpreted. If sign bit is 0, then the number is positive; if it is 1, then the number is negative. Table 2.3 shows the different data types, number of bytes occupied by then and the range. Data Type unsigned char signed char Meaning unsigned character(positive) represents single character Size (in Bytes) 1 1 0 to 255 -128 to 127 Range

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 11

Data Type

Meaning

Size (in Bytes) 2

Range 0 to 65,535

unsigned int represents positive unsigned integer numbers short int short represents both positive signed short and negative integer short int quantity signed short int int unsigned long long signed long long int signed long int float double long double void represents positive long integer represents both positive and negative long numbers

-32,768 to 32,767

4 4

0 to 4,294,967,395 -2,147,483,648 to 2,147,483,647

floating point number A more accurate floating point number than float increases the size of double defines an empty data type.

4 8 10

3.4*(10-38) to3.4*(10+38) 1.7*(10-308) to1.7*(10+308) 3.4*(10-4932) to3.4*(10+4932)

Table 2.3 Data types with Size and Range Derived Data Types and User Defined data types are the combination of primitive data types. They are used to represent a collection of data. They are: Arrays Structures Unions Enumerated Pointers

Note: Number of bytes and range given to each data type is platform dependent.

2.6 VARIABLE DECLARATIONS


B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 12

All variables must be declared before they are used. It specifies two things: 1. It tells the compiler what the variable name used in the program. 2. It specifies what type of data that the variable can hold. General syntax for declaring variables is as follows:
data_type var1, var2,,varn;

data_type specifies the type of value the variable holds in it. var1, var2varn are the names of variables. Variables are separated by comma. A declaration statement must end with semicolon. Example, valid variable declarations: int i, j, k; // Declares variables i, j and k of type integer

float x, y, z; // Declares variables x, y and z of type float char ch; // Declares variable ch of type character

2.6.1 VARIABLE INITIALIZATION


Variables can be initialized in three ways: 1. declaration statement itself. 2. within the program using assignment statement. 3. Using input functions like scanf etc.., General Form for assigning values at the time of declaration is as follows:
[data _type] variable name = value;

Examples, int total=0, ct=1; float sum = 0.0; char ch=A; Using assignment statement it consists of the following form: var_name=constant; Examples,
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 13

tot =0; // tot is assigned with a value 0 bonus=100; // bonus is assigned with a value 100 Note: Assigning values using input functions will be discussed later.

2.7 CONSTANTS
A constant in C refers to the fixed values that do not change during the execution of a program. Like variables constants have a data type.

2.7.1 CONSTANT REPRESENTATION


C supports several representations (or types) of constants as shown in Figure 2.7.

Figure 2.7 Basic types of Constants with examples Integer Constants An integer constant refers to a sequence of digits. If we code the number as a series of digits, its type is signed integer, or long integer if the number is large. We can override this default by specifying unsigned (u or U), and long (l or L), after the number. There is no way to specify a short int constant. Table 2.4 shows several examples of integer constants.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 14

Embedded spaces, commas, and non-digit characters are not permitted between digits. For example, 12 345 Are illegal integers. Representation +123 -378 -32271L 76542LU Value 123 -378 -32,271 76,542 Type int int long int unsigned long unit 10,000 $1000

Table 2.4 Examples of Integer Constants Real Constants The default form for real constants is double. If we want the resulting data type to be float or long double, we must use a code to specify the desired data types. to represent float value we can use f or F , l and L are used to represent long double. Table 2.5 shows several examples of real constants. Representation 0. .0 2.0 3.1416 -2.of 3.1415926536L Value 0.0 0.0 2.0 3.1416 -2.0 3.1415926536 Type double double double double float long double

Table 2.5 Examples of Real Constants Single Character Constants A single character constant (or character constant) contains a single character enclosed between two single quote marks. Character constants have integer values known as ASCII values. Examples of character constants are:
a 5 S

Note that the character constant 9 is not the same as the number 9.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 15

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. Examples are: April 1984 David A

Note that a character constant x is not equals to the string X. Escape Characters If a character precedes with a \ (backslash) it is called escape character (or backslashed characters or control characters). It conveys a special meaning to the printf () function other than the normal character it represents. A list of escape characters is given in table 2.6. Escape Sequence \b \t \n \v \f \r \\ \ \ \o \c \a Description Back Space (Horizontal) Tab New line feed (LF) Vertical Tab Form Feed Carriage Return (CR) Back Slash (Solidus) Single quote (grave accent) Double quote null (C string terminator) null (Empty) string continuation (UNIX) Alert (beep sound) Table 2.6 Escape characters in C

2.7.2 CODING CONSTANTS


There are three different ways we can code (or use) constants in our programs: literal constants, defined constants, and memory constants.

Literal Constants
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 16

A literal is an unnamed constant used to specify data. If we know that the data cannot change, then we can simply code the data value itself in a statement. For example 10 is used in the following statement. Sum=a+10; Defined constants Another way to use a constant is to use the preprocessor command define. Like all preprocessor commands, it is prefaced with the pound sign (#). The defined constant contains the following form:
#define identifier value

Examples, #define pi 3.14 #define max 10 Memory Constants The third way to use constant is with memory constants. Memory constants use a C const keyword, to indicate that the data cannot be changed. The general form:
const data_type identifier=value;

// defines pi with 3.14 // defines max with 10

Here the value of the identifier cannot be changed in the program. Examples, /**************************************************** const int max=10; * Name: Const.c * const float pi=3.14; * Author: B V Rajesh * * Date: 18/11/10 * * Description: a program demonstrating constants usage * ****************************************************/ #include<stdio.h> #define PI 3.14 void main() { /* Variable Declaration */ const float val=3.14; /* Display Values */ printf("\n Literal Constant = %f",3.14); printf("\n Defined constant = %f", PI*3.14); printf("\n Memory Constant = %f",3.14*PI*val);
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 17

/* keep console screen until a key stroke */ getch();

OUTPUT

2.8 INPUT/OUTPUT STATEMENTS


Reading, processing, and printing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known as information or results/ So far we have seen two methods of providing data to the program variables. One method is to assign values to variables through the assignment statements such as n=10; a=5; and so on. Another method is to use the input functions. All the input/output operatios are carried out through functions defined in standard input output library (stdio.h). There are two types of Input and Output (I/O) statements: Unformatted I/O statements and Formatted I/O statements. We will discuss later Unformatted I/O.

Formatted I/O Statements


B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 18

Formatted input/output refers to an input data that has been arranged in a particular format.

2.8.1 FORMATTED INPUT FUNCTION


scanf() function is used to read formatted data values. For example consider the following data: 56.78 123 c

This line contains three pieces of data, arranged in a particular form. Such data has to be read conforming to the format of its appearance. For example, the first part of the data should be read into a variable float, the second into int, the third part into char. This is possible by using scanf function. General Form:
scanf (format control string, &var1, &var2&varn);

The format Control string is a listing of the data types of the variables to be input and the & in front of each variable name tells the system Where to store the value that is input. Format control string and variables are separated by comma. Format control string, also known as control string contains field specifications (or format specifier), which directs the interpretation of input data. It consist of the following form: %code (type-specifier) The percent sign (%) indicates that a conversion specification follows, code specifies data type. By default, the delimiter while reading the values is space. Delimiter can be user-defined. Format specifications contained in the format control string, must match the variable list in order. Input data values must be separated by spaces and must match the variables receiving the input in the same order. To read a string using %s, & need not be used. The format specifers for different data types shown in Table 2.7. 2.8.2 FORMATTED OUTPUT FUNCTION
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 19

printf() function is used to output the values. This function returns the number of characters printed. General Form:
printf (format control string, var1,var2varn);

Format Control String Consist of three types of things: 1. Characters that will be printed on the screen as they appear. 2. Format specifications that define the output format for display of each value. 3. Escape sequence characters such as \n,\t.., The format control string indicates how many arguments follow and what their types are. var1, var2varn are the variables whose values are formatted and printed according to the specifications of the control string. The arguments should match in number, order and type with the format specifications. Format Conversion Specifiers Table 2.7 shows Format Specifiers for different data types in C. Data Type char signed char unsigned char int signed int unsigned int short short int signed short int unsigned short int long int signed long int Format Specifier %c Meaning displays a single character

%d , %i %u %h %hd , %hi %hu %ld , %li

a decimal (base 10) integer unsigned decimal integer short integer short integer unsigned decimal integer long integer unsigned long decimal integer Meaning

unsigned long %lu int Data Type Format Specifier

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 20

float

%e %f %g

a floating point value in exponential notation a floating point value a number in either "e" or "f" format double precision value long double precision value displays a string of characters a hexadecimal integer an octal integer

Double long double

%lf, %le, %lg %Lf, %Le, %Lg %s %x %o

Table 2.7 Format Specifiers for different data types Examples, printf (char=%c, int=%d, floating point=%f ,ch, i, x); printf (sum = %f, sum);

/****************************************************** * Filename : Demo.c * * Author : B V Rajesh * * Date : 30/11/10 * * Description : program demonstrates Reading Data * * * ******************************************************/ #include<stdio.h> */ /* Read Values printf("\n Enter a character : "); void main() scanf("%c",&c); { printf("\n Enter a integer : "); scanf("%d",&i); /* variable declaration : "); printf("\n Enter a float */ char c; scanf("%f",&f); int i; float f; /* Display values */ printf("\n The Given character is %c",c); printf("\n The value of i= %d",i); printf("\n The value of f= %f",f); /* keep console screen until a key stroke */ getch(); B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 21 }

OUTPUT

printf (name = %c, name);

2.9 OPERATORS
C supports a rich set of operators. An operator is a symbol that tells the computer to perform mathematical or logical operations. Operators are used in C to operate on data and variables. C operators can be classified into a number of categories. They include: 1. 2. 3. 4. 5. 6. 7. 8. Arithmetic Operators Relational Operators Logical Operators Assignment Operators Increment & decrement Operators Conditional Operators Bitwise Operators Special Operators

2.9.1 ARITHMETIC OPERATORS


C provides all basic arithmetic operators which are work in the same way as they do in other languages. It can operator any built in data type allowed in C. Table 2.8 shows different types of arithmetic operators in C. C Operation Addition Binary Operator + C Expression a+b

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 22

Subtraction Multiplication

a-b a*b a/b a%b

Division(second operand must be / nonzero) Modulus (Remainder both % operands must be integer and second operand must be non zero) Table 2.8 Arithmetic Operators Integer arithmetic:

When both operands in a single arithmetic expression such as a+b are integer the expression is called integer expression. The integer arithmetic always yields an integer value. Integer division truncates any fractional part. Let a=14,b=4 Then a+b a-b a*b a/b a%b = = = = = 14+4 14-4 14* 4 14/4 14%4 = = = = = 18 10 56 3 3

(truncates fraction part) (remainder after division)

Floating point arithmetic When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands. Let x = 14.0 and y = 4.0 then x + y = 18.0 x y = 10.0 x * y = 56.0 x / y = 3.50 Mixed mode arithmetic When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic.
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 23

If anyone operand is of real type then the result will always be real thus 15/10.0 = 1.5. /********************************************************** * Filename : Arithmetic.c * * Author : B V Rajesh * * Date : 20/11/10 * * Description : a program demonstrates C arithmetic operators * ***********************************************************/ #include <stdio.h> void main() { /* Variable declaration & initializations */ int x = 10, y = 20 ,remainder = 0; /* display values of x and y */ printf("x = %d\n y=%d",x,y); /* demonstrate = operator + */ y = y + x; printf("y = y + x; y = %d\n",y); /* demonstrate - operator */ y = y - 2; printf("y = y - 2; y = %d\n",y); /* demonstrate * operator */ y = y * 5; printf("y = y * 5; y = %d\n",y); /* demonstrate / operator */ y = y / 5; printf("y = y / 5; y = %d\n",y); /* demonstrate modulus operator % */ remainder = y %3; printf("remainder = y %% 3; remainder = %d\n",remainder); /* keep console screen until a key stroke */ getch(); } OUTPUT

2.9.2 RELATIONAL OPERATORS


We often compare two quantities and depending on their relation take certain decision. Comparing the age of two people, price of two items.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 24

An expression containing relational operator termed as relational expression. A simple relational expression contains only one relational operator and takes the following form:
exp1 relational_operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. The value of relational expression is either 1 or 0. If It is 1 the specified relational is true and 0 If the specified relation is false. Given below is a list of examples of relational expressions and evaluated values. 6.5<= 25 TRUE -65 > 0 FALSE 10 < 7 + 5 TRUE Relational expressions are used in decision making statements of C /********************************************************** language : as if, while * Filename suchRelational.c and for statements to decide the course of * action of a running program. * Author : B V Rajesh * Date Different types 20/11/10 Operators and equality operators are listed in* of Relational * : Table 2.9 and 2.10. * Description : a program demonstrates C Relational operators * * * C operation Relational Operator C expression **********************************************************/ #include <stdio.h> greater than > x >y voidless than main() { greater than or equal to < >= x<y x >= y

less than or equal to <= x <= y /* Variable Declaration */ int i, j; Table 2.9 Relational Operators /* Read the values of i and j */ printf("Enter i: "); C operation Equality Operator C expression scanf("%d", &i); Equality x == y printf("\nEnter j: "); == scanf("%d", &j); not equal != x != y /* relational operations */ Table 2.10 Equality Operators printf("i > j %d\n", i > j); printf("i < j %d\n", i < j); printf("i >= j %d\n", i >= j); printf("i <= j %d\n", i <= j); printf("i == j %d\n", i == j); printf("i != j %d\n", i != j); /* keep console screen until a key stroke */ B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 25 getch(); }

OUTPUT

2.9.3 LOGICAL OPERATORS


Used to combine more than one relational test into a compound relational test. The logical operators are used if we want to test more than one condition and make decision. The first two (&&, ||) never appear by themselves (always go between relational tests). Truth Tables show you how to achieve results from an if statement that uses these operators. Table 2.11 shows different categories of logical operators. Operator Meaning && || Logical AND (true only if both the operands are true) Logical OR (true if either one operand is true)

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 26

Logical NOT (negate the operand) Table 2.11 logical operators

Logical AND (&&) This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true (1), otherwise false (0). Table 2.12 shows the truth table of Logical And (&&).
A B A&&B A||B

0 0 1 1

0 1 0 1

0 0 0 1

0 1 1 1

/***************************************************** Table 2.12 Truth table for Logical And, Logical OR * Filename : Logical.c * Logical OR (||)* Author : B V Rajesh * * Date : 20/11/10 * The logical OR is used to combine 2 expressions or the condition * Description : a program demonstrates C Logical operators * evaluates to true if any one of the 2 expressions is true. Table 2.12 shows * * the truth*****************************************************/ table of Logical OR(||). Logical NOT (!) #include <stdio.h> The logical not operator takes single expression and evaluates to true if void main() the expression is false and evaluates to false if the expression is true. In { other words it just reverses the value of the expression. /* Variable Declaration */ int a, b; A !A 0 /* Read the values of 1 and b */ a printf("Enter a: "); 1 0 scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); /* logical operations */ printf("a && b %d\n", a && b); printf("a || b %d\n", a || b); printf("!a !b %d %d\n", !a, !b); getch(); }

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 27

/* keep console screen until a key stroke */

OUTPUT

2.9.4 ASSIGNMENT OPERATORS


Assignment Operators are used to assign the result of an expression to a variable. Assignment operator can be used in three ways. Single assignment consists of the form a = 4; Multiple assignment used for variable initialization a=b=c=d=0; Compound assignment: Assignment operators are used to combine the = operator with one of the binary arithmetic operators. Table 2.13 shows examples of compound assignment. Example, salary = salary + 1000; salary += 1000; //is the same as above Operator += -= *= /= %= Example c += 7 c -= 8 c *= 10 c /= 5 c %= 5 Equivalent Statement c=c+7 c=c-8 c = c * 10 c=c/5 c=c%5

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 28

Table 2.13 Compound Assignment in C /****************************************************** * Filename : Assignment.c * * Author : B V Rajesh * * Date : 20/11/10 * * Description: a program demonstrates C Assignment operator * * * *******************************************************/ #include <stdio.h> void main() { /* Variable declaration */ int x = 10; /* demonstrate = operator */ int y = x; printf("y = %d\n",y); /* demonstrate += operator */ y += 10; printf("y += 10;y = %d\n",y); /* demonstrate -= operator */ y -=5; printf("y -=5;y = %d\n",y); /* demonstrate *= operator */ y *=4; printf("y *=4;y = %d\n",y);

/* demonstrate /= operator */ y /=2; printf("y /=2;y = %d\n",y); /* keep console screen until a key stroke */ getch(); }

OUTPUT

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 29

2.9.5 THE INCREMENT AND DECREMENT OPERATORS


We can add or subtract 1 to or from variables by using increment (++) and decrement (--) operators. Te operator ++ adds 1 to the operand and the operator subtracts 1. They can go on either side of the modified variable. They can apply in two ways postfix and prefix. Prefix form: variable is changed before expression is evaluated Postfix form: variable is changed after expression is evaluated. We can use increment and decrement operators in loops. Table 2.14 shows the working of increment and decrement operator. Operator ++ ++ --Example i++ ++i i---i Meaning postfix prefix postfix prefix Equivalent Statements i=i+1; i=i+1; i=i-1; i=i-1; i+=1; i+=1; i -=1; i-=1;

Table 2.14 Working of Increment and Decrement Operators /******************************************************** * Filename : Increment.c * * Author : B V Rajesh * * Date : 20/11/10 * * Description: demonstrates increment and Decrement operators * * * ********************************************************/ #include <stdio.h> /* Increment operator */ void main () printf("Postfix increment %d\n", a++); { printf("Now a is %d\n", a); /* Variable Declaration */ %d\n", ++a); printf("Prefix increment int printf("Nowresult; a=4, b=5, a is %d\n", a); /* Decrement Operator */ printf("Postfix decrement %d\n", b--); printf("Now b is %d\n", b); printf("Prefix decrement %d\n", --b); printf("Now b is %d\n", b);
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 30

/* keep console screen until a key stroke */ getch();

2.9.6 THE CONDITIONAL OPERATOR


Cs only conditional (or ternary) operator requires three operands (as opposed to the unarys single and the binarys double operand requirement). A ternary operator pair ? in C used to construct conditional expression. Syntax :
conditional_expression? expression1: expression2;

The conditional_expression is any expression that results in a True (nonzero) or false (zero) answer. If True expression1 executes, otherwise expression2 executes. Example: sales > 1000)? Bonus = 500: Bonus = 0; (a > b)? (ans = 10): (ans = 25); ans = (a > b)? (10): (25); /******************************************************* * Filename : Ternary.c * * Author : B V Rajesh * * Date : 20/11/10 * * Description: a program demonstrates C conditional operator * *******************************************************/ #include<stdio.h> void main() /* Read the values of a and b */ { printf(" EnterDeclaration of a: "); /* Variable the values */ scanf("%d",&a); int a,b,max; printf(" Enter the values of b: "); scanf("%d",&b); max=(a>b) ? a : b ; printf("\n Max=%d", max);
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 31

OUTPUT

/* keep console screen until a key stroke */ getch();

2.9.7 BITWISE OPERATORS


C has a special operator known as Bitwise operator for manipulation of data at bit level. These operators are used for testing the bits or shifting them right or left. Bitwise operator may not be applied for float and double. Table 2.15 shows different categories of Bitwise Operators. Operator & | ^ << >> ~ Meaning Bitwise AND Bitwise OR Bitwise exclusive OR Shift left Shift right ones complement

Table 2.15 Different Categories of Bitwise Operators Bitwise and Operator (&) It is a binary operator it requires two integral operands. It does a bit-by-bit comparison between the operands. The result of the comparison is 1 only when both bits are 1. It is 0 otherwise. Truth Table is shown in table 2.16. Let us consider two variables a and b whose values are 10 and 20, then a & b bit by bit comparisons are shown below:

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 32

a&b results in decimal value 0.


A B A&B A|B A^B

0 0 1 1

0 1 0 1

0 0 0 1

0 1 1 1

0 1 1 0

Table 2.16 Truth Tables for Bitwise And, Inclusive OR, Exclusive OR Bitwise Inclusive OR Operator (|) It is a binary operator it requires two integral operands. It does a bit-by-bit comparison between the operands. The result of the comparison is 0 when both bits are 0.it is 1 otherwise. Truth Table is shown in table 2.16. Let us consider two variables a and b whose values are 10 and 20, then a | b bit by bit comparisons are shown below:

a|b results in decimal number 30. Bitwise Exclusive or Operator (^) It is a binary operator it requires two integral operands. It does a bit-by-bit comparison between the operands. The result of the comparison is 1 when only one operand is 1.it is 0 other wise. Truth Table is shown in table 2.16. Let us consider two variables a and b whose values are 10 and 20, the a ^ b bit by bit comparisons are shown below:

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 33

a^ b results in decimal number 30. Ones Complement Operator (~) It is a unary operator applied to integral values. It complements the bits in the operand, which is reverse bit value. Check sum used when detecting receiving bits are valid or not. Truth Table is shown below.
A !A

0 1 Shift Operators

1 0

The shift operators move bits to the right or left, for this purpose we have two categories: Bitwise Shift-Right Operator (>>), Bitwise Shift-Left Operator (<<). Bitwise Shift-Right Operator (>>) It is a binary Operator that requires two integral operands. the first one is value to be shifted. the second one specifies number of bits to be shifted. The general form is as follows:
Variable >> expression;

When bits are shifted right, the bits at the rightmost end are deleted. The shift right operation is shown in Figure 2.8. Example, a=8; b=a>>1; // assigns 4 after shift right operation

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 34

Figure 2.8 Shift-right Operation Shift right operator divides by a power of 2. I.e a>>n results in a/2n. where n is number of bits to be shifted. Bitwise shift Left Operator (<<) It is a binary Operator that requires two integral operands. the first one is value to be shifted.the second one specifies number of bits to be shifted. When bits are shifted left, the bits at the leftmost end are deleted. The shift left operation is shown in Figure 2.9. Example, a=8; b=a<<1; // assigns 16 after left shift operation

Figure 2.9 Shift-right Operation Shift left operator multiply by a power of 2, a<<n results in a*2 n. Where n is number of bits to be shifted.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 35

/**************************************************************** * Filename : Bits.c * * Author : B V Rajesh * * Date : 20/11/10 * * Description: program a demonstration of C bitwise operators * * * ****************************************************************/ #include <stdio.h> void main() { /* Variable Declaration */ int d1 = 10; /* 01010 */ int d2 = 20; /* 10100 */ int d3; /* Display values of d1 and d2 */ printf("\nd1=%d",d1); printf("\nd2=%d",d2); d3 = d1 & d2; /* 01010 & 10100 = 00000 */ printf("\n Bitwise AND d1 & d2 = %d",d3); d3 = d1 | d2; /* 01010 | 10100 = 11110 */ printf("\n Bitwise OR d1 | d2 = %d",d3); d3 = d1 ^ d2;/* 01010 ^ 10100 = 11110 (=30) */ printf("\n Bitwise XOR d1 ^ d2 = %d",d3); d3 = ~d1; /* ones complement of 1010 is 1111 0101 (-11) */ printf("\n Ones complement of d1 = %d",d3); d3 = d1<<2; /* 0000 1010 left shift by 2 bits is 0010 1000 (40) */ printf("\n Left shift by 2 bits d1 << 2 = %d",d3); d3 = d1>>2; /* 0000 0101 right shift by 2 bits is 0000 0010 (2) */ printf("\n Right shift by 2 bits d1 >> 2 = %d",d3); /* keep console screen until a key stroke */ getch(); } OUTPUT

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 36

2.9.8 SPECIAL OPERATORS


C supports the following special category of operators. & * , sizeof() . And Address operator Indirection operator Comma operator Size of operator Member selection Operators

comma Operator It doesnt operate on data but allows more than one expression to appear on the same line, e.g. int i = 10, j = 20; Is used to separate arguments in Input/output function calls, e.g. printf (%d %.2f %c, an integer, a float, a char); The comma allows some interesting statements. Example, i = 10; //i is assigned the value 10 j = (i = 12, i + 8); //i is assigned 12 added to 8 produces 20 Comma operator is used in Functions arguments separating. The size of Operator Is a unary operator (operates on a single value). Produces a result that represent the size in bytes or the data specified format size of data. Example: int a = 5; sizeof a; //produces 2
Directly applied to data type name also, syntax as follows: sizeof(data type)

example, sizeof(char); // produces 1 sizeof(int); // produces 2

2.10 EXPRESSIONS
An expression is a sequence of operands and operators that reduces to a single value. Figure 2.10 shows different categories of expressions in C.
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 37

Figure 2.10 Different Categories of Expressions Primary Expressions The most elementary type of expression is a primary expression. It consists of only one operand with no operator. In C, the operand in the primary expression can be a name, a constant, or a parenthesized expression. Name is any identifier for a variable, a function, or any other object in the language. The following are examples of some used as primary expressions: a price sum max

Literal Constants is a piece of data whose value cant change during the execution of the program. The following are examples of literal constants used in primary expression: A 56 98 12.34

Any value enclosed in parentheses must be reduced in a single value is called as primary expression. The following are example of parentheses expression: (a*x + b) Postfix Expression The postfix expression consists of one operand followed by one operator. The general syntax as follows: operand (variable) operator The postfix Increment and decrement will increase or decrease the value of variable by 1. The value of postfix increment expression is determined before the variable is increased. Figure 2.11 illustrates the working of postfix increment. (a-b*c) (x+90)

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 38

Figure 2.11 Working of Postfix Expression Prefix Expression In prefix expression, the operator comes before the operand. The general syntax as follows:

operator operand (variable)


The prefix Increment and decrement will increase or decrease the value of variable by 1. The value of variable is increased before prefix increment expression is determined. Figure 2.12 illustrates the working of prefix increment.

Figure 2.12 Working of Postfix Expression Unary Expression A unary expression, like a prefix expression, consists of one operator and one operand. The operator comes before the operand. A Unary operator comes in two forms: Unary plus (+), Unary Minus (-). Some of the examples of unary expressions are shown in Table 2.17.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 39

Table: 2.17 Examples of Unary Expression Binary Expression Binary expressions are formed by an operator operand combination. They are perhaps the comst common expression category. Any two numbers added, subtracted etc..,. It takes of the form:

Examples: a+b Assignment Statement Assignment statement is used to assign a value to a variable. In C, the assignment operator is =. The left side of the = is always a variable, whose address specifies where to store the data on the right side. For example, the statement x = y + z; computes the value of y+z and store the result in the variable x. However, x + 3 = y; is not legal because x + 3 is an arithmetic expression (i.e.) not a storage location. a*b + c a-b

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 40

2.11 OPERATOR PRECEDENCE AND ASSOCIATIVITY


Operator Precedence Defines the order in which operators are applied. The order is not defined explicitly by the language, Inferred from the syntax definition. Precedence is applied before Associativity to determine the order in which expressions are evaluated. Associativity is then applied, if necessary. Parentheses have highest precedence. The order of evaluation can be changed by introducing parentheses into an expression. Table 2.18 shows the precedence level of different operators. Operator Associativity Associativity is used to determine the order in which operators with same precedence are evaluated in an expression. Associativity can be left-to-right or right-to-left. Left-to-right Associativity evaluates the expression by proceeding from the Left to Right as shown in Figure 2.13. Right-to-left evaluates the expression by proceeding from the right to left as shown in Figure 2.14. Unary and assignment operators are right-to-left associative. All other operators are left-to-right associative.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 41

Table 2.18 Precedence and Associativity of Operators in C

2.12 TYPE CASTING IN C


C provides a mechanism for allowing the programmer to change the default data type of a given expression. This is called Typecasting. Typecasting allows a variable to behave like a variable of another type. C provides two types of type conversions: Implicit and Explicit type conversions. Implicit type conversion
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 42

In implicit type conversion, if the operands of an expression are of different types, the lower data type is automatically converted to the higher data type before the operation evaluation. The result of the expression will be of higher data type. The final result of an expression is converted to the type of the variable on the LHS of the assignment statement, before assigning the value to it. Examples, char c = 'a'; int i; i = c; /* i is assigned by the ascii of a */ int i = 5 , j = 1; float x = 1.0, y; y = x / i; y = j / i;

/* y = 1.0 / 5.0 */ /* y = 1 / 5 so y = 0 */

The C compiler uses the following rules to promote the types if two operands do not agree in expressions.

Figure 2.15 C Promotion Rules Explicit type conversion


B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 43

In explicit type conversion, the user has to enforce the compiler to convert one data type to another data type by using typecasting operator. This method of typecasting is done by prefixing the variable name with the data type enclosed within parenthesis. The original value of the variable is not altered. General form:
(data_type) expression (data_type) can be any valid C data type and expression is any variable, constant

or a combination of both. Example, float sum; sum = (int) (1.5 * 3.8); The typecast (int) tells the C compiler to interpret the result of (1.5 * 3.8) as the integer 5, instead of 5.7. Then, 5.0 will be stored in sum, because the variable sum is of type float. Note: Type casting is allowed in expressions only. /**************************************************************** * Filename : Bits.c * * Author : B V Rajesh * * Date * /* Display : 30/11/10 */ given values * Description: a demonstration of C bitwise operators * printf("\n c=%c",c); * * printf("\n a=%d b=%d", a, b); ****************************************************************/ printf("\n x=%g y=%g", x, y); #include<stdio.h> implicit type conversion */ /* illustrating printf("\n\n %d", c*a); void main() printf("\n %lf", a*x); { /* /* illustrates explicit & Initialization */ Variable Declaration type conversion */ char c='z'; z=(double)(a/b); int printf("\n\n (double)(a/b)=%f", z); a=100, b=45; double x=100.0, y=45.0; double z; z=(double)a/b; printf("\n (double)(a/b)=%f", z); c=(char)(x/y); printf("\n (char)(x/y)=%d", c); /* keep console screen until a key stroke */ B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 44 getch(); }

OUTPUT

2.13 STATEMENTS
A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions. You may have noticed that we have used a semicolon at the end of the statements in our programs. Most statements need a semicolon at the end; some do not. Different types of statements in C are shown in Figure 2.16. An expression terminated by a semicolon (;) is termed to be a simple statement (or expression statement). Compound statements are used to group the statements into a single executable unit. It consists of one or more individual statements enclosed within the braces { }. Return statement returns 0 to operating system on successful execution of the program.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 45

Figure 2.16 Types of Statements in C

2.14 CONTROL STRUCTURES IN C


Control Structures control the flow of execution in a program or function. The basic programming control structures are sequence, selection, and iteration (looping). In a sequence structure, the instructions are executed in the same order in which they appear in the program. A program, which consists of declaration statements, input-output statements, and one or more simple expression statements, is executed in a sequential manner. In a selection structure, the control flow can be altered by evaluating conditions. In an iterative structure, a group of instructions is executed repeatedly, until some condition is satisfied.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 46

Selection Statements Selection (or Decision making) statements are used to alter the normal sequential flow of control. It provides the ability to decide the order of execution. The following are the selection statements available in C: 1. if statement 2. Conditional / Ternary operator statement (? :) 3. switch statement

2.15 IF STATEMENT
The if statement, allows us to establish decision-making in the programs. Programs may require certain logical tests condition) to be carried out at some particular points. Depending on the result of the expression the statements are executed. Condition Condition is an expression that is either false (represented by 0) or true (represented by 1). Conditions may contain relational or equality operators, and have the following forms. Variable relational-operator variable (or constant) Variable equality-operator variable (or constant) The if statement has four basic forms: Simple if statement if.else statement Nested if else statement else if ladder

2.15.1 SIMPLE IF STATEMENT


The general form of a simple if statement is if (condition) { statement-block; }

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 47

Figure 2.17 Flowchart of simple if statement Following are the properties of an if statement: 1. If the condition is true then the statement block will be executed. 2. If the condition is false it does not do anything. 3. The condition is given in parentheses and must be evaluated as true (nonzero value) or false (zero value). 4. If a compound statement is provided, it must be enclosed in opening and closing braces. Consider the following segment of a program that is written for swapping the contents of two numbers. int num1=20,temp; int num2=40; if(num1>num2) { temp=num1; num1=num2; num2=temp; } printf(\n Hello ); The program test the condition num1>num2. If num1 greater than num2 the swapping occurs. For otherwise, proceed next statement printing hello on monitor.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 48

/ ************************************************************* **** Name: Div.c * * Author: B V Rajesh * * Date: 22/11/10 * * Description: a program demonstrating simple if statement * ***********************************************************/ #include<stdio.h> void main() OUTPUT1 { /* Variable declaration */ float a, b, c; /* Read the values of a and b */ printf("\n Enter the value of a and b: "); scanf("%f%f", &a, &b); if(b!=0) { c=a/b; printf(\n c=%f, c); } printf("\n hi "); /* keep console screen until a key stroke */ getch(); } OUTPUT2

2.15.2 THE IF ELSE STATEMENT


An else clause can be added to an if statement to make an if-else statement. The general form is

if(condition) { statements1; } else { statements2; }


Figure 2.18 Flowchart of ifelse statement
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 49

Following are the properties of an ifelse statement: 1. If the condition is true then the true statement block will be executed. 2. If the condition is false then false statement block got executed. 3. The condition is given in parentheses and must be evaluated as true (nonzero value) or false (zero value). 4. If a compound statement is provided, it must be enclosed in opening and closing braces. / ***************************************************************** Name: Even.c * * Author: B V Rajesh ** Date: 22/11/10 ** Description: a program demonstrating simple if else statement * ****************************************************************/ #include<stdio.h> void main() { /* Variable declaration */ int num; /* Read number */ printf("\n Enter a number : "); scanf("%d", &num); if(num%2==0) { printf("\n The Given number %d is Even",num); } OUTPUT2 else { printf("\n The Given number %d is Odd",num); } /* keep console screen until a key stroke */ getch(); }
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 50

OUTPUT1

2.15.3 NESTING OF IF ELSE STATEMENTS


When a series of decisions are involved, we may have to use more than one if else statement in the nested form as follows:

Figure 2.19 Flowchart on nested if else statements Nested if / else structures test for multiple cases by placing if / else structures inside other if / else structures. / ************************************************************ Name: Even.c * * Author: B V Rajesh * * Date: 22/11/10 * * Description: a program demonstrating simple if else statement * ***********************************************************/ #include<stdio.h> void main() { /* Variable declaration */ int i,j,k; /* Read values */ printf("\n Enter the values of a,b and c : "); scanf(%d%d%d",&a,&b,&c);
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 51

if(i > j) { if (i > k) printf(\nmax=%d, i); else printf(\nmax =%d, k); } else { if(j>k) printf(\nmax =%d,j); else printf(\nmax =%d,k); }

OUTPUT Enter the values of a, b and c : 20 49 10 max=49

/* keep console screen until a key stroke */ getch(); }

2.15.4 THE ELSE IF LADDER


There is another way of putting ifs together when multiple decisions are involved. A multipath decision is a chain of ifs in which the statement associated with each else is an if. It takes the following general form: if (condition1) statements1; else if (condition2) statements2; else if(conditionn) statementsn; else default_statement; statement x; The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statementx) skipping the rest of the ladder). When all n conditions become false, final else containing default_statement will be executed. Figure 2.20 shows the flowchart of else if ladder.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 52

Figure 2.20 Flowchart of else if ladder

/*********************************************************** * Filename : Arithmetic.c * * Author : B V Rajesh * * Date : 20/11/10 * * Description : a program demonstrates working of else if ladder * * * * **********************************************************/ #include<stdio.h> void main() { /* variable declaration */ int a, b, c; int D; /* read values */ printf("\n Enter the values of a,b and c: "); scanf("%d%d%d",&a,&b,&c); /* find descriminiten */ D=b*b-4*a*c; printf("\n The Nature of roots of a quadratic equation");

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 53

if(D==0) { printf("\n\n\n roots are real and equal "); } else if(D>0) { printf("\n\n\n roots are real and not equal "); } else { printf("\n\n\n roots are imaginary "); }

OUTPUT

/* keep console screen until a key stroke */ getch(); } 2.16

THE SWITCH STATEMENT

This is a conditional control statement that allows some particular group of statements to be chosen from several available groups. It is a multi-way conditional statement generalizing the if else statement. A switch statement allows a single variable to be compared with several possible case labels, which are represented by constant values. If the variable matches with one of the constants, then an execution jump is made to that point. A case label cannot appear more than once and there can only be one default expression. The switch statement takes this form:

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 54

Note that this statement does not allow less than, greater than, etc. ONLY the equality operator (==) is used with a switch statement. The control variable must be integral (int or char) only. When the switch statement is encountered, the control variable is evaluated. Then, if that evaluated value is equal to any of the values specified in a case clause, the statements immediately following the colon (:) begin to run. Default case is optional and if specified, default statements will be executed, if there is no match for the case labels. Once the program flow enters a case label, the statements associated with one case have been executed, the program flow continues with the statement for the next case. In other words, once the program enters through a closed switch, it executes the code for all of the following cases until end. Lets consider a program segment

It consists of the following outputs

The results are possible, depending on the value of printFlag. If printFlag is 1, then all three printf statements are executed. If printFlag is 2, then the first print
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 55

statement is skipped and the last two are executed. Finally, if printFlag is neither 1 nor 2, then only the statement defined by the default is executed. But occasionally we need this flexibility; it is not always we want. If we want execute only one case-label, C provides break statement. It causes the program to jump out of the switch statement, that is go to the closing braces (}) and continues the remaining code of the program. If we add break to the last statement of the case, the general form of switch case is as follows:

After adding the break statement to each case label the switch case executes only one printf . The results are shown below.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 56

Difference between Switch and else if ladder


B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 57

The switch statement only works on integer. Whereas else if ladder works for any type of value. In switch case only equality operation is performed. In else if any operator can be used in the condition. If the number of test cases are more in terms of readability and understabality switch case is better than else if ladder. switch works faster than else if ladder.

2.17 LOOPS IN C
The real power of computers is in their ability to repeat an operation or a series of operations many times. This repetition, called looping or iteration. Each loop must have an expression (condition) that determines if the loop is done. If it is not done, the loop repeats one more time; if it is done, the loop terminates. We need to test for the end of a loop; we can have either a pre- or a post-test terminating condition. In a pretest loop, in each iteration, the control expression is tested first. If it is true, the loop continues; otherwise, the loop is terminated. In a post-test loop, in each iteration (repetition), the loop action(s) are executed. Then the control expression is tested. If it is true, a new iteration is started; otherwise, the loop terminates. In a pre tested loop if the condition is false in the first test itself then no actions are taken place. Where as in the case op post test at least once the body of the loop is going to execute. A looping process, in general, would include the following four steps, Before a loop start, the loop control variable must be initialized; this should be done before the first execution of loop body. Test for the specified condition for execution of the loop, known as loop control expression. Executing the body of the loop, known as actions. Updating the loop control variable for performing next condition checking. Table 2.19 shows the difference between a pre tested loop and post tested loop in terms of iterations test conditions etc..,
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 58

Table 2.19 Pretest loop and post test loop

Figure 2.21 Flow chart for pretest loop and post test loop C language provides three loop control structures for performing repetition. They are shown in Figure 2.22.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 59

Figure 2.22 Different types of loops in C

2.17.1 THE WHILE STATEMENT


The "while" loop is a generalized looping structure that employs a variable or expression for testing the ending condition. Is a repetition statement that allows an action to be repeated while some conditions remain true. Variables used in the loop control testing must be initialized testing for the termination condition is done at the top of the while () loop. The body of WHILE statement can be a single statement or compound statements. Syntax: Form 1: Simple Statement while (condition) statement; Form 2: Compound Statements while (condition) { s1; s2; s3; .. }

In the above syntax while is the reserve word, condition should be specifies in between braces, a valid c expression. The statement (or block) will execute repeatedly until condition becomes false.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 60

/********************************************************* * Name: Rev.c * * Author: B V Rajesh * * Date: 24/11/10 * * Description: a program to revese a positive number * *********************************************************/ #include<stdio.h> void main() { /* Variable Declaration */ Figure 2. 23 Flow chart for while loop /* Display Values */ int n,rem,rev=0; printf("\n Enter a positive number: "); scanf("%d",&n); while(n!=0) { rem=n%10; rev=rev*10+rem; n=n/10; } printf("The reverese of %d is %d",n,rev);
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 61

/* keep console screen until a key stroke */ getch();

OUTPUT Enter a positive number: 1234 The reverse of 1234 is 4321

2.17.2 DO WHILE STATEMENT


Statements in the loop are executed first (at least once, and condition is tested last. Loop is controlled by a condition. The general form is : do { statement; statement; } while (condition); statement; On reaching do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, condition statement is evaluated. If the condition is true, it evaluates the body of the loop once again. This process continues up to the condition becomes false. In menu-driven application do-while statement is used. In do while statement, the Example while statement must ebd with semi colon. #include <stdio.h> void main() { int do {

i = 1, n=5;

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 62 printf( %d * %d = %d , n, i, n*i);

i = i + 1; } while ( i<= 5); }

2.17.3 THE FOR LOOP


When the number of passes through a loop is known in advance, a for statement is often used. The general form of the for loop is for( initialization; test-condition; increment) { Body of the loop } The execution of the for statement is as follows: Initialization of the control variables is done first, using assignment statements such as i=1 count=0. The variables I and count are known as loop-counter variables. The value of the control variable is tested using the test-condition. The test-condition is a relational expression, such as i<10 that determines when the loop will exit. If the condition is true, the body of the statement that immediately follows the loop. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now the control variable is incremented using an assignment statement such as i=i+1. And the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is true, the body again executed, this process continues till the control variable fails to satisfy the test-condition. Consider the following segment of code: for(i=0;i<10;i++) { printf(%d,i); }
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 63

This for loop executes 10 times and prints the digits 0 to 9 in one line. The three sections enclosed within parentheses must be separated by semi colon. We can write the for loop in the following ways Option 1 for (k= 1; k< = 10 ;) { printf(%d, K); K = k + 1; } Here the increment is done within the body of the for loop and not in the for statement. Note that the semicolon after the condition is necessary. Option 2 Int k = 1; for (; k< = 10; k++); { printf(, k); } Here the initialization is done in the declaration statement itself, but still the semicolon before the condition is necessary.

The infinite loop One of the most interesting uses of the for loop is the creation of the infinite loop. Since none of the three expressions that form the for loop are required, it is possible to make an endless loop by leaving the conditional expression empty. For example: for (; ;) Printf(The loop will run forever\n); Actually the for (; ;) construct does not necessarily create an infinite loop because Cs break statement, when encountered anywhere inside the body of a loop, causes immediate termination of the loop. Program control then picks up the code following the loop, as shown here:
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 64

For (; ;) { Ch = getchar( ); If (ch = = A) Break ; } Printf (you typed an A); This loop will run until A is typed at the keyboard. For loop with no bodies A statement, as defined by the C syntax, may be empty. This means that the body of the for may also be empty. This fact can be used to improve the efficiency of certain algorithms as well as to create time delay loops. The following statement shows how to create a time delay loop using a for loop: for (t = o; t < SOME _VALUE; T++); One final C operator is the comma ,, which most often finds use in the for statement. A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right operand. Thus, in a for statement, it is possible to place multiple expressions in the various parts. break statement When a break statement is enclosed inside a block or loop, the loop is immediately exited and program continues with the next statement immediately following the loop. When loop are nested break only exit from the inner loop containing it. /* get a character */

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 65

Figure 2.24 working of break in different looping statements continue statement C supports a statement continue to skip a part of the loop. It causes the loop to be continued with the next iteration after skipping any statements between. The continue statement tells the compiler, skip the following statements and continue with the next iteration. The format of the continue statement is:

Figure 2.24 working of continue in different looping statements Nested Loops These loops are the loops which contain another looping statement in a single loop. These types of loops are used to create matrix. Any loop can contain a number of loop statements in itself. If we are using loop within loop that is called nested loop. ANSI C support nesting up to 15 levels.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 66

In this the outer loop is used for counting rows and the internal loop is used for counting columns SYNTAX:for (initializing ; test condition ; increment / decrement) { statement; for (initializing ; test condition ; increment / decrement) { body of inner loop; } statement; } Consider the following segment of program for (j=1; j<=4; j++) { for (i=1; i<=5; i++) { printf (*); } printf (\n); } OUTPUT OF THIS PROGRAM IS

**** **** **** ****

ASSIGNMENT-II
1. (a) What are the general characteristics of C? (b) Give and Explain the structure of a C program? 2. (a) What is a variable? Explain declaring of variable. How to assign values to variables.
B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 67

(b) Write about space requirements for variables of different data types. 3. (a) Define the following with examples: (i) C tokens (ii) Identifiers (iii) Keyword (iv) constant (b) Differentiate Constants and Variables. 4. (a) What is the standard Input / Output header file in C? How it is used? (b) What are the commonly used Input / Output functions used in C? How they are accessed? Explain. 5. (a) What is an operator? What are the different categories of operators? Explain with examples? (b) What is precedence and Associativity? Give the Precedence and Associativity of different operators. 6. (a) What is an Expression? What are the different categories of expression? Explain with examples. (b) Explain Switch statement. How does this statement differ from the other conditional statements? 7. (a) Explain about different forms of IF statement and draw the flowchart for each one. (b) Describe in detail the execution of While statement with example. 8. (a) What is the purpose of for statement? How does it differ from the while statement and the do-while statement? (b) How many times will a for loop be executed? What is the purpose of the index in a for statement. (c) Can any of the three initial expression in the for statement be omitted? If so, what are the consequences of each omission? 9. (a) What is the purpose of break and continue statements? Write the difference between them. (b) Suppose a break or continue statements are included within the innermost of several nested control statements. What happens when break or continue statement is executed? (c) Summarize the syntactic rules associated with the do-while statement. Compare it with the while statement.

B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 68

Вам также может понравиться