1 UNIT IV INTRODUCTION TO C 1. OVERVIEW OF C C is portable, structured programming language. It is robust, fast.extensible. It is used for complex programs. The root of all modern language is ALGOL (1960). BCPL (Basic Combined Programming Language) a user friendly OS providing powerful development tools developed from BCPL. Assembler tedious long and error prone. A new language ``B'' a second attempt. c A totally new language ``C'' a successor to ``B''. c By 1973 UNIX OS almost totally written in ``C''. Characteristics of C Some of C's characteristics that define the language and also have lead to its popularity as a programming language. Small size Supports variety of data types and a set of operators. Extensive use of function calls Enables the implementation of hierarchical and modular programming with the help of functions. C can extend itself by addition of functions to its library continuously. Structured language
2 Low level (BitWise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions. C has now become a widely used professional language for various reasons. It has high-level constructs. It can handle low-level activities. It produces efficient programs. It can be compiled on a variety of computers. Basic structure of C program Documentation Section Link section Definition section Global declaration section main() function section Declaration part Executable part Sub program section Function 1 Function 2 (user defined functions) Function n
3 2. CONSTANTS, VARIABLES, DATATYPES CONSTANTS Constants in C are applicable to values, which do not change during the execution of a program. C constants are classified as o Numeric constants Integer constants Real constants o Character constants Single character constants String constants 1. Numeric constants a. Integer constants Sequence of numbers from 0 to 9 without decimal point or fractional part or any other symbols. Minimum 2 bytes, maximum 4 bytes. It may be positive or negative or zero Eg:10,+30,-15 b. Real constants floating point constants many parameters are defined in real constants like height,length,distance. Eg:2.5,3.14 It can be written in exponential notation. 2. Character constants a. Single character constant Single character Single digit or single special symbol or white space enclosed within a pair of single quote marks. Characters constants have integer values known as ASCII values.
4 Eg: a, 8, u b. String constants Sequence of characters enclosed within double quote marks. String may be a combination of all kinds of symbols. Eg: hello, India, 444, a VARIABLES During program execution, value of variables can be changed. Variable can be of different data types. Variable is a data name used for storing a data value. Value may be changed during program execution Variable name may be declared based on the meaning of the operation. Eg: height, average, sun. Rules for defining variables Must begin with a character without spaces but underscore is permitted. Length of the variable varies from a computer to another. Variable should not be a C keyword. May be a combination of lower and upper characters. Variable should not start with digit. DATA TYPES C support variety of data types. Data is represented using numbers or characters. C is a so called type safe programming language, that is, any variable needs to be assigned a supported data type. C supports the following data types: /* elementary data types */ bool char short
5 int double float long signed char, int, short, unsigned char, int, short, /* customized or non-elementary data types */ struct enum Data types Size(bytes) Format specifier Char 1 %c Unsigned char 1 %c Short or int 2 %i or %d Unsigned int 2 %u Long 4 %ld Unsigned long 4 %lu Float 4 %f or %g Double 8 %lf Long double 10 %lf Declaring variables Should be done in declaration part of the program. Compiler obtains the variable name. It tells the compiler the data type of the variable being declared and helps in allocating the memory. Syntax: data type variable name int age;
6 Initializing variables Variables declared can be assigned or initialized using an assignment operator =. Syntax: Variable-name = constant Or Data-type variable name = constant Eg: int y=2; int x, y,z; Example program: Addition of two numbers #include<stdio.h> #include<conio.h> void main () int a,b,c; printf( enter the values of a and b ); scanf( %d %d,&a,&b); c=a+b; printf( the value of c is=%d,c); getch(); 3. OPERATORS & EXPRESSIONS An operator indicates an operation to be performed on data that yields a value. An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C language program to operate on data and variables. C has a rich set of operators which can be classified as
7 1. Arithmetic operators +,-,*,/ and % 2. Relational Operators >,<,==,>=,<=,!= 3. Logical Operators &&,,! 4. Increments and Decrement Operators ++,-- 5. Assignment Operators = 6. Bitwise Operators &,/,>>,<<,~ 7. Comma operator, 8. Conditional Operators?: 1. Arithmetic Operators All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe operand, therefore the number 5 when operated by unary will have the value 5. Operator Meaning + Addition or Unary Plus Subtraction or Unary Minus * Multiplication / Division % Modulus Operator Examples of arithmetic operators are x + y x - y -x + y a * b + c -a * b here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language which evaluates the remainder of the operands after division.
8 2. Relational Operators Often it is required to compare the relationship between operands and bring out a decision and program accordingly. This is when the relational operator comes into picture. C supports the following relational operators. Operator Meaning < is less than <= is less than or equal to > is greater than >= is greater than or equal to == is equal to!= is not equal to 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. Given below is a list of examples of relational expressions and evaluated values. 3. Logical Operators C has the following logical operators, they compare or evaluate logical and relational expressions. Operator Meaning && Logical AND Logical OR! Logical NOT (&&) 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.
9 Example a > b && x = = 10 The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to Increment and decrement operator: It is used to increment or decrement the value Eg:i++; j--; 5. Assignment Operators The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. Example x = a + b Here the value of a + b is evaluated and substituted to the variable x. In addition, C has a set of shorthand assignment operators of the form. var oper = exp; Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator 6. Bitwise operator Operator Meaning >> right shift << left shift ^ bitwise XOR ~ one s complement & bitwise AND bitwise OR
10 7. Comma operator It is used to separate two or more expressions. Eg:a=2,b=4,c=a+b; 8. Conditional operator Syntax: Condition?(expression1) expression2); If the condition true,the expression 1 is evaluated. If the condition is false,the expression2 is evaluated. Expressions Arithmetic Expressions An expression is a combination of variables constants and operators written according to the syntax of C language. In C every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable. Some examples of C expressions are shown in the table given below. Algebraic Expression C Expression a x b c a * b c (m + n) (x + y) (m + n) * (x + y) (ab / c) a * b / c 3x2 +2x + 1 3*x*x+2*x+1 (x / y) + c x / y + c Evaluation of Expressions Expressions are evaluated using an assignment statement of the form Variable = expression; Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and then replaces the previous value
11 of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. Example of evaluation statements are x = a * b c y = b / c * a z = a b / c + d; The following program illustrates the effect of presence of parenthesis in expressions. main () float a, b, c x, y, z; a = 9; b = 12; c = 3; x = a b / 3 + c * 2 1; y = a b / (3 + c) * (2 1); z = a ( b / (3 + c) * 2) 1; printf ( x = %fn,x); printf ( y = %fn,y); printf ( z = %fn,z); output x = 10.00
12 y = 7.00 z = 4.00 Precedence in Arithmetic Operators An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C. High priority * / % Low priority + - Rules for evaluation of expression First parenthesized sub expression left to right are evaluated. If parenthesis are nested, the evaluation begins with the innermost sub expression. The precedence rule is applied in determining the order of application of operators in evaluating sub expressions. The associability rule is applied when two or more operators of the same precedence level appear in the sub expression. Arithmetic expressions are evaluated from left to right using the rules of precedence. When Parenthesis are used, the expressions within parenthesis assume highest priority. Operator precedence and associativity Each operator in C has a precedence associated with it. The precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may
13 belong to one of these levels. The operators of higher precedence are evaluated first. The operators of same precedence are evaluated from right to left or from left to right depending on the level. This is known as associativity property of an operator. The table given below gives the precedence of each operator.
14 4. MANAGING INPUT/OUTPUT OPERATORS: Input/Output functions are classified into two types. They are, Formatted functions Unformatted function Formatted functions Read and write all types of data values. Require conversion symbol to identify the data type. Return the values after execution. Unformatted functions Only work with character data type. Do not require conversion symbol for identification of data type. Return values are always same.
15 Input/Output Functions Formatted Functions Unformatted Functions Input Output Input Output scanf() printf() getch() putch() getche() putchar() getchar() put() gets() Formatted Functions: 1. printf () statement: Prints all types of data values to the console. Requires conversion symbol and variable names to print the data. Eg: main () int x=2; float y=2.2; char z= c ; printf( %d %f %c,x,y,z); Output c
16 2.scanf () statement Reads all type of data values It is used for run time assignment of variables. Requires conversion symbol to identify the data to be read Syntax: scanf( %d %f%c,&a,&b,&c); &-address operator-: prints the memory location of the variable. It indicates memory location,so that the value read would be placed at that location. It also returns values. Return value is exactly equal to the number of values correctly read. If any mismatch error will shown. Eg; #include<stdio.h> #include<conio.h> main() int a; clrscr(); printf( Enter the value of A ); scanf( %c,&a); printf( A=%c,a);
17 Output: Enter the value of A =8 A=8 Escape Sequences: printf(),scanf() statements follow a combination of characters called as escape sequences.it starts with \ \ n newline \ b backspace \ f formfeed \ singlequote \\ backslash \0 NULL \ t horizontal tab \ r carriage return \ a alert(bell) \ double quotes \ v vertical tab \? question mark Eg:Average of three real numbers. #include<stdio.h> #include<conio.h> main()
18 float a,b,c,d; clrscr(); printf( Enter three float numbers:\n ); scanf( \n %f %f %f,&a,&b,&c); d=a+b+c; printf( \n Average of given numbers:%f,d/3); Output: Enter three float numbers: Average of given numbers: 3.5 Unformatted Functions: There are three types of I/O functions. 1) Character I/O 2) String I/O 3) File I/O 1. Character I/O a) getchar() It reads character type data from the standard input. It reads one character at a time till the user presses the enter key. b) putchar() It prints one character on the screen at a time, which is read by the standard input.
19 c) getch() and getche() These functions read any alphanumeric characters from the standard input device. Character entered is not displayed by getch() function d) putch() It prints any alphanumericcharacter taken by the standard input device. 2.String I/O a) gets() It is used for accepting any string through stdin keyboard until enter key is pressed. stdio.h is needed for implementing the above function. b) puts() It prints the string or character array. c) cgets() It reads strings from the console. Syntax: cgets(char *st); d. cputs() It displays string on the console. Syntax : cputs(char *st); 3.File I/O fprintf() - write values to files. fscanf() - read values from files. getc() - reads a single character from operand file and moves the file pointer. putc()- writea single character into a file.
20 fgetc() - reads a character and increase the file pointer position. fputc() - writes character to file shown by the file pointer. fgets() - reads the string. fputs() - write the string to operand file. putw() - write an integer value to file. getw() - returns the integer value and increase the pointer. Commonly used library functions: a) clrscr() - clear the screen -> conio.h b) exit () - terminates the program->process.h c) sleep() -pause the execution of program for a given number of seconds-dos.h d) system () - helpful in executing different dos. 5. DECISION MAKING: Program is the execution of one or more instructions. Based on the condition, the order of execution may change. On the basis of applications it is essential to Alter the flow of a program. Test the logical conditions. Control the flow of execution as per the selection. C language supports the control statements as listed below. if statement if-else if-else.if switch() case 1. if statement: syntax: if(condition) statement; eg:
21 if (a>b) printf( a is greater ); 2. if-else: Syntax: if(condition is true) execute statement1; else execute statement2; Eg: if (a>b) printf( a is greater ); else printf( b is greater ); 3. Nested if-else: Rules: Nested if else can be chained with one another. If condition is false, control passes to else block. If one of the if statement satisfies the condition, other nested else if will not be executed. Syntax: if ( condition) statement1; statement2; else if( condition) Statement3;
22 Statement4; else Statement5; Statement6; Eg: finding biggest of three numbers. #include<stdio.h> #include<conio.h> main() int a,b,c,big; clrscr(); printf( Enter three numbers ); scanf( %d %d %d,&a,&b,&c); if(a>b) if(a>c) big=a; else big=c; else if(b>c)
23 big=b; else big=c; printf( \n Biggest number is %d,big); getch(); Output: Enter three numbers: 18,-5, 13 Biggest number is switch() It is multiway branch statement. It requires only one argument of any data type, which is checked with number of case options. If value matches with case constant, particular case statement is executed. If not matched, default is executed. Every case terminates with : symbol. break is used to exit from current case. Syntax: switch (variable or expression) case constant A: Statement; break; case constant B: Statement; break;
24 default: statement; Eg: Program to find value of y #include<stdio.h> #include<conio.h> #include<math.h> main() int n; float x,y; clrscr(); printf( \n Enter values to x and n: ); scanf( %f %d,&x,&n); switch(n) case 1: y=1+x; break; case 2: y=1-x; break; case 3: y=1+pow(x,n) break; default: y=1+n*x;
25 break; printf( \n value of y(x,n)=%f),y); getch(); Output: Enter value to x and n: Value of y(x,n)=3.10 break statement: It allows programmers to terminate the loop. It skips from loop or block in which it is defined. continue statement: It is opposite to break. Continuing next iteration of loop statements. It does not terminate, bit it skips the statements. goto statement: It does not require any condition. It passes control anywhere in the program Syntax: goto label;
26 Eg: even or odd using goto. #include<stdio.h> #include<conio.h> #include<stdlib.h> main() int x; clrscr(); printf( \n Enter a number: ); scanf( %d,&x); if( x%2==0) goto even; else goto odd; even: printf( \n %d is even number ); return; odd: printf( \n %d is odd number ); Output: Enter a number: 5 5 is odd number.
27 Difference between break and continue break Exits from current block or loop Control passes to nest statement Terminates the program continue Loop takes next iteration Control passes to the beginning of loop Never terminates the program 5. BRANCHING AND LOOPING: Branching and looping are used for repetitive tasks. Loop: A loop is defined as a block of statements which are repeatedly executed for certain number of times. Terms in loop are Loop variable Initialization Incrimination or decrimination Loops in C language are for() while() do while() a) for loop It allows for executing a set of instructions until a certain condition is satisfied. Syntax: for (initialize;test condition;re-evaluation parameter) Statement; Statement;
28 Formats: for (;;) infinite loop no arguments for (a=0;a<=20;) infinite loop a is neither increased nor decreased for( a=0;a<=10;a++) displays value value of a is displayed printf( %d,a); from 0 to 10 from o to 10 for(a=10;a>=0;a--) printf( %d,a) displays from 10 to 0 value a is decreased from 10 to 0 Eg: display numbers from 1 to 15 using for loop #include<stdio.h> #include<conio.h> main() int i; Output: 1 2 clrscr(); for( i=1;i<=15;i++) printf( %d,i);
29 Nested for loops: Using loop within loop Eg: finding perfect cubesof1,2,3,4 #include<math.h> main() int i,j,k; clrscr(); printf( Enter a number ); scanf( %d,&k); for(i=1;i<k;i++) for(j=1;j<=i;j++)
30 if(i==pow(j,3)) printf( \n Number: %d & its cube :%d j,i); Output: Enter a number: 1000 Number:1 & its cube :1 Number:2 & its cube :8 Number:3 & its cube :27 Number:4 & its cube :64 b) While loop: syntax: while (test condition) Body of the loop; Loop statements will be executed till the condition is true. Test condition is evaluated and if the condition is true, body of the loop is executed. When condition becomes false the execution will be out of the loop. Eg: add 10 consecutive numbers starting from 1 main()
31 int a=1;sum=0; clrscr(); while(a<=10) printf( %d,a); sum=sum+a; a++; printf( \n Sum of 10 numbers:%d,sum); Output: Sum of 10 numbers: 55 c) do-while loop: syntax: do Statement; while (condition); condition is checked at the end of the loop. do-while loop will execute atleast one time even if the condition is false initially. do-while loop executes until the condition becomes false.
32 Eg: main() int i=1; clrscr(); do printf( \n This is a program of do while loop ); i++; while(i<=5); Output: This is a program of do while loop This is a program of do while loop This is a program of do while loop This is a program of do while loop This is a program of do while loop d) do while statement with while loop syntax: do while(condition) Statements; while(condition);
33 Eg: Print values from 1 to 5 using while statement in do while loop main () int x=0; clrscr(); do while(x<5) x++; printf( \t %d,x); while(x<1); Output