You are on page 1of 56

0 # 55

C FUNDAMENTALS
Prepared by

S.Gunasekaran B.E, 7/1/2011

This unit is explained about the fundamentals of C language such as C character set-Identifiers and keywords-Data types-Constants-Variables-Declaration-Expressions-Statements-Symbolic constantsOperators-Data input and output-control statements-Unconditional statements, nested loop.

1 # 55

HISTORY OF C LANGUAGE
C is one of the most popular programming languages. It was developed by Dennis Ritchie at AT & Ts Bell Laboratories at USA in the early 1970s. It is an upgraded version of two earlier languages, called Basic Combined Programming Language (BCPL) and B, which were also developed at Bell laboratories. The following table illustrates the history of C language. Language Year 1960 1967 1970 1972 1978 1989 1990 Founder International group Martin Richards Ken Thompson Dennis Ritche Kernighan and Ritche ANSI Committee ISO Committee

ALGOL BCPL B C K&RC ANSI C ANSI/ISO C

C IS A MIDDLE LEVEL LANGUAGE


a) Low level language: Low level language is in terms of 0s and 1s (bits). C language has the certain features of Low-level Language, that allow the programmer to carry out operations on bits that are normally available in Assembly language or Machine language.

b) High level language: High level language looks like normal English, whose instruction set is more compatible with human languages. These languages are easily understandable and designed to provide a better program efficiency. These are machine independent. Examples are FORTAN, PASCAL, COBOL, BASIC, C++ etc. c) Middle level language: C lies in between these two categories it is neither a low level language nor a high level language, it is a middle level language. i.e., performs the task of Low level language as well as high level language. We can write the code for Operating System, Application Programs, and Assembly language programs in C language. Unix Operating System is written in C language.

2 # 55

STRUCTURE OF A C PROGRAM
There are some sections in C program given below: i) Documentation Section It consists of set of comment lines used to specify the name of program, author and other details etc., Comments: It is helpful in identifying the program features and underlying logic of the program. The line begins with /* and ending with */. These are not executable, the compiler is ignored anything between /* and */.The new style is // ii) Preprocessor Section Definition section It is used to link system library files, for defining the macros and for defining the conditional inclusion. Eg: iii) #include<stdio.h>, #define A 10, #if def, #endif etc.

Global Declaration Section The variables that are used in more than one function throughout the program are called global variables and declared outside of all the function i.e., before main(). It has two parts: Declaration part to declare all the variables used in the program Execution part Contains at least one valid C statement. It begins with opening braces {and ends with closing braces }. The closing brace of main function is the logical end of the program.

iv)

Sub Program Section It contains the function definitions included.

The following tables are explained the programming structure.

3 # 55

STRUCTURE documentation section preprocessor section definition section global declaration section main() { declaration part; execution part; } sub program section { Body of the subprogram; }

SAMPLE /* finding area of circle */ #include<stdio.h> #define PI 3.14 main() { int r=5; float area; area = PI * r * r; printf(Area of circle: %f, area); } OUTPUT: Area of circle: 78.5

CHARACTER SET
Character set is the fundamental raw material of any language and they are used to represent information. C language consists of two character set namely, a) Source character set b) Execution character set

Source Character Set These are useful to construct the statements in the source program Alphabets Upper case AZ, Lower case az ,Digits 0,19 ,Special character , + - * / $ _ { [ ] < > \ | ~ @ # % ^ & : ; ? Execution Character Set These are employed at the time of execution. This set of characters are also called as non graphic characters because, these characters are invisible and cannot be printed or displayed directly. This will be effect when program is being executed. Execution characters set are always represented by a backslash (\) followed by a character. We simply call it as escape sequences.

4 # 55

CHARACTER Bell (alert) Backspace Horizontal tab Vertical tab Newline (Line feed) Form feed Carriage return Quotation Mark Apostrophe Question Mark Back Slash Null

ESCAPE SEQUENCE \a \b \t \v \n \f \r \ \ \? \\ \0 (indicate end of string)

C TOKENS
The individual units of C programming language are called C tokens. It is usually referred as individual text and punctuation in a passage of text and has the following types

C Tokens

Identifiers

Keywords

Constants

Strings

Operators

Special Symbols

Total, Age

int, double, for

39, 39.77

Guna Vikram

+, -, *, /

#, $, %

5 # 55

IDENTIFIERS
Identifiers are referring to the names of variable, functions and arrays.

RULE FOR NAMING AN IDENTIFIERS


First character must be an alphabet Must consist of only letters, digits or underscore Only first 31 characters are significant Must not contain white space

The following are valid Salary, aug99_sales, I, index The following are not valid 2001_sales, aug99+sales, my age, printf

KEYWORDS
There are certain reserved words called keywords that have standard and predefined meaning in C language, which cant be changed. All keywords are fixed meanings and these meanings are cant be changed Keywords serve as basic building blocks for program statements Example: Auto, double, int, struct, break, else, case, char, float, for

DATA TYPES
Data type is the type of the data, which are going to access within the program. C supports different data types. Each data type may have predefined memory requirement and storage representations in program.

6 # 55

They are four data types: Primary Data Type Char int float double C User defined Derived Empty

typedef enum

arrays pointers structures union

void

Basic data types: Type Character Integer Floating point Double floating point Valueless Keyword char int float double void

Several of the basic types can be modified using one or more of these type modifiers: signed unsigned short long The type modifiers precede the type name that they modify. The basic arithmetic types, including modifiers, allowed by C are shown in the following table along with their guaranteed minimum ranges. Most compilers will exceed the minimums for one or more types. Also, if your computer uses twos complement arithmetic (as most do), then the smallest negative value that can be stored by a signed integer will be one more than the minimums shown. For example, the range of an int for most computers is 32,768 to 32,767. Whether type char is signed or unsigned is implementation dependent.

7 # 55

Type Byte CHARACTER TYPE char unsigned char 1 bytes signed char INTEGER TYPE Int 2 bytes unsigned int 2 bytes signed int 2 bytes short int 1 bytes unsigned short 1 bytes int signed short int 1 bytes long int 4 bytes signed long int 4 bytes unsigned long 4 bytes int FLOAT TYPE float 4 bytes double 8 bytes long double 10 bytes

Minimum Range 127 to 127 or 0 to 255 0 to 255 127 to 127 32,767 to 32,767 0 to 65,535 same as int same as int 0 to 65,535 same as short int 2,147,483,647 to 2,147,483,647 same as long int 0 to 4,294,967,295

3.4E-38 to 3.4E+38 (6 digits of precision) 1.7E-308 to 1.7E+308 (10 digits of precision) 3.4E-4932 to 1.1E+4932 (10 digits of precision)

EMPTY DATA TYPE void When a type modifier is used by itself, int is assumed. For example, you can specify an unsigned integer by simply using the keyword unsigned. Thus, these declarations are equivalent. unsigned int i; // here, int is specified unsigned i; // here, int is implied

VARIABLES
A variable is an identifier that is used to represent some type of information within a designated portion of the program. Example int a,b,c; Here a,b,c is a variable

8 # 55

RULES FOR NAMING THE VARIABLE:


Variable name can be any combination of 1 to 18 alphabets, digits or underscore First character must be an alphabet Length of the variable cant exceed upto 8 characters long, and some C compilers can be recognizing upto 31 characters long. No commas or blank spaces are allowed within a variable name. No special symbol, an underscore can be used in a variable name.

Syntax: datatype v1, v2, v3,., vn; Where datatype v1, v2, v3... vn Example: main() { int i,j; char c; float x; //rest of program follows } //These 3 lines declare 4 variable is the type of the data are the list of variables

USER DEFINED VARIABLES:


a) Type declaration: C Language provides a feature to declare a variable of the type of user defined type declaration, which allows users to define an identifier that would represents an existing data type and this can be used to declare variables. Syntax:

typedef datatype identifier;


Where typedef datatype user defined type declaration existing data type

9 # 55

identifier

refers to the new name given to the data type

Eg:

typedef int marks; marks m1, m2, m3;

b) Enumerated data type: C language provides another user defined data type is called enumerated data type. Syntax:

enum identifier {value 1, value2, ., value n};

where enum user defined enumerated data type. identifier refers to the new name given to the datatype value1, value2, , value n enumeration constants Eg: enum day {mon, tue, wed,,sun}; enum day w_st, w_end; w_st = mon; w_end=sun;

CONSTANTS
The items whose values cant be changed during the execution of program are called constants. C constants can be classified as follows:

10 # 55

Constants

Numeric

Character

Integer

Real

Character

String

INTEGER CONSTANTS
An integer constant formed with the sequence of digits. There are three types of integer constants which are different number system. Decimal number Octal number Hexadecimal Eg: marks = 90; per = 75; discount = 15; These are basically three types of integer namely, 0 to 9 0 to 7 0 to 9, A, B, C, D, E, F

Decimal Octal Hexadecimal

Eg: 10, 153, -342, 089, etc. Eg: 037, 0,0567, etc. Eg: 0x4, 0x8F, 0xBCF etc.

11 # 55

REAL CONSTANTS
It is made up of a sequence of numeric digits with presence of decimal point. Eg: weight = 56.8; height = 5.6; speed = 3.11;

CHARACTER CONSTANTS
The character constant contains is a character with enclosed quotes Eg: p N 4 +

STRING CONSTANTS
A string constant is a sequence of characters enclosed in double quotes ( ), the characters may be letters, numbers, special characters and blank spaces etc. At the end of string \0 is automatically placed. Eg: String, HI 39.56, 22

i)

Declaring a variable as constant: When the value of some of the variables may remain constantly during the execution of the program, in such a situation, this can be done by using the keyword const. Syntax:

const datatype variable = valconstant


Where const variable datatype constant Eg: const int rate = 397;

keyword to declare constant name of the variable type of the data constant

12 # 55

STRING: String is a collection of character Eg: India, Tamilnadu

OPERATORS:
An operator is a symbol that tells the computer to perform the certain mathematical or logical manipulations C operators can be classified into a number of categories. They include

Arithmetic operator
Relational operator

Logical operator
Assignment operator

Operators Increment and decrement operator


Conditional operator Bitwise operator

Special operator

1. ARITHMETIC OPERATOR
C provides the entire basic arithmetic operator + / Addition operator Subtraction operator Division operator

% modulo division Modulo operator cant used to floating point data

13 # 55

Example: a=10, b=5 a+b=15 a-b=5 a/b=2 a%b=2

2. RELATIONAL OPERATOR
Relational operator which is used to compare two quantities and depending on their relation take certain decisions Relational expressions are used in decision statements such as if and while They operator are < less than > greater than <= less than or equal to >= greater than or equal to == is equal to != not equal to Example: a=10, b=5 a<b false a>b true a<=b false a>=b true a==b false a!=b true

3. LOGICAL OPERATOR
Logical operator which is used to test more than one condition and make decisions

14 # 55

They operator are && ->Logical AND ||->Logical OR !->Logical NOT Example: if((a<b) && (c>d)) { printf( This is true); } The variable a must be less than b and, at the same time, c must be greater than d .if both condition is true then if block statement execute, either one or false statement not execute If((a<b)||(c>d)) { printf( This is true); } The variable a must be less than b and, at the same time, c must be greater than d .if both condition either one or true or both true then if statement block execute If(!(a<b)) If a is not small than b or not equal to b then the if block statement is executed

4. ASSIGNMENT OPERATOR
Assignment operator are used to assign the results of an expression to a variable = ->assignment operator Example: Variable operator = expression a=10, b=5 a=a+b ->a=15 is equal to a+=b ->a=15

5. INCREMENT AND DECREMENT OPERATOR


The operator ++ add 1 to operand while subtract 1. Increment and decrement statements in for and while loops extensively

15 # 55

Two types Prefix: A prefix operator first adds 1 or subtract to the operand and then the result is assigned to the variable on left Example: Assume a=5; b=++a; a=6,b=6 b=--a; a=5,b=5; Postfix: A postfix operator first operator first assigns the value to the variable on left and then increment or decrement the operand Example: Assume a=5; b=a++ b=5,a=6 b=a- b=5,a=4

6. CONDITIONAL OPERATOR
Conditional operator also called as ternary operator. This conditional operator is used to replace if else logic in some situation The conditional operators are Conditional exp? expression1: expression 2; If the condition exp is true is expression 1 is execute .if the condition exp is false then expression 2 is execute a>b?(ans=10);(ans=25); is equal to if(a>b) { ans=10; } else

16 # 55

{ ans=25; }

7. BITWISE OPERATOR
Bitwise operator for manipulation of data at bit level. These operator are used for testing the bits or shifting them right or left .bitwise operator not be applied to float or double The bitwise operators are & Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR << Shift left >> Shift right Eg: 24 >> 2 is 6 24 0001 1000 After shifting right by 2 position, 0000 0110 6

8. SPECIAL OPERATOR
Comma operator: The comma operator can be used to link the related expressions together .the comma linked list of expressions are evaluated left to right and the value of right most expression is the value combined Example: Value=(x=10,y=5,x+y); Sizeof() operator: The sizeof is compile time operator and when used with an operand it returns the number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier a=sizeof(sum); b=sizeof(long int); c=sizeof(234);

17 # 55

SPECIAL SYMBOLS:
These are the symbols, which has some syntactic meaning and has got significance. These will not specify any operation. In C language call it as Delimiters as given below: SYMBOLS # , : ; () {} [] NAME Hash comma Colon Semicolon Paranthesis Curly braces Square braces MEANING Pre-Processor directive Variable delimiters to separate list of variables Label Delimiters Statement Delimiters Used in expressions or in functions using for structure blocking C

used along with arrays

EXPRESSIONS
An expression consists of a sequence of constants, identifiers, and operators that the program evaluates by performing the operations indicated. The expression's purpose in the program may be to obtain the resulting value, or to produce side effects of the evaluation, or both. Single constant, a string literal, or the identifier of an object or function is in itself an expression. Such a simple expression, or a more complex expression enclosed in parentheses, is called a primary expression. Every expression has a type. An expression's type is the type of the value that results when the expression is evaluated. If the expression yields no value, it has the type void. Some simple examples of expressions are listed below: Variable = Expression; Eg: y = (a/b) +c; k = ((2 * x * x)/b) c;

18 # 55

OPERATOR PRECEDENCE AND ASSOCIATIVITY


An expression may contain several operators. In this case, the precedence of the operators determines which part of the expression is treated as the operand of each operator. For example, in keeping with the customary rules of arithmetic, the operators *, /, and % have higher precedence in an expression than the operators + and -. For example, the following expression: a-b*c is equivalent to a - (b * c). If you intend the operands to be grouped differently, you must use parentheses, thus: (a - b) * c If two operators in an expression have the same precedence, then their associativity determines whether they are grouped with operands in order from left to right, or from right to left. For example, arithmetic operators are associated with operands from left to right, and assignment operators from right to left, as shown below lists the precedence and associativity of all the C operators.

OPERATOR GROUPING EXPRESSION a/b%c a=b=c ASSOCIATIVITY Left to right Right to left EFFECTIVE GROUPING (a / b) % c a = (b = c)

OPERATOR PRECEDENCE AND ASSOCIATIVITY PRECEDENCE 1. OPERATORS Postfix operators : [ ] ( ) . -> ++ -(type name){list} 2. Unary operators: ++ -! ~ + - * & sizeof 3. 4. 5. 6. The cast operator: (type name) Multiplicative operators: * / % Additive operators: + Shift operators: << >> Right to left Left to right Left to right Left to right Right to left ASSOCIATIVITY Left to right

19 # 55

OPERATOR PRECEDENCE AND ASSOCIATIVITY PRECEDENCE 7. 8. 9. 10. 11. 12. 13. 14. 15. OPERATORS Relational operators: < <= > >= Equality operators: == != Bitwise AND: & Bitwise exclusive OR: ^ Bitwise OR: | Logical AND: && Logical OR: || The conditional operator: ? : Assignment operators: = += -= *= /= %= &= ^= |= <<= >>= 16. The comma operator: , Left to right ASSOCIATIVITY Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left

DATA INPUT AND OUTPUT


Standard devices C always assumes that input comes from stdin or the standard input device .this is usually the keyboard. C assumes that all output goes to stdout or the standard output device Standard I/O devise in C

I/O DEVICE Screen Keyboard Printer Serial port Error messages Disk files

C NAME Stdout Stdin Stdprn Stdaux Stderr None

20 # 55

SIMPLE INPUT AND OUTPUT STATEMENT


scanf The scanf () functions is used to read the formatted data items from the keyboard the format is user defined data items .it can be read or written as defined by a programmer The general format scanf(control string ,argument list); The control string is a specified format code to read from the keyboard and the argument list is a user defined variable list .usually, the argument list of the user defined variables must include the address operator(&) as a prefix to the variable

For example int x,y; scanf(%d%d,&x,&y); char c,i; scanf(%f%f,&c,&i); The complete format code used in the scanf() function for the various data variables shown below Code %c %d %i %e %f %h %o %s %x Meaning Read a single character Read a decimal integer Read a decimal integer Read a floating point number Read a floating point number Read a short integer Read a octal number Read a string Read a hexadecimal number

All the variables used to receive values through scanf() must be passed by their addresses .this means that all arguments must be pointed to the variables used as arguments

21 # 55

printf() The printf() function is one of the most important and useful function to display the formatted output data items on the standard output device normally the video screen The general form of printf() function is as printf(control strings,argument list); Where the control strings are user defined format code and the argument list is a set of data items to be displayed in a proper format as defined by the control stings The complete format code used in the printf() function for the various data variables shown below

Code %c %d %i %e %f %h %o %s %x %%

Meaning Read a single character Read a decimal integer Read a decimal integer Read a floating point number Read a floating point number Read a short integer Read a octal number Read a string Read a hexadecimal number Print a percent sign

THE get() AND putc() FUNCTIONS


The most fundamental character I/O functions are getc() and putc(). getc() The getc() function inputs a single character form the standard input device which is keyboard ,unless you redirect it

The format for getc( ) follows intvar=getc(device);

Dont let the integer intvar confuse you. Even though getc() is a character function, you use a integer variable to store the getc() input value. getc() returns a 1 when an end-of-file condition occurs. If you are using getc() to read information from a disk file, the 1 is read when the end of the file is reached The getc() device can be any c standard input device .if you are getting character input from the keyboard ,use stdin as the device

22 # 55

putc() The putc() functions writes a single character to the standard output device ,which is the screen, unless you redirect it from your operating system. The format of putc() follows: putc(intval,device); The intval can be integer variable, expression, or constant. You output character data with putc().the device can be any standard output c device.to write a character to your printer, use stdprn for the device. Example program /*Introduces getc() and putc()*/ #include<stdio.h> #include<conio.h> void main() { int inchar; char first,last; clrscr(); printf("what is your first name initial?"); inchar=getc(stdin); first=inchar; inchar=getc(stdin); // ignore newline //Wait for first initial //Holds incomming initial //Holds converted first and last intial

printf("what is your last name initial?"); inchar=getc(stdin); last=inchar; inchar=getc(stdin); // ignore newline //Wait for last initial

23 # 55

printf("\nHere they are!!!\n"); putc(first,stdout); putc('\n',stdout); putc(last,stdout); getch(); } // A newline is output

OUTPUT

The getchar() and putchar() functions


When you perform character I/O ,the getchar() functions are easier to use than getc() and putc(). The getchar() and putchar() functions are identical to getc() and putc(),except you do not specify a because they assume that the standard input and output devices are stdin and stdout (typically ,the screen and the keybord).in the following

inchar=getc(stdin); Is identical to inchar=getchar(); And

24 # 55

putc(var.stdout); is identical to putchar(var); The getchar() and the getc() functions are both buffered input functions. That is as you type characters, the data goes to a buffer rather than immediately to your program. The buffer is a section of memory managed by C When your program gets to a getc() or a getchar(),the program temporarily waits as you type the input. The program does not seethe characters because they are going to the buffer in memory there is no limit to the size of the buffer; it keeps filling up with you press enter. Pressing the enter key signals the computer to release the buffer to your program /*Illustrates simple getchar() and putchar()*/ #include<stdio.h> #include<conio.h> void main() { int mychar; clrscr(); mychar=getchar(); // Get the character // Must be integer

printf("You Typed This!!!\n"); putchar(mychar); getch(); }

25 # 55

OUTPUT

getch() and putch() funtoins


The getch() and putch() functions are slightly different than the previous character I/O functions. Their formats are similar to getchar() and putchar() ; they both assume that stdin and stdout are the standard input and output devices, and you cant specify other devices(unless you redirect them with your operating system) The format of getch() intvar=getch(); The format of putch() putch(intvar); The getch() and putch() functions are not ANSI C standard functions, but they are available on a large number of compilers and well worth mentioning, getch() and putch() are non-buffered functions Both getch() and putch() assume that stdin and stdout are the standard input and output devices. When you want your program to respond immediately to keyboard input use getch().some programmers want to make users press enter after answering a prompt or selecting from a menu. They feel that buffered input gives users more time to decide if they really want to give that answer: users can press Backspace and correct the input before pressing Enter Example program /*uses getch() and putch() input and output */ #include<stdio.h> #include<conio.h>

26 # 55

void main() { int ctr; char letters[5]; clrscr(); printf("Please Type Five Letters....\n"); for(ctr=0;ctr<5;ctr++) { letters[ctr]=getch(); } printf("\nYou Typed Five Letters are!!!\n"); for(ctr=0;ctr<5;ctr++) // Print them to the screen { putch(letters[ctr]); } for(ctr=0;ctr<5;ctr++) { putc(letters[ctr],stdprn); // Print them to the printer } getch(); } // Add input to array // The for loop counter // Holds five input characters

27 # 55

OUTPUT

STRING I/O FUNCTIONS


The input and output functions are listed fellow gets(s):stores input from stdin(usually directed to the keyboard)into the string named s puts(s):output the s string to stdout(usually directed to the screen by the operating system) Therefore when you enter stings with gets(), C places a string-terminating character in the string at the point where you press Enter. This creates the input sting. (Without the null zero, the input would not be a string).when you output a string, the null zero at the end of the sting becomes a newline character. This is good because you typically prefer a newline at the end of a line of output (to put the cursor on the next line) Example Program /*using gets() and puts()*/ #include<stdio.h> #include<conio.h> void main() { char book[30]; clrscr(); printf("What is the Book Tittle?\n"); // Holds the string

28 # 55

gets(book);

// Get an input String

printf("You Typed the Book Tittles are!\n"); puts(book); // Display the String

printf("Thanks for the Book!!!\n"); getch(); } OUTPUT

29 # 55

DECISION MAKING AND BRANCH STATEMENTS

Decision Making and Branching Statements

Simple if statements

The if else statements

Nesting of if else statements

The else if Ladder

Simple if statements: Syntax: if(test expression) { Statement block one or more; } Statement x; If the test expression is true then the statement is executes otherwise it goes to out of branch

Condition

False

True True Statements

30 # 55

Example: //simple if program #include<stdio.h> #include<conio.h> void main() { int age=21; //declare and assign age as 21 clrscr(); printf(\n What is student age? ); scanf(%d,&age); if(age<=18) { printf(Your are Minor); } getch(); } Output:

31 # 55

Simple if else statements: Syntax: if(condition) { Block of one or more statements } else { Block of one or more statements } The if condition is true then execute entire if block statement other wise else statement is execute

True Condition

False

True Statements

False Statements

32 # 55

Example: //simple if else program #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("What is your number?"); scanf("%d",&num); if(num>=10) { printf("More than 10\n"); } else { printf("Less or equal to 10\n"); } getch(); }

33 # 55

OUTPUT

Nested if else statements: When a series of decisions are involved. We may have to use more than one if.else statements

Syntax: if(test condition-1) { if(test condition-2) { Statements -1; } else { statements -2; } } else

34 # 55

{ Statements-3; } Statements x;

If the condition-1 is false, the statement-3 will be executed, otherwise to perform the second test. if the condition -2 is true, the statement-1 will be evaluated, otherwise the statement2 will be evaluated and then the control is transferred to the statement-x

35 # 55

Example: //nested if else program #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("\nEnter the three valus:"); scanf("%d%d%d",&a,&b,&c); prtinf(\n***OUTPUT***\n); printf("The Largest values are:"); if(a>b) { if(a>c) { printf("%d",a); } else { printf("%d",c); } } else { if(c>b) { printf("%d",c); } else {

36 # 55

printf("%d",b); } } getch(); }

OUTPUT

The else if ladder statements: A multiple decision is a chain of if is which statement associated with each else is an if Syntax: If(condition) Statement -1; else if (condition 2) statement-2; else if(condition-3) statement-3; else if(condition n) statement n; else default statements;

statement x;

37 # 55

The conditions are evaluated from the top to downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statementx. When all the condition is false then the final else containing the default statement will be executed Example: //else if ladder #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("Enter the Number(1-5)"); scanf("%d",&num); printf(\n***OUTPUT***\n); if(num==1) printf("color=RED"); else if(num==2) printf("color=GREEN"); else if(num==3) printf("color=WHITE"); else if(num==4) printf("color=YELLOW"); else if(num==5) printf("color=BLUE"); else printf("color=BLOCK"); getch(); }

38 # 55

OUTPUT

switch case statement:


The switch statement is sometimes called the multiple choice statement Syntax: switch (expression) { case value1: block-1; break; case value2: block-2; break; . . . default: default-block; break;
default Statements case 2 Statements case 1 Statements switch

39 # 55

The expression can be an integer expression, a character, a constant or a variable. The sub expression (value1, value 2 and so on) If the expression matches value1 the statement execute and so on. None of the value is not match then default statement is executes Example: //simple switch program #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("Enter the number(1-7)"); scanf("%d",&num); switch(num) { case 1: { printf("This is Sunday"); break; } case 2: { printf("This is Monday"); break; } case 3: { printf("This is Tuesday"); break; }

40 # 55

case 4: { printf("This is Wendsday"); break; } case 5: { printf("This is Thursday"); break; } case 6: { printf("This is Friday"); break; } case 7: { printf("This is Saturday"); break; } default: printf("You Enter the Wrong Number try again"); } getch(); }

41 # 55

OUTPUT

UNCONDITIONAL STATEMENTS
break The for loop was designed to execute for a specified number of times, sometimes, though rarely the for loop should quit before the counting variable has reached its final value, as with while loops, you use the break statements to quite a for loop early. The break statement goes in the body of the for loop. Programmers rarely put break on a line by itself, and it almost comes after an if test.if the break were on a line by itself the loop would always quit early defeating the purpose of the for loop The format of break is break; Example for(ctr=0;ctr<n;ctr++) { break; printf(Loop now\n); // this never print } break terminates loop immediately

42 # 55

Example /*a for loop running at the user's request*/ #include<stdio.h> #include<conio.h> void main() { int num,ans; clrscr(); printf(" Here are the numbers from 1 to 20\n"); for(num=1;num<=20;num++) { printf("%d\n",num); printf("Do you want to see another (Y/N)?"); ans=getchar(); if((ans=='N')||(ans=='n')) { break; } } printf("\n That's all !!!"); getch(); } // will exit the for loop if user wants // loop counter variable

43 # 55

OUTPUT

THE CONTINUE STATEMENT The break statements exits a loop early ,but the continue statements forces the computer to perform another iteration of the loop.if you put a continue statements in the body of a for or a while loop, the computer ignores any statements in the loop that follow continue The format of continue is continue; Example for(ctr=0;ctr<n;ctr++) { continue; printf(Loop now\n); // this never print } continue causes loop to repeat once again

/* demonstrates use of continue statement */ #include<stdio.h> #include<conio.h> void main(){ int ctr; clrscr(); for(ctr=1;ctr<=10;ctr++) { printf("%d",ctr); // Loop 10 times

44 # 55

continue;

// Causes body to end early

printf("C Programming\n"); } getch(); }

OUTPUT

GOTO STATEMENT: C supports the goto statement to branch unconditionally from one point to another in the program. The goto requires a label to identify the place where the branch is to be made. A label is any valid variable name, must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred.

General forms:
goto label; .. .. label: statement; label: statement; .. .. goto label; Backward jump

Forward jump Syntax: goto begin;

Backward jump

45 # 55

goto breaks the normal sequential execution of the program. If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. such a jump is called backward jump. If the label: is placed after the goto label; some statements will be skipped and the jump is known as forward jump. A goto is used at the end of a program to direct the control to go to the input statement, to read further data. Example /* This is Program demonstrates the overuse of goto */ #include<stdio.h> #include<conio.h> void main() { clrscr(); goto Here; First: printf("A\n"); goto Final; There: printf("B\n"); goto First; Here: printf("C\n"); goto There; Final: getch(); }

46 # 55

OUTPUT

DECISION MAKING AND LOOP STATEMENTS


DECISION MAKING AND LOOP STATEMENTS

while while

do-while

for

The while statement is one of several C construct statement. Looping statements cause parts of a program to execute repeatedly as long as a certain condition is being met. While is an entry-controlled loop statement. Syntax: while(test-condition) { Body of the loop } The test condition is evaluated and if the condition is true(non zero),the block of one or more C statements execute repeatedly until the test condition becomes false(evaluates to zero)

47 # 55

Body of the loop

True Condition False

Example: //simple while program #include<stdio.h> #include<conio.h> void main() { char name[15]; int count=0; clrscr(); printf("What is Your First Name?"); scanf("%s",name); while(name[count]) { count++; } printf(\n***OUTPUT***\n); printf("Your Name has %d Characters",count); getch(); }

48 # 55

OUTPUT

dowhile
The dowhile is exit controlled loop. The body of the do-while execute at least once. The do-while statement controls the do-while loop, which is similar to the while loop except the relational test occurs at the bottom (rather than top) of the loop. This ensures that the body of the loop executes at least once.

Syntax: do { Body of the loop } while(test-condition);


Body of the loop

Example: //simple do while program #include<stdio.h>


True

#include<conio.h> void main() { int ctr=0; clrscr(); do

Condition

False

49 # 55

{ printf(" Computers are fun!\n"); ctr++; } while(ctr<0); getch(); } OUTPUT

for loop:
The for loop is another entry-controlled loop, that enables you to repeat sections of your program for a specific number of times unlike the while and do-while loops, the for loop is a determinate loop, and then initialization and test condition and increment and decrement in single lines syntax: for (initialization; test condition; increment/decrement operator) { Body of loop; }

50 # 55

Initialization Increment/Decrement

Example: //simple for program #include<stdio.h> #include<conio.h> void main() { int total,ctr; total=0; clrscr(); for(ctr=100;ctr<=200;ctr++) { total+=ctr; } printf(\n***OUTPUT***\n); printf("The total is %d",total); getch(); }
False Condition True Body of the loop

51 # 55

OUTPUT

NESTED LOOPS: One for loop statement within another for loop statement called nested for loop. Syntax: for () { . for (..) { . } } Example: #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=5;i++)

52 # 55

{ for(j=1;j<=i;j++) { printf("%d",j); } printf("\n\n"); } getch(); } OUTPUT

JUMPS IN LOOPS:
Jumping Out of loop: Exiting from a loop can be used by break or goto statement. When a break statement is used inside a loop, the loop is immediately exited and the program continues with the statement immediately follows the loop. When the break is used in nested loop the program will exit only from the single loop.

53 # 55

Example: a) while () { if (condition) break; Exit From loop } Exit from loop b) do { . . if (condition break; }while (.);

c)

for () { . . if (error) break;

d)

for () { . for (..) { .. if (condition) break;

Exit from loop }

.. .. Exit from Inner loop .............. } .

. }

Skipping a part of loop: During the loop operations, to skip a body of loop under some conditions we may use continue statement. It tells the compile to skip the following statement and then continues with the next iteration.

54 # 55

Example: a) while (test-condition) { -------------if (-----------) continue; --------------------} b) do { --------------if (-----------) continue; --------------------}while(test-condition);

c)

for (initialization; test condition; increment/decrement operator) { -----------if -----------) continue; --------------------------}

THE STANDARD HEADERS Each standard library function is declared in one or more of the standard headers. These headers also contain all the macro and type definitions that the C standard provides. This chapter describes the contents and use of the standard headers. Each of the standard headers contains a set of related function declarations, macros, and type definitions. The standard headers are also called header files, as the contents of each header are Usually stored in a file. Strictly speaking, however, the standard does not require the headers to be organized in files.

55 # 55

The C standard defines the following headers.

assert.h ctype.h stdio.h

limits.h math.h conio.h

signal.h stdarg.h stddef.h

stdlib.h string.h time.h

You might also like