You are on page 1of 20

PROGRAMMING IN C

INTRODUCTION TO C
C is an offspring (child) of Basic Combined Programming Language (BCPL) called B. B was developed in 1960s at Cambridge University. B was modified by Dennis Ritchie, at Bell Laboratories in 1972. C is strongly associated with UNIX because developed in UNIX. C runs under MS-DOS. IMPORTANCE Of C Robust C is having set of built-in functions & operators used to write Complex Programs. Efficient & Fast C programs due to variety of data types & operators. Portable C programs written for 1 computer can be run on another computer without modification. Extend ability we can add our own function to c library.

STRUCTURE OF C PROGRAMS
Documentation Section Link Section Definition Section Global Declaration Section Main Function Section Declaration Part Executable Part Sub Program Section Documentation Section: Set of comment lines, giving name of program author etc.

Link Section: Link the Functions from C Library. Definition Section: Defines all Symbolic constants. Global Declaration Section: Global variables are used in more then 1 functions. Main Function Section: Declaration part: Declares all variables used in executable part. Executable part: At least 1 statement. Two parts within open & close braces. Execution begins at open brace ends at close brace. Close brace logical end of program. All statements end with. Sub Program Section: All user-defined functions are placed in this section. Usually placed immediately after main () function. Can appear in any order. All sections except main () function may be absent. Sample program /* Addition program*/ #include<stdio.h> #define MAX 100 int a=10; main () { int b; b=add(a,MAX); printf(%d,b); } int add(int x, int y){ return(x+y); } 2

Important Points: Every C program requires a main () function. Use of more than one main () is illegal. C programs are written in lower case letters. Upper case are used for symbolic constants and output strings. All words in program must be separated by a space, tab or a punctuation mark. Every statement ends with semicolon. All variables must be declared.

C TOKENS
In C program the smallest individual units are called tokens. C has 6 types of tokens. eg) C TOKENS

Keyword

Identifiers

Constants

Strings

Special symbols

Operator s

Keywords: System defined words are keywords. All keywords have fixed meaning and those meaning cannot be changed. Keywords are the basic building blocks of program. Eg: auto, for int, while etc Identifiers: User defined words are identifiers. Identifiers are the names of variables, functions and arrays. They consist of a sequence of letters and digits. First letter must be a character. Underscore is also permitted. Eg: total, pass_mark. 3

Constants: The value which does not change during the execution of a program is called constants. -Two types of constants: 1. Numeric constant 2. Non-numeric constant Numeric constant -It is a collection of numeric digits with special characters +,-, and. -Two types of Numeric constant -Integer constant and Float constant Integer constant -It refers to a sequence of digits without any decimal points. -eg) 15, 56, +98,-67 Float constant It contains sequence of digits with decimal points. Eg) 6.432,+18.92,-17.3

Non-Numeric constant -Is a sequence of letters. Two types Single character constant A single character constant consists a single character enclosed within a pair of single quotes. Eg: 5,x,;, - 5 is not the same as number 5. Character constants have integer value known as ASCII values.Eg:printf(%d,a); This will print the value 97 because the ascii value of a is 97. Eg: 2 printf (%c, 97); this will print the letter a.

String constant: A string constant is a sequence of characters enclosed in double quotes. The characters may have letters numbers, special characters and space. Eg: : Hello , 2006, 5+3, GOOD LUCK

Special symbols: - In C,!,@,#,$, %,^,&,*,(,),{,} are called special symbols. Operators,: +, _ , *, /,<,>,<=,>=,=,%,&&,||,! are some of the operators in C.

DATA TYPES IN C
-Data types specifies the type of data which is used to assign a variable -Three classes of data types: 1. Primary data types (or) Fundamental data type 2. User defined data types 3. Derived data types Primary data types: -Available in most of the computer languages. -Also called as Standard data type. Primary Data types Integer Signed int short int long int Unsigned unsigned int unsigned short int unsigned long int Character char signed char unsigned char

Floating point type float double long double void

Size and Range Data type char int float double User defined data type: -A data type which is created by the user is called as the user defined data type. -Two types: 1. typedef 2. Enumerated data type Typedef: -Used to give name to the available data type. -General format is typedef type identifier; -here, type refers to existing data type. -identifiers refer to new name given to the data type. Eg) typedef int x; We can declare the integer variables a, b like the following: X a, b; //which is equivalent to int a, b; Enumerated data type -user is defined the data types. -Assigning the variable values. Syntax: Enum identifier{v1,v2,v3}; -The compiler will assign the digits for each value begins with 0 and so on.. eg) enum day{Monday,Tuesday,..Sunday}; size (bits) 8 (1 byte) 16 (2 bytes) 32 (4 bytes) 64 (8 bytes) Range of values -128 to 127 -32,768 to 32,767 3.4 e-38 to 3.4 e+38 1.7 e-308 to 1.7 e+308

//program for Enumeration void main() { enum day{sun=1,mon,tue,wed}; enum day5{sund=5,mond,tues,wed}; printf(\n Sunday=%d,sun); printf(\n Monday=%d,mon); printf(\n Tuesday=%d,tue); printf(\n \n \n); printf(\n Sunday=%d,sund); printf(\n Monday=%d,mond); printf(\n Tuesday=%d,tues); } output: Sunday=1 Monday =2 Tuesday=3 Sunday=5 Monday=6 Tuesday=7 Derived data type: - (arrays, structures, unions and functions) -Data type to be used for grouping more than one data.

VARIABLES
-Its a quantity whose value can be changed during the execution of the program. - It is a data name used to store value. -A variable name can be chosen by the programmer. Eg) amount, height, total, salary Rules for forming the variable: -Must begin with an alphabet. -length of 36 characters -Uppercase and lowercase variables have different meaning. Eg) variable Total is different from variable total. -It should not be a keyword -white space not allowed. Two types: -Global variable -local variable Global variable: -In a c program if a variable is used in all the functions, then it is called as global variable. Local variable: -If a variable is used within a function, then the variable is called as local variable.

ARRAYS:
An array is a group of related data items that share a common name. the individual elements can be identified by index or subscript, in brackets after array name. Declaration of arrays: Arrays must be declared before they are used. It has the general from: Type variable-name[size]; Type specifies the datatype of element. Size indicates the maximum number of elements that can be stored inside the array. Eg: float height[50]; 8

This array can store 50 real elements. Initialization of arrays: We can initialize the elements of arrays when they are declared. It has the general from: Type arrayname[size]={list of values} Eg1: int n[3]={0,0,0}; N is an integer array of 3 elements each element is initialized to 0. Eg2: float total[5]={0.0,15.75,-10}; This will initialize the first three elements to 0.0,15.75 and 10.0, the remaining 2 elements will be 0. size of array can be omitted while initializaing. Eg: int counter[]={1,1,1,1}; One-dimensional Arrays: List of items with one variable name and only one subscript is called onedimensional array. Eg: int number[5]; Usually the subscript starts with 0 Number[0],number[1],. . . . . . . .number[n]. Example program using one dimensional array //Sum of n numbers void main() { int sum=0,a[10],i ,n; printf(Enter the value of n:); scanf(%d,&n); for(i=0;i<n;i++) { scanf(%d,&a[i]);

} for(i=0;i<n;i++) { sum=sum+a[i]; } printf(Sum=%d,sum); } Character arrays: String are treated as character arrays. C compiler adds a null character \0 at the end of strings. So we must allow one extra element space for null terminator. Eg: char name[10]; Suppose, WELL DONE is assigned to name then it will be allocated as W E L L D O N E \0

Two-dimensional arrays: An array with 2 subscripts is called a two-dimensional array or a table. The first index refers to the rows and the second index refers to the columns of the table. The twodimensional arrays are declared as, Type array-name[row-size][column-size]; Two dimensional arrays are stored in memory as: Col0 (0,0) col1 (0,1) col2 (0,2) Row0 Row1 Row2

10

Initializing two-dimensional arrays: Eg: int table[2][3]={0,0,0,1,1,1}; This initializes the elements of first row to 0 and the second row to 1 initialization is done row by row. This is equivalent to Int table[2][3]={{0,0,0},{1,1,1}}; (Note: write example program using two dimensional array for the examination) Multidimensional arrays: Arrays with three or more dimensions. They are declared as, Type array-name[s1][s2][s3].[sn]; Eg: int survey[3][5][12];

Library functions:
-The functions which are not written by the user are called as the library functions or Builtin-functions. -These functions are also called as Pre-defined functions. Mathematical functions: -For doing some mathematical calculations in real time problem, we can use these functions such as sqrt, sinx, log etc., The mathematical functions are stored in math.h library. If any of these function is to be called, the header file is to be included as #include<math.h> (note: Give example program using math.h) String functions: These functions are used for processing the strings. A string is an array of characters. These functions are stored in a header file, string.h.if any function is to be called,the header file is to be included as #include<string.h> string functions are: (i)strlen()-It is a function to find the length of the string. (ii)strcpy()-It is a function to copy the content of one string to another. (iii)strcat()-It is a function to concatenate one string to another. (iv)strcmp()-It is a function to compare two strings.

11

(v)strrev()-It is a function to reverse a string. ctype functions: These functions are used for finding the given character is digit, space, lower case, uppercase, alphabet, and alpha numeric. These functions are stored in a header file, ctype.h.if any function is to be called, the header file is to be included as #include<ctype.h> ctype functions are: (i)isspace() (ii)islower() (iii)isupper() (iv)isdigit() (v)isalpha() (vi)isalnum() (note: Give example program using this ctype functions for the examination) )

OPERATORS
An operator is a symbol used for doing operation. C operators are classified into number of categories. They include Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators

12

Arithmetic operators -These operators are used for forming arithmetic expression (mathematical expression) + * / % real operands. For example, a=14 and b=4 then a+b=18, a-b=10,a*b=56, a/b=3(decimal part truncated) a%b=2(remainder of division) During modulo division, the sign of the result is always the sign of the first operand. Eg: -14%3=-2, -14%-3=-2, 14%-3=2. Relational Operators: -These operators ate used for defining relational expression. -we may compare the marks of two persons, or price of two items. These comparisons can be done with the help of relational operators. Using relational operators we can compare two operands. The relational operators are <, <, <=,>,>=, ==,! =. Eg: 4.5<=10 4.5<-10 a+b!=c+d Logical operators: These operators are used to combine two or more relational expressions. C has the following logical operators: && logical AND 13 True False Addition or unary plus Subtraction or unary minus Multiplication Division modulo division

% operator gives the remainder and it leaves the fractional part. It cannot be used with

|| ! Eg:

logical OR logical NOT

If(A>b && x==10) this expression returns true only if both the conditions are true. If (number<0 || number>100) this expression returns true if any one of the two conditions is true. Assignment operator Assignment operator is used to assign a value to the variable. = is the assignment operator. Shorthand assignment: It is also used as V op=exp; where v is the variable, exp is expression, op is a binary arithmetic operator.op= is known as shorthand assignment operator. Also, x+=y+1; is equivalent to x=x+(y+1); Here the shorthand operator += means add y+1 to x. For example, x=x+3 can be written as x+=3 Increment and Decrement operators: -Used for incrementing and decrementing the value of variable. -Two formats: -post increment operator .ie) variable ++ -pre increment operator ie) ++ variable -Increment operator adds 1 to the operand and decrement operator subtracts 1 from the operand. ++ is the increment operator and -- is the decrement operator. They can be used as ++m; (preincrement) Eg: m=5; Y=++m; Y will be 6. or m++ ;( post increment) --m ;( predecrement) or m-- ;( post decrement)

14

The preincrement operator first increment the operand by 1 and then assigns the value to the variable. -Post increment operator first assigns the value to the variable and then increments the operand. Eg: m=5; y=m++; y will be 5 and m will be 6. Similarly predecrement and post decrement operators work. Conditional operators: -Used for the conditions. General format is Variable =condition? a.exp1:a.exp2 Eg) a=10; b=15; x= (a>b)? a: b; Eg) big=(x>y) x : y; -if the values of x and y are 10 and 12, then big=12.because the condition is false, so the value of exp2 is assigned to big. -if the x and y are 100 and 10 then big=100, because condition is true so the value of exp1 is assigned to big. Bitwise operators: -Some of the operators are used to do the bitwise operators. -A bit is a binary digit where value is either 0 or 1. -bitwise operators are: & | ^ << Bitwise AND Bitwise OR Bitwise XOR(exclusive OR) Shift left

15

>> ~

Shift right Ones Complement

Special operators: -Comma and size of () are the special operators. Comma operator: It is used to link related expressions together. Eg: Val=(x=10, y=5, x+y); The expression is evaluated from left to right and the value of Val will be 15. Comma operator is also used in loops. sizeof operator: It is a compile time operator and it returns the number of bytes the operand occupies, Eg: int x; sizeof(x); will return 2.

Expressions
-It is a collection of variables and constants with the operators. -Three types of expressions: *Arithmetic Expression *Relational Expression *Logical Expression Arithmetic Expression: -Is an expression in which variables and constants are combined with arithmetic operators. -The arithmetic operators are + * / % Eg) a+b%35 Addition or unary plus Subtraction or unary minus Multiplication Division modulo division

16

Y-25+45 Relational Expression: -Is an expression in which variables and constants are combined with the relational operators. -The resultant value of relational expression is either true or false -Relational operators are < <= > >= == != Eg) a>=b b==c Logical Expression: -Is an expression in which the variables and constants are combined with the logical operators. -Logical operators are && logical AND || ! logical OR logical NOT Lesser than lesser than or equal to Greater than Greater than or equal to Equal to Not equal to

-Used to combine more than one relational expression. General Format is Relational expression1 logical operator Relational Eg) if ((a<b) && (a>c)) if ((mark1>50) ||(mark2>50)) Evaluation of an expression: -Some rules to evaluate the arithmetic expression. -Rules are called as priority Rules. -Also called as hierarchy rules.

17

Rule 1: If an expression contains parenthesis expression within the parenthesis will be performed first. Rule 2: If an expression has more than one parenthesis the inner parenthesis is performed first. Rule 3: If more one symbols of same priority, it will executed from left to right. Eg) Let X=2, Y=5 Then the value of expression (((y-1)/x)*(x+y)) is calculated as -First evaluation is done on the innermost parenthesis. (Y-1)= (5-1) =2 =>T1 -Second evaluation is done on next outer parenthesis. (T1/x)= (4/2) =2 =>T2 -Third evaluation is done on the next parenthesis (x+y)= (2+5) =7 =>T3-Last evaluation is for finding the value of whole expression. (T2*T3)= (2*7) =14 =>14

Input/output statements in c
-Input functions: (i) getchar () (ii) scanf () (iii) gets () getchar (): -The getchar function returns single character from a standard input device. -The function does not require any arguments. Syntax: character variable=getchar (); c=getchar (); -The getchar function gets characters and the value is assigned to the character variable c. scanf(): -This function can be used to enter any combination of numerical values, single characters and strings.

18

Syntax; scanf(control string,args1,args2..argsn); -args1, args2. argsn represents the individual input data items. Control string %c %d %f %s gets (): -gets () accept a single arguments. The arguments must be a data item that represents a string. Eg)#include<stdio.h> Void main() { char line[80]; gets(line); } Output functions: (i)putchar() (ii)printf() (iii)puts() putchar(): -The putchar function transmit a single character to a standard output device Syntax: putchar (character variable); Eg) putchar(c); The character stored in c is printed to the screen. printf(): -The function can be used to output any combination of numeric values, single characters and strings. single character integer float string

Eg) scanf (%d, &x);

19

Syntax: printf(control string,args1,args2..argsn); puts(): -puts() accepts a single arguments. The argument must be a data item that represent a string. Eg) #include<stdio.h> void main() { int i=123; printf(%6d,i); printf(%-6d,i); } (Note: Write more example program using I/O and O/p statements for the examination)

20

You might also like