You are on page 1of 161

C Tutorials

1.1 1.2 1.3 1.4 1.5 1.6 Learn C in 15 days C Introduction (4 topics) C in 10 days (Fundamentals) C Basics and Keywords Learn C in 7 days 26 Points about C basics

C Examples
2.1 2.2 C Basic Examples C Programming Examples

C Interview Questions with Answers


3.1 3.2 3.3 3.4 3.5 3.6 C C C C C C Subjective Questions with Answers Interview Questions with Answers Objective Questions And Answers FAQs Basics Objective Questions & Answers Basic Subjective Question & Answers

Hot C Topics
4.1 4.2 4.3 4.4 4.5 4.6 Array Basics C Functions C Memory Management C Pointers C Data Structures C File Handling Basic C Tutorials with Examples 1.Induction, Features and History of C. 2.Sample of C program, Advantages and Disadvantages of C and Data Types. 3.Integers,float and characteristics. 4.Characters Types, Size in Bytes and Range. 5.What Are Variables and Types of Operators. 6.Program Using the Operators. 7.Diffrents Types of Loops.

8.Program Using for Loops 9.Use of Continue and Break Statements. 10.Use of Switch Statements. 11.Arrays. 12.Multidimensional Arrays. 13.Example of Arrays. 14.What is Function in C. 15.Register variables, Prototyping ,Preprocessor and How to use functions. 16.Example of Function. 17. Benefits of Function and Pointers in C With Example. 18.Introduction of Structure. 19. Accessing the members of Structure. 20. Structure With typedef Keyword and Use of sizeof function. 21.Example of Structure. 22.Introduction of String. 23.Dynamic memory allocation 24.Allocating memory and use of calloc - malloc function. Introduction of C C is programming language developed in the at AT and Tee Bell Laboratories of USA in 1972's. It was designed and developed by man named Dennis Richte. C is so popular because it reliable and simple and easy to use, with the help of C language new languages are born known as C++, Java, C# and many other languages. Learning in C--( Alphabets, symbols ,digits)--(constant, variables, keywords)--(Instructions)-(Progams) Alphabets are : A,B,C.. Z. Symbols: ~,@,#,$,%,^,&,*,(),_, etc. these are also called special symbols. Digits: 1,2,3,4,5,6,7,8,9,0.

History Of C Before using C we were using language which is known as B, now what is B: it was on Interpreter based and had performance drawbacks. So Dennis Ritchie developed language known as C in 1972s. And it was famous as Mother Language of the computer system. It was based on compiler. Strong Point as compare to B : In C language Compiler (Translator) compiles the whole source code to Machine code where as interpreter read the source code line by line or step by step. Features of C 1. C language is the structured programming language because it has some standards. 2. Code reusability means we can use the code from environment to other environment. 3. Built in type float, int etc expressions, operators. 4. Syntax for decision control. 5. It has some libraries which pre is defined.(preprocessors). 6. File organization (.c, .cpp etc) A sample of C Program #include <stdio.h> // Preprocessor main () // main function { // opening the brackets Printf(Hello); } // close the brackets. Advantages Of C 1. 2. 3. 4. 5. 6. C is a small , efficient ,powerful and flexible language C is close to computer H/W (architecture). C is standardized, making it more portable compare to other languages. It contains libraries. Many other languages borrow from Csyntax for ex: Java, java script, perl. UNIX was written in C.

Disadvantages of C 1. C is designed for professional users. 2. C was not able to automatic checking compare other languages. 3. C does not support modern concept like OOPs and multithreading. Data Types In C Mainly there are two types of data types: 1. Simple or primivitive. 2. Compound or structured or derived. An primitive data is fundamental unit of information which cannot be broken down further. Simple: integers, floats, characters, pointers. Derived data is made up of one or more simple data items.

Compound : arrays, structures, unions Integers in C Integers stores numeric value without a decimal point in the system memory. Types Short int Int Long int Bytes required 2 4 4

Floats in C It stores numeric values with decimal point in the system memory. Types Float Double Long double Characters in C Bytes required 4 8 8

data type which stores an element of machine character set. The character set is used is usually ASCII set, it is denoted by char. It takes only one byte. Also singed and unsigned both occupy one byte having different ranges. The primary data type themselves could be of several types. for example Character char could be Unsigned char. or Signed char. The values stores in the given integer variables will always be be positive. for example we can declare a variables to be unsigned. unsigned int num_student, The range of integer values is -32768 to +32767 value s for a 16 bit OS to range 0 to 65535.char ch =A; where ASCII value of A is 65.

Characters Types, Size in Bytes and Range Type Name Bytes Range ------------- 16 bit system ------------char 1 -128 to 127 signed char 1 -128 to 127 unsigned char 1 0 to 255 short 2 -32,768 to 32,767 unsigned short 2 0 to 65,535 int 2 -32,768 to 32,767 unsigned int 2 0 to 65,535 long 4 -2,147,483,648 to 2,147,483,647 unsigned long 4 0 to 4,294,967,295 float 4 3.4E+/-38 (7 digits) double 8 1.7E+/-308 (15 digits) long double 10 1.2E+/-4932 (19 digits)

------------- 32 bit system ------------Type Name Bytes Range

char signed char unsigned char short unsigned short int unsigned int long unsigned long float double long double

1 1 1 2 2 4 4 4 4 4 8 10

-128 to 127 - 128 to 127 0 to 255 -32,768 to 32,767 0 to 65,535 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 3.4E+/-38 (7 digits) 1.7E+/-308 (15 digits) 1.2E+/-4932 (19 digits)

What is Variables? A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer. For ex: int a =10; int a // initialization // declaration

Operators in C Operators are: 1. Arithmetical operators 2. Logical operators 3. Relational operators 4. Bitwise operator 5. Shift operators Arithmetic operators: These operators are used for the for mathematical expression like (Addition +, Subtraction - , Multiplication * , Division /, Modulus %) addition is used to two or more than two expression, same as subtraction is used to find the difference, etc. But there is difference between division and modulo i.e., modulo always gives the remainder. for example: 7%2 then it gives modulo 1 because remainder is1. Logical Operators:

&&-------------Logical And (a>b&& x==10)

||-------------logical OR (a<m||a<n) !---------------Logical Not (! (x>=y) Not exp.evaluates values of x neither greater than or equal to y) Assignment operator: (x=a+b;) means value of (a+b) is stores in x. Bitwise operator: (a: 100101 ~a: 011010) Shift operator: These are of two types a) Right shift(a>>L) b) Left shift (a<<L)

Write a Program using the above the operators: #include<stdio.h> main() { int num1 ,num2; printf(enter two integers); scanf(%d%d,&num1&num2); if (num1 ==num2) printf(%d is equalto %d,num1,num2); if (!num1 ==num2) printf (%d is not equals to %d,num1,num2); if(num1>num2) printf(%d is greater than %d,num1,num2); if (num1<num2) printf(%d is less than %d,num1,num2); if (num1<=num2) printf(%d is less than equal to %d,num1,num2); if (num1>=num2) printf(%d is greater than equal to %d,num1,num2); Return 0; } Different loops

1. for loop(int i=4;i<,=4;i++) 2. while loop 3. do while loop a) all loops use same logical(true /false) b) stop

While loop: while(something is true) { (body of program) } If the loop condition is not true then at the beginning loop never executed

do while loop: do while loop is always executed once.do while loop statement allows you to execute code block in loop body at least one. syntax: do { // statements } while (expression); do{ // loop body } While loop(loop condition) Void main { do{ printf(hello world); } while (4<1); } for example using do while loop statement 1. #include <stdio.h> 2. void main(){ 3. int x = 5; 4. int i = 0; 5. // using do while loop statement 6. do{ 7. i++; 8. printf("%d\n",i); 9. }while(i < x); 10. 11. } The program output 1 2 3 4 5 For loop: The for loop is used to implement any type of loop condition. It is based on numeric variables. There are three parts which is separated by semi-colons in control block of the for loop.initialization_expression is executed before execution of the loop starts. The execution of the loop continues until the loop_condition is false The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.

Example of using for loop statement to print an integer five times #include <stdio.h> void main() { // using for loop statement int max = 5; int i = 0; for(i = 0; i < max;i++){

printf("%d\n",i); } }

And the output is 1 2 3 4 5 For Loop Example Using C For example: Void main() { int p,n,count; float r, si; for (count =3;count <=3;count=count ++ ) { printf (enter the value of p,n,r); scanf(%d%d%f,&p,&n,&r); si =(p*n*r)/100; printf(simple interest =%f,si); } getch(); } nesting for loop: void main() int r ,c,sum; for(r =1;r<=3;r++) { for (c=1;c=2;c++) { sum =r+c; printf(r=%d,c=%d,sum=%d\n,r,c,sum); } } }

Continue Statement Continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions.

Void main () { int r ,c; for(r=1;r<=10;r++) { if (r==5) Continue; else printf(r=%d,\n,r); } getch(); } Break statement:

Break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately.

Void main() { int a; for (a=1;a<=10;a++) { if (j==5) Break; else printf(%d\n,a); } Printf(hello) // control pass here getch(); }

Switch statement The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. Switch statement is used to switch the multiple switch(expression){ case value1: /* execute unit of code 1 */ break; case value2: /* execute unit of code 2 */

break; ... default: /* execute default action */ break; } Syntax: switch (integer expression) case 1: do this; case2: do this; //default :do this; } Write a program for calculator using do while loop #include<stdio.h> // these are header files #include<conio.h> // these are header files void main() // main function compiler read from main { int a,b,C,R; // take a variables int type char rep='y'; do{ printf("\nCalculator\n"); // printf is a function ,using for display a message printf("1.addition\n"); printf("2.sutraction\n"); printf("3.multiplication\n"); printf("4.division\n"); printf("enter the value of a"); scanf("%d",&a); printf("enter the value of b"); scanf("%d",&b); printf("enter your choice"); scanf("%d",&C); switch(C){ case 1:R=a+b; printf("\nresult is%d",R); break; case 2:R=a-b; printf("\nresult is%d",R); break; case 3:R=a*b; printf("\nresult is%d",R); break; case 4:R=a/b; printf("\nresult is%d",R); break; // if valid then then break default: printf("\ncondition is invalid"); } printf("\ndo you want to continue(y/n):"); scanf("%c",&rep); }while(rep!='n'); //printf("do you want to continue"); getch(); } // scanf("%c",&rep);

Arrays Array by definition is a variable that hold multiple elements which has the same data type. Array is variables that hold multiple elements which has same data type. An array is a multi element box, uses an indexing system.

Declaring the array: We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Name; Type of array Number of element "data type array name[size];" There are some rules for array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer. We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1]. Initializing the array: It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. int list[5]={2,3,4,5,6} OR int list[5] = {2,1,3,7,8}; Character arrays: char string1[]=first;, "Here ,we using char string and its array size is six." char string[]={f,g,t,y,u,I,\0}; // \0 null character terminating the string. Passing the array To pass an array argument in a function specifies the name of array to pass without any bracket. int myarray[24]; myfunction(my array,24). array usually pass to the function array using call by reference function knows where the array stored passing array element: using call by value pass subscripted name (ex: myarray[5]) to function. Function prototype: void modify array (int b[],int array size); Parameter name may be optional. int b[] may be int[] int array size may be int Multidimensional Array:

An array with more than one index value is called a multidimensional array. All the array above is called single-dimensional array. To declare a multidimensional array you can do follow syntax data_type array_name[][][]; The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows: 1. int matrix[3][3]; Initializing Multidimensional Arrays You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array: 1. 2. 3. 4. 5. 6. int matrix[3][3] = { {11,12,13}, {21,22,23}, {32,31,33}, };

Two dimensional arrays Multidimensional array have two or more than indexes values which specify the element in the array. i.e., multi[i][j]. Where [i] specify row and [j] specify column Declaration and calculation: int a[10][10]; int b[2][2]; // int b [2][2]={{0,1},{2,3}} Sum = a[10][10]+b[2][2] Array and Pointer

Each array element occupies consecutive memory locations and array name is a pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array. This program helps you visualize the memory address each array elements and how to access array element using pointer.

#include <stdio.h> void main() { const int size = 5; int list[size] = {2,1,3,7,8}; int* plist = list; // print memory address of array elements for(int i = 0; i < size;i++) { printf("list[%d] is in %d\n",i,&list[i]); } // accessing array elements using pointer

for(i = 0; i < size;i++) { printf("list[%d] = %d\n",i,*plist); /* increase memory address of pointer so it go to the next element of the array */ plist++; .}} list[0] is in 1310568 list[1] is in 1310572 list[2] is in 1310576 list[3] is in 1310580 list[4] is in 1310584 list[0] = 2 list[1] = 1 list[2] = 3 list[3] = 7 list[4] = 8 You can store pointers in an array and in this case we have an array of pointers. " int *ap[10];" What is function? A fuction is a self contained block of statement that perform a coherent taskof some kind. main() { message(); printf(hi) } message() { printf(smile ) } Write Any C program using at least one function If a program contain only one function , it must be main() If a program contain more than one function then these can be contain in main(). There is no limit on number that might be present in a C program Each function in a program is called sequence specified by the function calls in main(). A function can be called from other function but can not be defined in the other function. There are two types of function : a) library function(printf() ,scanf()). b) User defined (my() ). Passing the values between the function : main() { int a ,b,c,sum; printf(enter the values );

scanlf(%d%d%d,%a,%b,%c); sum=calsum(a,b,c); // actual argu./calling function printf(\nsum=%d,sum); } Callsum(x,y,z) // called function int x,y,z; { Int d; D=x+y+z; return(d); } // a function can be return only one value at a time WHAT IS A REGISTER VARIABLE? A computer can keep data in a register or in memory. A register is much faster in operation than memory but there are very few registers available for the programmer to use. variables are to be stored in a register in order to speed up the execution of the program. compiler probably allows you to use one or more register variables and will ignore additional requests if you request more than are available. WHAT IS PROTOTYPING? A prototype is a model of a real thing and when programming in ANSI-C,ability to define a model of each function for the compiler. The compiler can then use the model to check each of your calls to the function and determine if you have used the correct number of arguments in the function call and if they are of the correct type. By using prototypes, the compiler do some additional error checking. The ANSI standard for C contains prototyping as part of its recommended standard. Every ANSI-C compiler will have prototyping available. What is pre-processor? is executed just prior to the execution of the compiler. It's operation is transparent to you but it does a very important job. It removes all comments from the source and performs a lot of textual substitution based on your code, passing the result to the compiler for the actual compilation of your code. How to use the function Before using a function we should declare the function so the compiler has information of function to check and use it correctly. The function implementation has to match the function declaration for all part return data type, function name and parameter list. When you pass the parameter to function, they have to match data type, the order of parameter. Here is an example of using function. #include<stdio.h> /* functions declaration */ void swap(int *x, int *y); void main() { int x = 10; int y = 20;

printf("x,y before swapping\n"); printf("x = %d\n",x); printf("y = %d\n",y); // using function swap swap(&x,&y); printf("x,y after swapping\n"); printf("x = %d\n",x); printf("y = %d\n",y); } /* functions implementation */ void swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp; }

Here is the output x,y before swapping x = 10 y = 20 x,y after swapping x = 20 y = 10 Benefits of using function C programming language supports function to provide modularity to the software. One of major advantage of function is it can be executed as many time as necessary from different points in your program so it helps you avoid duplication of work. By using function, you can divide complex tasks into smaller manageable tasks and test them independently before using them together. In software development, function allows sharing responsibility between team members in software development team. The whole team can define a set of standard function interface and implement it effectively. Pointer in C C pointer is a memory address. for example: int x = 10; You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator & before it. printf("memory address of x is %d\n",&x); and in my PC the output is memory address of x is 1310588 To access memory address of variable x you have to use pointer. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows: int *px;

Now pointer px to points to memory address of variable x, you can use address-of operator (&) int *px = &x; you can change the content of variable x for example you can increase, decrease x value : *px += 10; printf("value of x is %d\n",x); *px -= 5; printf("value of x is %d\n",x);

the output indicates that x variable has been change via pointer px. value of x is 20 value of x is 15

It is noted that the operator (*) is used to dereference and return content of memory address. In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address. In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows: int c = 10; int c2 = 20; . /* define a pointer and points to an constant integer. pc can point to another integer but you cannot change the content of it */ const int *pc = &c; /* pc++; */ /* cause error */ printf("value of pc is %d\n",pc); pc = &c2; printf("value of pc is %d\n",pc); /* define a constant pointer and points to an integer. py only can point to y and its memory address cannot be changed you can change its content */ int y = 10; int y2 = 20; int const *py = &y; *py++;/* it is ok */ printf("value of y is %d\n",y); /* py = &y2; */ /* cause error */

Output value of pc is 1310580 value of pc is 1310576 value of y is 10 Introduction of C structure In some programming contexts, you need to access multiple data types under asingle name for easy manipulation; for example you want to refer to address with multiple data

like house number, street, zip code, country C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member. Defining structure To define a structure, you can use struct keyword.struct struct_name{ structure_member }; The name of structure is followed the rule of variable name. For example 1. struct address{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. }; It contains house number as an positive integer, street name as a string, zip code as an integer and country as a string. Declaring structure The above example only defines an address structure without create any instance of it. To create or declare a structure you have two ways: The first way is declare a structure follows by structure definition like this : 1. struct struct_name { 2. structure_member; 3. ... 4. } instance_1,instance_2 instance_n; In the second way you can declare your structure instance at a different location in your source code after structure definition. Here is structure declaration syntax : struct struct_name instance_1,instance_2 instance_n; Complex structure Structure can contains arrays or other structures so it is sometimes called complex structure. For example address structure is a complex structure. We can define a complex structure which contains address structure as follows: 1. struct customer{ 2. char name[50]; 3. structure address billing_addr; 4. structure address shipping_addr; 5. }; Accessing structure member To access structure members we can use dot operator (.) between structure name and structure member name as follows: structure_name.structure_member For example to access street name of structure address we do as follows: 1. struct address billing_addr; 2. billing_addr.country = "US"; If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure. 1. struct customer jack; 2. jack.billing_addr.country = "US";

Initializing structure C programming langauge treats a structure as a custom data type therefore you can initialize a structure like a variable. struct product{ char name[50]; double price; } book = { "C programming language",40.5}; In above example, we define product structure, then we declare and initialize book structure with its name and price. Structure and pointer A structure can contain pointers as structure members and we can create a pointer to a structure as follows: struct invoice{ char* code; char date[20]; }; struct address billing_addr; struct address *pa = &billing_addr; Shorthand structure with typedef keyword To make your source code more concise, you can use typedef keyword to create a synonym for a structure. This is an example of using typedef keyword to define address structure so when you want to create an instance of it you can omit the keyword struct 1. typedef struct{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. } address; 7. 8. address billing_addr; 9. address shipping_addr;

Copy a structure into another structure One of major advantage of structure is you can copy it with = operator. The syntax as follows 1. struct_intance1 = struct_intance2 be noted that some old C compilers may not supports structure assignment so you have to assign each member variables one by one. Structure and sizeof function sizeof is used to get the size of any data types even with any structures. For example #include <stdio.h>

typedef struct __address{

int house_number;// 4 bytes

char street[50]; // 50 bytes int zip_code; // 4 bytes char country[20];// 20 bytes } address;//78 bytes in total void main()

// it returns 80 bytes

printf("size of address is %d bytes\n",sizeof(address));

Example Of Structure You will never get the size of a structure exactly as you think it must be. The sizeof function returns the size of structure larger than it is because the compiler pads struct members so that each one can be accessed faster without delays. So you should be careful when you read the whole structure from file which were written from other programs. example of using C structure

#include <stdio.h> typedef struct _student{ char name[50]; unsigned int mark; } student; void print_list(student list[], int size); void read_list(student list[], int size); void main(){ const int size = 3; student list[size]; read_list(list,size); print_list(list,size); } void read_list(student list[], int size) { printf("Please enter the student information:\n"); for(int i = 0; i < size;i++){ printf("\nname:"); scanf("%S",&list[i].name); printf("\nmark:"); scanf("%U",&list[i].mark); } } void print_list(student list[], int size){ printf("Students' information:\n"); for(int i = 0; i < size;i++){ printf("\nname: %s, mark: %u",list[i].name,list[i].mark); } }

Here is program's output Please enter the student information: name:Jack mark:5 name:Anna mark:7 name:Harry

mark:8 Students' information: name: J, mark: 5 name: A, mark: 7 name: H, mark: 8

C does not have a string type as other modern programming languages. C only has .character type so a C string is defined as an array of characters or a pointer to characters Null-terminated String String is terminated by a special character which is called as null terminator or null parameter (/0). So when you define a string you should be sure to have sufficient space for the null terminator. In ASCII table, the null terminator has value 0. Declaring String As in string definition, we have two ways to declare a string. The first way is, we declare an array of characters as follows: 1. char s[] = "string"; And in the second way, we declare a string as a pointer point to characters: 1. char* s = "string";

Declaring a string in two ways looks similar but they are actually different. In the first way, you declare a string as an array of character, the size of string is 7 bytes including a null terminator. But in the second way, the compiler will allocate memory space for the string and the base address of the string is assigned to the pointer variables. Looping Through a String loop through a string by using a subscript. // loop through a string using a subscript char s[] = "C string"; int i; for(i = 0; i < sizeof(s);i++) { printf("%c",s[i]); You can also use a pointer to loop through a string. You use a char pointer and point it to the first location of the string, then you iterate it until the null terminator reached. // loop through a string using a pointer char* ps = s; while(*ps != '\0'){ printf("%c",*ps); ps++; } Passing a String to Function A formal way to pass a string to a function is passing it as a normal array. Dynamic Memory Allocation

Introduce to dynamic memory allocation In some programming contexts, you want to process data but don't know what size of it is. For example, you read a list of students from file but don't know how many students record there. specify the enough maximum size for the the array but it is not efficient in memory management. C provides you a powerful and flexible way to manage memory allocation at runtime. It is called dynamic memory allocation. Dynamic means you can specify the size of data at runtime. C programming language provides a set of standard functions prototype to allow you to handle memory effectively. With dynamic memory allocation you can allocate and free memory as needed. Getting to know the size of data Before allocating memory, we need to know the way to identify the size of each data so we can allocate memory correctly. We can get the size of data by using sizeof() function. sizeof() function returns a size_t an unsigned constant integer. For example: sizeof(int); It returns 4 bytes in typical 32 bit machines. #include <stdio.h> typedef struct __address{ int house_number; char street[50]; int zip_code; char country[20]; } address; void main() { printf("size of int is %d byte(s)\n",sizeof(int)); printf("size of unsigned int is %d byte(s)\n",sizeof(unsigned int)); printf("size of short is %d byte(s)\n",sizeof(short)); printf("size of unsigned short is %d byte(s)\n",sizeof(unsigned short)); printf("size of long is %d byte(s)\n",sizeof(long)); printf("size of char is %d byte(s)\n",sizeof(char)); printf("size of float is %d byte(s)\n",sizeof(float)); printf("size of double is %d byte(s)\n",sizeof(double)); printf("size of address is %d byte(s)\n",sizeof(address)); } Output: size of int is 4 byte(s) size of unsigned int is 4 byte(s) size of short is 2 byte(s) size of unsigned short is 2 byte(s) size of long is 4 byte(s) size of char is 1 byte(s) size of float is 4 byte(s) size of double is 8 byte(s) size of address is 80 byte(s) Allocating memory

We use malloc() function to allocate memory. void * malloc(size_t size); malloc function takes size_t as its argument and returns a void pointer. The void pointer is used because it can allocate memory for any type. The malloc function will return NULL if

requested memory couldnt be allocated or size argument is equal 0. Here is an example of using malloc function to allocate memory: int* pi; int size = 5; pi = (int*)malloc(size * sizeof(int)); sizeof(int) return size of integer (4 bytes) and multiply with size which equals 5 so pi pointer now points to the first byte of 5 * 4 = 20 bytes memory block. We can check whether the malloc function allocate memory space is successful or not by checking the return value. if(pi == NULL) { fprintf(stderr,"error occurred: out of memory"); exit(EXIT_FAILURE); } Beside malloc function, C also provides two other functions which make convenient ways to allocate memory: void *calloc(size_t num, size_t size); void *realloc(void *ptr, size_t size); calloc function not only allocates memory like malloc but also allocates memory for a group of objects which is specified by num argument. realloc function takes in the pointer to the original area of memory to extend and how much the total size of memory should be. Freeing memory When you use malloc to allocate memory you implicitly get the memory from a dynamic memory pool which is called heap. The heap is limited so you have to deallocate or free the memory you requested when you dont use it in any more. C provides free function to free memory. Here is the function prototype: void free(void *ptr); You should always use malloc and free as a pair in your program to a void memory leak.

C Introduction (4 topics)

1. C Programming introduction 2.

C constant

3. Statement in C

4.

What is printf
C Programming introduction

C is a programming language developed by AT & Ts Bell Laboratories of USA in 1972. C was originally designed for and implemented on the UNIX operating system on the DEC PDP-11, by Dennis Ritchie. It is a basically an outgrowth of two earlier language called BCPL and B .in c there are 32 keywords and 40 operators. C is a general-purpose programming language with features economy of expression, modern flow control and data structures, and a rich set of operators. C is not a ``very high level'' language, nor a ``big'' one, and is not specialized to any particular area of application.

Why use c programming? C language is very prevalent in creating different applications and writing of several different software source-codes. The essential feature comprising C language includes the simple and straight-forward use of compiler with a low-level access to memory. c programming is structure programming language we can add no. of module (function) according to our need.. Here are some examples of structured and non structured languages: Non structured FORTRAN COBOL Structured Pascal C++ C Java Modula-2

Advantages and disadvantages of C language Advantages: C is a general-purpose programming language with features economy of expression, modern flow control and data structures, and a rich set of operators. c programming is structure programming language we can add no. of module (function) according to our need. Disadvantages: There is no runtime checking. There is no strict type checking (for ex: we can pass an integer value for the floating data type). As the program extends it is very difficult to fix the bugs.

Why c is called middle level language?

C is called middle level language because it is actually binding the gap between a machine level language and more conventional high level languages. user can use c language to do

system programming (for writing operating system) as well as application programming (for generate menu driven customer billing system ). So that is called middle level language .

High level - Ada , Modula-2 , Pascal, COBOL, FORTRAN, BASIC Middle level - Java , C++ , C, FORTH, Macro-assemble Low level - Assembler General Structure of c programs 1. Document section 2. Pre-processor section 3. Global section 4. Main() Section { } 5. User-Deined section 1.Document section- This section is related with user comment section .user can add comment two ways (a) Single line comment- for single line comment user can add // two forward slash before for single line. User can add number of // single line comment in program.

EXAMLPE- // this is single line comment (b) Multiline comment- for multiline comment user can add /* */ User can add number of multiline comment.

EXAMPLE- /* this is multiline comment this is multiline comment this is multiline comment this is multiline comment this is multiline comment this is multiline comment*/

2-Pre-processer Directive section- Normally every c program started with some Header files .that is called pre-processor section. Pre-processor section is a section where number of header files are included .basically its helpful to link some files with c program. With help of different header files we can access different function easily. Example- for access sqrt(), printf(), scanf(), getch(), functions different header files like #include<stdio.h>, #include<conio.h> , #include<math.h>included in c program. 3.Global Declaration Section- Global section is helpful to declare some variable which we can access in all over program. Basically before main function we can declare different global variable. We can access those variable in all over program.

4.Main Function section- In c language there must be a main() function.this section contain two parts (a) Declaration part- for declare variables (b) Execution part- all statements between{} these braces are execute by c compiler. 5.User defined section- Users can add number of different function with different data type ..he can add called same function number of times in main() function also. Example of general structure of c program

// this is comment section. #include<stdio.h> //these are header files #include<conio.h> int a; // this is global section void main() // this is main section { Printf(this is main section) ; } int function() // this is user defined section { Printf(this is user defined section); }

Is C case sensitive language? Yes in capital letter and lower letter have different meaning in c language .so c language is a case sensitive language. How to Execute a program in c : Creating a executable form of our c program have a three steps: 1. Creating our program 2. Compiling our program 3. Linking our program Creating our program: first we create our program in c language. that have a Document section, Pre processor section, global declaration section, main section, user defined section. With these section we create c program. Compiling our program: after creating our program we do the compile that program. After compiling program that convert the program in .obj extension. After finish these two steps we do linking of the program, linking time that include a some library files. After linking the program that create a .exe file of that program and that exe file always be execute. These three steps showing in the diagram

C constants: Constants also called a literals. Constant refer to fixed values that the program may not

alter. constant can be any of the basic data types. In c have a two type of constant : 1. Numeric constant 2. Character constant C constant is showing in the figure:

Example of the backslash constant: #include<stdio.h> #include<conio.h> Void main() { int a=12; printf(\n %d\ \ \?,a); getch(); } Output of the program: 12 ? Data type in C A data type in a programming language is a set of data with values having predefined characteristics. In c we write any program that have a variables . that variables have a some values. But that value will be which type we dont know , so that always we define by the data type. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. Types of data type: data type types is following given bellow

Primary defined data type type integer enumerated float typeded Double Long float

pointer data type

structure datatype

user data

array string structure union

int - data type int is used to define integer numbers. Exp- { int Count; Count = 5; } float - data type float is used to define floating point numbers. Exp - { float Miles; Miles = 5.6; } double - data type double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes. Exp- { double Atoms; Atoms = 2500000; } char - data type char defines characters. Exp- { char Letter; Letter = 'x'; } Modifiers: The three data types above have the following modifiers. short long signed unsigned The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules: short int <= int <= long int float <= double <= long double What this means is that a 'short int' should assign less than or the same amount of storage

as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is: Type Bytes Bits Range short int 2 16 -32,768 -> +32,767 (16kb) unsigned short int 2 16 0 -> +65,535 (32Kb) unsigned int 4 16 0 -> +4,294,967,295 ( 4Gb) int 4 32 -2,147,483,648 -> +2,147,483,647 ( 2Gb) long int 4 32 -2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char 1 8 -128 -> +127 unsigned char 1 8 0 -> +255 float 4 32 double 8 64 long double 12 96 Variables: A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer. Types of variables: in c variable are divided in two types 1. Global variable- global variable is a variable defined outside any function block. Global variable is also called external variable. 2. Local variable- local variable is a variable defined inside a function block. Local variable is also called automatic variables. Variable Declaration Examples: Single declarations int age; float amount; char last; Multiple declarations You can repeat the the declaration line with a different variable on each line e.g. int age; int hrNumber; but the normal way is to separate the variables by a comma. Although not required the names are easier to read if a space follows the comma. int age, HouseNumber, quality; float distance, Discount; char first, second; Scope of variablesThe scope of a variable depends on where it is declared.

The area of the program where that variable is valid, i.e. the parts of the program that have access to that variable. This is determined by the location of the declaration. The life span of that variable, i.e. the length of time that the variable remains in memory. Where do you Declare VariablesVariables can be declared as Prior to the start of the main( ) function. Within the main function, after the opening { Within a function after the opening { Within a block of code, after the { Global or external variable Declared before the start of the main( ) function.

Static When static is used with a global variable it indicates that the variable is local to the current file. If the programmer would like the value of the variable to be remembered when the function is revisited then that variable must be declared as static. Exp- static int aVariable = 1; In the example the initialisation to 1 occurs only on the first execution of this line of code, it is disregarded on further executions of the line. static has a different meaning when used with global variables. OperatorsAn operator is a symbol which helps the user give the command to computer, and 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: 1. 2. 3. 4. 5. 6. 7. 8. Arithmetic operator Relational Operators Logical Operators Assignment Operators Increments and Decrement Operators Conditional Operators Bitwise Operators Special Operators

Arithmetic Operators: Arithmetic operators means do the all arithmetic operations like as addition, subtraction, multiplication , division, modules etc. 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. Arithmetic Operators: Operator Meaning + Addition or Unary Plus Subtraction or Unary Minus * Multiplication / Division

Example:

Modulus Operator

#include<stdio.h> //include header file stdio.h void main() //tell the compiler the start of the program { int numb1, num2, sum, sub, mul, div, mod; //declaration of variables scanf (%d %d, &num1, &num2); //inputs the operands sum = num1+num2; //addition of numbers and storing in sum. printf(\n Thu sum is = %d, sum); //display the output sub = num1-num2; //subtraction of numbers and storing in sub. printf(\n Thu difference is = %d, sub); //display the output mul = num1*num2; //multiplication of numbers and storing in mul. printf(\n Thu product is = %d, mul); //display the output div = num1/num2; //division of numbers and storing in div. printf(\n Thu division is = %d, div); //display the output mod = num1%num2; //modulus of numbers and storing in mod. printf(\n Thu modulus is = %d, mod); //display the output } Integer Arithmetic When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 20 and y = 5 be 2 integer numbers. Then the integer operation leads to the following results. x+y=27 xy=15 x*y=100 x%y=0 x/y=4 In integer division the fractional part is truncated.

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

xy=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. If any one operand is of real type then the result will always be real thus 15/10.0 = 1.5 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 come 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 is equal to is not equal to

to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational operators. 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. 6.5 <= 25 TRUE -65 > 0 FALSE 10 < 7 + 5 TRUE Relational expressions are used in decision making statements of C language such as if, while and for statements to decide the course of action of a running program.

Logical Operators C has the following logical operators, they compare or evaluate logical and relational expressions.

Operator && || ! Logical AND (&&) :

Meanings Logical AND Logical OR Logical NOT

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. 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 10. Logical OR (||) : The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true. Example : a<m || a<n The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n. Logical NOT (!) : The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression. For example : ! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y 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 Example : x + = 1 is same as x = x + 1 The commonly used shorthand assignment operators are as follows Shorthand assignment operators Statement with simple assignment operator a=a+1 a=a1 Statement with shorthand operator a += 1 a -= 1

a = a * (n+1) a = a / (n+1) a=a%b Example for using shorthand assignment operator

a *= (n+1) a /= (n+1) a %= b

#define N 100 #define A 2 main() { int a; a = A; while (a < N) { printf(%d \n,a a *= a; } } Output : 2 4 16

//creates a variable N with constant value 100 //creates a variable A with constant value 2 //start of the program //variable a declaration //assigns value 2 to a //while value of a is less than N //evaluate or do the following //print the current value of a //shorthand form of a = a * a //end of the loop //end of the program

Statement in c: Statement is a part of our program that can be executed. In other words every statement in our program alone or in combination specifies an action to performed by our program. C provides variety of statements. One of the reason for popularity of C is because of the extreme power provided to programmer in C due to it rich and diverse set of statements define in C. Types Of Statements Statements in C are categorized into following types1.Conditional Statement: its also called a selection statement. this statement depends on the condition. that decide the flow of statements based on evaluation of the results of condition. if - else and switch statements always come in conditional statements. if-else : if - else is a conditional statements. that always depend on condition. if statement have a some condition (true or false), that is given by the program .if the if condition will not be true than it will read the else statement and execute the else statement and go to the next line of the program for execution. if the if statement is true than it execute the if statement and it will not read the else statement and go to next line of the program for execution. General form of if-else statementif (condition) statement;

else statement; OR if ( condition ) { expresion1; } else { expresion2; } Example- #include<stdio.h> int main(){ int a,b; printf("Enter value for a :"); scanf("%d",&a); printf("Enter value for b:"); scanf("%d",&b); if ( a > b ){ printf("a is large number - %d\n",a); } else{ printf("b is large number - %d\n",b); } return 0; } General representation of nested if in C: if (condition1) statement1 else if (condition2) statement2 else . . . switch Statement It has a built in multiple - branch structure and work similar to if else ladder generally. The input value to to the switch statement construct is a int or char variable. Note that no float or any other data is allowed. This input variable is compared against a group of integer constant. All the statements in and after the case in which there is a match is executed until a break statement is encountered or end of switch is reached. We are also allowed to give a default case which will be executed if no other statement match is found. representation of switch in C can be switch (input) { case constant1 : statement1; break; case constant2 :

statement2; break; . . . case default : statement n+1; break; #include <stdio.h> int main (void) { char ch; printf ("\nEnter Character x,y or z: "); ch = getchar (); switch (ch) { case 'x' : printf ("You Entered x"); break; case 'y' : printf ("You Entered y"); break; case 'z' : printf ("You Entered z"); break; default : printf ("You Didnot Entered x, y or z"); } return 0; } 2.Iteration Statements - These are used to run a particular block statements repeatedly or in other words form a loop. for, while and do-while statements come under this category. for Statement -for statement is one of the iteration statement Loops generated by for statement is are also called entry controlled or close ended because the condition for iteration of loop is check at the starting of the loop and loop will not execute even once if the condition will not satisfy even once. General form of for statement is for (initialization; condition, increment) statement; 1. Initialization - In this we initialize the loop control value to a starting value. 2. Condition - In this evaluate the condition for the iteration of the loop and loop repeat only when this is true.

3. Increment - In this we determine how the value of loop control value changes with each iteration of the loop. It can be increment, decrement or any mathematical expression. Example of for loop#include <stdio.h> int main (void) { int num; int i; for (i = 0; i<100;i++) printf ("\n%d",i); for (int j = 100; j>0;j--) printf ("\n%d",i); }

while Statement : while is an iteration statement . It is used to create loops. While produce entry controlled loops . loops in which condition check is performed at starting. form of while statement is while (condition){ statement } Example of while: #include <stdio.h> int main (void) { int i = 0; while (i>10) { printf ("\n%d", i); // Loop prints values 0 to 9. i++; } return 0; } do - while Statement : do - while is also iteration statement. It is similar to while but has many different properties. It is an exit controlled loop which means that condition for next loop iteration is checked at bottom of the loop. the do-while loop will run at least once. form of do - while statement is do { statement; } while (condition); Example of do-while : #include <stdio.h>

int main () { int i = 0; do { printf ("\n%d", i); i++; } while (i>10) // Loop prints values 0 to 9. return 0; } 3. Jump Statements : The are used to make the flow of your statements from one point to another. break, continue, goto and return come under this statements. return :- return is a jump statement. Return statement has a special property that it can return a value with it to the calling function if the function is declared non - void. Void functions are the one which are explicitly declared not to return a value and hence a return statement with value when encountered in such a function leads to an error by compiler. Also a function declared non-void should always return a value of the respective type. form of return statement is return expression; Example of return: #include <stdio.h> int function (void) { int b; b = scanf ("%d", &b); return b; // returns the value of b to the calling function. } int main () { printf ("\n%d", function ()); return 0; } 4. goto Statement goto statement is a jump statements .Goto is used for jumping from one point to another point in your function. You can not jump from one function to another. Jump points or way points for goto are marked by label statements. Label statement can be anywhere in the function above or below the goto statement. form of goto statement is -. . goto label1;

. . label1 : . . label2 : . . goto label2; Example of goto: #include <stdio.h> int main (void)// Print value 0 to 9 { a = 1; loop:; // label stament printf ("\n%d",a); a++; if (a < 10) goto loop ; // jump statement retrun 0; } 5. break Statement : break statement is a jump statement.Break statement when encountered within a loop immediately terminates the loop by passing condition check and execution transfer to the first statement after the loop. In case of switch it terminates the flow of control from one case to another. Example of break : #include <stdio.h> int main () { for (int i = 0; i<100; i++) { printf ("\n%d", i); if (i == 10); // This code prints value only upto 10. break; } return 0; } 6. continue Statement: continue is a jump statement. It is analogues to break statement. Unlike break which breaks the loop, continue statement forces the next execution of loop bypassing any code in between. For for statements it causes the conditional check and increment of loop variable, for while and do-while it passes the control to the condition check jumping all the

statements in between. Continue plays an important role in efficiently applying certain algorithms. Example of continue : #include <stdio.h> int main () { for (int i = 0; i<100; i++) { if (i == 10); // This code prints value only upto 9 even though loop executes 100 times. continue ; printf ("\n%d", i); } return 0; } What is printf: The printf statement allows you to send output on screen and see the output of that program. that is following given bellow. Example: #include <stdio.h> int main() { int x, y, n; x = 2; y = 5; n = x + y; printf("%d + %d = %d\n", x, y, n); return 0; } output: 2 5 7 What is scanf : The scanf function allows you to accept input from users via keyboard. which for us is generally the keyboard. The scanf function can do a lot of different things, but it is generally unreliable unless used in the simplest ways. It is unreliable because it does not handle human errors very well. But for simple programs it is good enough and easy-to-use. scanf("%d", &b): the scanf function uses the same placeholders as printf: int uses %d float uses %f char uses %c character strings use %s Example of the scanf:

#include <stdio.h> int main() { int a, b, c; printf("Enter the first value:"); scanf("%d", &a); printf("Enter the second value:"); scanf("%d", &b); c = a + b; printf("%d + %d = %d\n", a, b, c); return 0; } output : a=2 b=3 c=5 Difference between Declaration and Definition: declaration introduces just the name and type of something but allocates no storage, while definition, also allocates the space used by the thing being declared. Example of Declaration and Definition: int func_dec(void); /* * Because this function has a body, it is also a definition. * Any variables declared inside will be definitions, * unless the keyword 'extern' is used. * Don't use 'extern' until you understand it! */ int def_func(void){ float f_var; /* a definition */ int c; /* another definition */ int random_num(void); /* declare (but not define) another function */ return(0); } What is odd loop? loop is the repetition of data according to the given conditions "so odd loop is that loop which only repeat the odd numbers & it leave the even numbes". Example of odd loop: main( ) { char ritu = 'a' ; int num ; for ( ; ritu == 'a' ; ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "nWant to enter another number y/n " ) ; scanf ( " %c", &ritu ) ; }

} Keywords in c: Keywords are the words. The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called Reserved words. There are only 32 keywords available in C. that is given given below, auto double break else case enum char extern const float continue for default goto do if Identifier in c: An identifier is nothing but a data type. It may variable, content, structure or a pointer. C in 10 days (Fundamentals) C Tutorial for Beginners int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

1. Basics about C 2. C Data Types 3. Declaration of Storage Class 4. Getting Started With C 5. Identifiers and Keywords 6. 7. Write a first C program 8. Instructions in 'C' Language 9. Functions 10. Pointer

11. History of C:-

12. C is a programming language developed at AT & Ts Bell Laboratories of USA in


1972. It was designed and written by a man named Dennis Ritchie. In that time some languages were there like Algol-60 and Pascal. C language is member of Algol60 based languages. CPL (Combined Programming Language) was built but it never implemented after BCPL (Basic CPL) came as implemented language. It was rewritten by Ken Thompson in 1970 named B specially for UNIX Operating System. Dennis M. Ritche added some new features and introduced a new language called C language. The major advance of C over the languages B and BCPL was its typing structure. C language adopted some features from Algol-68 also. The Future of C Language:13. Although the C may be a base for successful object oriented extensions like C++ and Java, C still running to remain and be used with same qualities as ever. C is still a preferable language to write short efficient low-level code that interacts with the hardware and OS. The old C programmers sometimes used assembly language for doing jobs that is not possible to do in C. In future, the programmers in other programming languages may do the same. They will write the code in their favorite language and for low-level routines and efficiency they will code in C using it as an assembly language. 14. Advantages of C language:- It's a systems language (which means it can be used to do low-level programming with minimal or no run-time). - It is essentially high level assembly (it was designed to write portable OS's in, ) - A lot of libraries are written in C and it's easy to find reference code, and to get support. - C code is readable by people who understand most other curly-bracket languages (C++, D, Java, C#). - It lacks advance features (somewhat a disadvantage), but combined with the above point it's a good language to demonstrate code in. C lacks features like classes, templates, and exceptions. Overall, it's declining as an applications language, but still holding strong as a systems language. Disadvantages of C Language:1. There is no runtime checking. 2.There is no strict type checking( for ex: we can pass an integer value for the floating data type). 3. As the program extends it is very difficult to fix the bugs What is the age of C ? Since the time, it was developed almost 30 years ago; C has been in use, without its importance being marginalized. Over a period of time a huge amount of source code has been developed and been made available, and therefore, there is a lot of C to be leant and to be used. Why C is Well-researched and studied ?

One of the best things about C is the amount of study, in-depth analysis, and research that has gone into it. This has meant that almost all issues concerned with C have been clearly understood and elucidated. There are a whole lot of tutorials that will help you learn the language, as well as solve, any kind of problems that might arise. You also get the help of a huge amount of expertise, insights, and opinions on the language that has been a result of years of development, study, and use.

Is C great for putting ideas into practice ? C is inherently easy to understand. Moreover, if you want to express some common ideas in programming, and in a way in which people are comfortable with, then using C is the best way you can accomplish this. You could call it the lingua franca, when it comes to programming. It can be adapted to suit the requirements of any development, and its current use and the languages used to program the UNIX system, illustrates this fact with aplomb.

C is Closer to the Machine When you are working with C, you are working with various aspects like individual bits, pointers, and bytes. This will allow you to understand the various optimization techniques for the computer system. It's always good to know, what is happening with regards to the components of the system that you are using. While working with higher level languages this is extremely useful, if something does not work or is slower than you thought it would be. Data types:Primary data type, Integer Type, Floating Point Types, Void type, Character Type, Size and Range of Data Types on 16 bit machine, derived data type, Declaration of Variables, User defined type declaration, Declaration of Storage Class, auto, static, extern, and register, Defining Symbolic Constants, Declaring Variable as Constant and Volatile Variable C language data types can be classified as Primary data type Derived data type User-defined data type Primary data type All C Compilers accept the following fundamental data types

1 Integer .

int

2 Character .

char

3 Floating Point float .

4 Double double . precision floating point

5. Void

void

The size and range of each data type is given in the table below

DATA TYPE

RANGE OF VALUES -128 to 127 -32768 to +32767 3.4 e-38 to 3.4 e+38

char Int

float

double 1.7 e-308 to 1.7 e+308

Integer Type : Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values. Floating Point Types : Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which

consumes 80 bits of memory space.

Using void data type, we can specify the type of a function. It is a good practice to avoid functions that does not return any values to the calling function. Character Type : A single character can be defined as a defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from 128 to 127. Size and Range of Data Types on 16 bit machine.

TYPE

SIZE (Bits) Range 8 8 16 16 8 8 32 32 32 64 -128 to 127 0 to 255 -32768 to 32767 0 to 65535 -128 to 127 0 to 255 -2147483648 to 2147483647 0 to 4294967295 3.4 e-38 to 3.4 e+38 1.7e-308 to 1.7e+308

Char or Signed Char Unsigned Char Int or Signed int Unsigned int Short int or Signed short int Unsigned short int Long int or signed long int Unsigned long int Float Double

Long Double

80

3.4 e-4932 to 3.4 e+4932

Non-Primitive Data Type:A non-primitive data type is am abstract data type that is built out of primitive data types linked list, queue, stack, etc. Declaration of Variables Every variable used in the program should be declared to the compiler. The declaration does two things. 1. Tells the compiler the variables name. 2. Specifies what type of data the variable will hold. Example: Int sum; Int number, salary; Double average Datatype Keyword Equivalent

Character Unsigned Character Signed Character Signed Integer Signed Short Integer

char unsigned char signed char signed int (or) int signed short int (or) short int (or) short signed long int (or) long int (or) long unsigned int (or)

Signed Long Integer

UnSigned Integer

unsigned UnSigned Short Integer unsigned short int (or) unsigned short unsigned long int (or) unsigned long float double

UnSigned Long Integer

Floating Point Double Precision Floating Point

Extended Double long double Precision Floating Point

User defined type declaration:In C language a user can define an identifier that represents an existing data type. The user defined datatype identifier can later be used to declare variables. The general syntax is typedef type identifier;> here type represents existing data type and identifier refers to the row name given to the data type. Example: typedef int salary; typedef float average; Here salary symbolizes int and average symbolizes float. They can be later used to declare variables as follows: Units dept1, dept2; Average section1, section2; Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and section2 are indirectly float data type. The second type of user defined datatype is enumerated data type which is defined as follows. Enum identifier {value1, value2 . Value n};

The identifier is a user defined enumerated datatype which can be used to declare variables that have one of the values enclosed within the braces. After the definition we can declare variables to be of this new type as below. enum identifier V1, V2, V3, Vn The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2 .. value n Example: enum day {Monday, Tuesday, . Sunday}; enum day week_st, week end; week_st = Monday; week_end = Friday; if(wk_st == Tuesday) week_en = Saturday; Declaration of Storage Class:Variables in C have not only the data type but also storage class that provides information about their location and visibility. The storage class divides the portion of the program within which the variables are recognized. auto :Auto is the default storage class. It is a local variable known only to the function in which it is declared. static : Local variable which exists and retains its value even after the control is transferred to the calling function. extern : Global variable known to all functions in the file register : Social variables which are stored in the register. Defining Symbolic Constants:A symbolic constant value can be defined as a preprocessor statement and used in the program as any other constant value. The general form of a symbolic constant is # define symbolic_name value of constant Valid examples of constant definitions are : # define marks 100 # define total 50 # define pi 3.14159 These values may appear anywhere in the program, but must come before it is referenced in the program. It is a standard practice to place them at the beginning of the program. Declaring Variable as Constant:-

The values of some variable may be required to remain constant through-out the program. We can do this by using the qualifier const at the time of initialization. Example: Const int class_size = 40; The const data type qualifier tells the compiler that the value of the int variable class _size may not be modified in the program.

Format Specifiers in C:-

%c %d %i %f %e %E %g %G %o %s %u %x %X %p %n %%

The character format specifier. The integer format specifier. The integer format specifier (same as %d). The floating-point format specifier. The scientific notation format specifier. The scientific notation format specifier. Uses %f or %e, whichever result is shorter. Uses %f or %E, whichever result is shorter. The unsigned octal format specifier. The string format specifier. The unsigned integer format specifier. The unsigned hexadecimal format specifier. The unsigned hexadecimal format specifier. Displays the corresponding argument that is a pointer. Records the number of characters written so far. Outputs a percent sign.

Getting Started With C:Now we are going to starts with C language ----1. The Character Set Of C:- Character set can be of Alphabets, Digits or special symbols. It can be A,B,C.Z, a,b,cz, 1,29, !,@,#,$ and so on. 2. Constants, Variables and Keywords:- Alphabets, Digits and Special Symbols creates Constants, Variables and keywords. Constants:A constants is an entity that does not change. Whatever we calculated, it stores in memory. Computer memory has millions of cells also known as memory Locations. If the memory location has a value it does not change called constant. Types Of Constants:There are two types of constants 1. Primary Constants:Integer Constant Real Constant Character Constant 2. Secondary Constants:- Array

Pointer Structure Union Enum Variables:The Name which are given to the memory locations called Variables. These memory location contains constants (Integer, Real and Character). Types of variables depend on types of variables that it can handle. Particular type of variable can hold only the same type of constants. For Examples:- A integer type of variable can hold integer constant. Rules for constructing a variable name:1. The first character in the variable name must be an alphabet or underscore. 2. There should be no commas or blank spaces within variable name. 3. There should not be any special symbol within a variable name except a underscore. 4. Variable name should be 31 characters long. 5. variable name should be meaningful so that user can understand. Variable type The Programming language C has two main variable types 1. Local Variables 2.Global Variables Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initialized by the system, you must initialize it yourself. When execution of the block starts the variable is available, and when the block ends the variable 'dies'. Global Variables Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initialized automatically by the system when you define them!

Data Type int char float pointer

Initialser 0 '\0' 0 NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name. Identifiers:-

Identifiers are names which are given to elements of a program such as variables , arrays & functions. Basically identifiers are the group of alphabets or digits. Rules for making identifier name 1. the first character of an identifiers must be analphabet or an underscore 2. all characters must be letters or digits. 3.There is no special characters are allowed except the underscore"_". 4. There is no two underscores are allowed. 5. don't use keywords as identifiers. C Keywords:1. Keywords are the words whose meanings are already exist in the compiler. 2. Keywords can not be use as variable names. 3. Keywords are also called Reserved words. 4. There are only 32 keywords available in C. auto, double, int, struct, break, else, long, switch, case, enum, register, typedef, char, extern, return, union, const, float, short, unsigned, continue, for, signed, void, default, goto, sizeof, volatile, do, if, static, while Definitions v/s Declaration in C A declaration is when you declare a new variable of some specific type. A definition is when you define a new name for some particular value or type. /* * A function is only defined if its body is given * so this is a declaration but not a definition int func_dec(void); /* * Because this function has a body, it is also * a definition. * Any variables declared inside will be definitions, * unless the keyword 'extern' is used. * Don't use 'extern' until you understand it! */ int def_func(void){ float f_var; /* a definition */ int counter; /* another definition */ int rand_num(void); /* declare (but not define) another function */ return(0); } How to write a first C program:Rules:1. In C program each instruction written as a separate statement.

2. The statement of a program must be in the sequence by which we want to execute. 3. Blank space are not allowed in the variable name but you can use blank spaces between two words which increase readability. 4. Statements should be in small case letters. 5. Every statement ends with a semicolon (;). 6. Semicolon is called statement terminator. 7. You can put the comment within a program by using /* .*/. 8. Comments are not necessary to use in a program but it is a good habit to use comments in a program.

Compilation and Execution of a C Program:1. Write a program using editor. 2. Save the file with .c extension. 3. To compile the program you can select compile from compile menu and press enter or you can press Alt+f9 4. It will check the errors if program has any error it will terminate the program then you can find out he error and you can correct it. After correcting the error you can compile the program again. After compiling successfully it will create a object (.obj) file.

5. Once the source program has been converted into an object file, it is still not in the form that you can run. The reason behind this is that there may be some references to standard library functions or user-defined functions in other object files, which are compiled separately. Therefore these object files are to be linked together along with standard library functions that are contained in library files. To link our object file, select Link from the Compile menu. After this the .OBJ file will be compiled with the one or more library files. The result of this linking process produces an executable file with .EXE extension. Figure-4 depicts this linking process.

6. .exe file is a stand alone executable file. which can direct execute from command prompt 7. 8. After pressing Alt+f9 it will complete the whole process creating .OBJ and .EXE. To display the output of the program press Alt+f5.

Examples of a simple C program:/* Calculation of simple interest */ main( ) { int p, n ; float r, si ; p = 1000 ; n=3; r = 8.5 ; /* formula for simple interest */ si = p * n * r / 100 ; printf ( "%f" , si ) ; } main():1. main() is a function which is entry point of any program. 2. main() is collective name which is given to a set of statements. 3. This name has to be main(). It can not be change. 4. Statements within a main() should be enclosed within a pair of { }. 5. main() { statement 1; statement 2; } 6. Every function used in a program must be declared.

Difference between main() and other functions:1. parameters to main() are passed from command line, 2. main() is the only function declared by the compiler and defined by the user, 3. main() is by convention a unique external function, 4. main() is the only function with implicit return 0; at the end of main(). When control crosses the ending } for main it returns control to the operating system by returning 0 to it (if there is no explicit return statement with a return value). The OS normally treats return 0 as the successful termination of the program. 5. return type for main() is always is an int, (some compilers may accept void main() or any other return type, but they are actually treated as if it is declared as int main(). It makes the code non-portable. Always use int main() ). Example:main() { Int i; Static int j; } NOTES:1. Parameters are passed from command line to main (). 2. It is the only function declares by the compiler and defines by the user. 3. Return type for main() is always is an int, (some compilers may accept void main() or any other return type, but they are actually treated as if it is declared as int main(). It makes the code non-portable. Always use int main() ).

Receiving Input:To receive the input from user we use scanf() function in C Language. scanf() is a function that reads data with specified format and is present in many other programming languages. int scanf(const char *format, ...); "scanf" stands for "scan format", because it scans the input for valid tokens and parses them according to a specified format.

#include <stdio.h> int main(void) { int n; while (scanf("%d", &n) == 1)

printf("%d\n", n); return 0; } Types of Instructions in 'C' Language:There are basically three types of instructions in C: (a). Type Declaration Instruction (b). Arithmetic Instruction (c). Control Instruction The purpose of each of these instructions is given below: (a). Type Declaration Instruction: To declare the type of variables . (b). Arithmetic instruction: To perform arithmetic operations between constants and variables. (c). Control instruction: To control the sequence of execution of various statements.

1. An arithmetic operation between integer and integer is always integer. 2. An operation between real and real is always real. 3. An operation between integer and real is always real.Type Conversion in Assignments the type of the expression and the type of the variable on the left-hand side of the assignment operator will not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of equal(=). For example, consider the following assignment statements. int i ; float b ; i = 6.3 ; b = 60 ; in the example above i is type of integer and b is float type but the value assigned is opposite to each other. i is having 6.3 which is float and after assigning this value, it will contain only 6 rest of .3 is demoted. and variable b is having 60 which is integer type and it assign 60.000000, promoted the value. arithmetic operations are performed in an arithmetic expression is called as Hierarchy of operations. and if a=4,b=7,c=3 then using the same expression we will obtain two different answers as z=5.6 or z=7. To avoid this condition we must be aware of hierarchy of operations. In arithmetic expressions scanning is always done from left to right. The priority of operations is as shown below,

Priority Operators First Second Third Fourth Parentheses or brackets() Multiplication & Division Addition & Subtraction Assignment i.e.=

If we consider the logical operators used in C language, the operator precedence will be like; Operators Type ! */% +== != && || = Logical NOT Arithmetic and modulus Arithmetic Relational Relational Logical AND Logical OR Assignment

In the tables above, the higher the position of an operator, higher is its priority. Control Instructions in C The Control Instructions enable us to specify the order in which instructions in a program are to be executed. or the control instructions determine the flow of control in a program. There are four types of control instructions in C. (a) Sequence Control Instruction The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. (b) Selection or Decision Control Instruction Decision instructions allow the computer to take a decision as to which instruction is to be executed next. (c) Repetition or Loop Control Instruction The Loop control instruction helps computer to execute a group of statements repeatedly. (d) Case Control Instruction same as decision control instruction. Control Statement:-

There are 3 types of control statement:1. If Statement 2. If-else Statement 3. The Conditional Operators If Condition:if (condition is true) execute the statement; The if condition tells the compiler that the condition is true, execute the statement. Condition of if is always within the pair of parentheses. If condition is true the statement will execute and condition is false, the statement will not execute. For checking condition is true or false we use the relational operators. Relational Operators:-

The Expression x==y x!=y x<y x>y

Is True If x is equal to y x is not equal to y x is less than y x is greater than y x is less than or equal to y x is greater than or equal to y

x<=y

x>=y

Example:main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; } Multiple statements within if:-

We can execute more than one statements for that if condition should be satisfied. If-Else Statement:We can use If Else condition when we have more than one conditions. If block checks the condition 1 is true it will execute other else block condition will be executed. Or You can say we can execute group of statements by the If else condition. Example:/* Calculation of gross salary */ main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; } Nested If else:We can use several If else condition within if block or else block. This is called nested if else condition. Example:/* program of nested if-else */ main( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You would go to heaven !" ) ; else { if ( i == 2 ) printf ( "Hell was created with you in mind" ) ; else printf ( "How about mother earth !" ) ; } }

Logical operators:There are only three logical operator in C. 1. && AND 2. || OR 3. ! NOT The first two operator allows two or more conditions to be combined in an if statement. Example:main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; } Loops:Loops are required to perform the same series of actions. We frequently need to perform an action over and over. Ability to perform a set of instructions repeatedly called loops. There are three types of loops:1. for 2. while 3. do while

1. for loop:for (initialization_expression; loop_condition; increment_expression){ // statements There are three parts which is separated by semi-colons in control block of the for loop. initialization_expression is executed before execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part. The execution of the loop continues until the loop_condition is false. This expression is checked at the beginning of each loop iteration.

The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.

Here is an example of using for loop statement to print an integer five times #include <stdio.h> void main(){ // using for loop statement int max = 5; int i = 0; for(i = 0; i < max;i++){ printf("%d\n",i); } } 2. While Loop:A loop statement allows you to execute a statement or block of statements repeatedly. First it check the condition then execute it. If condition is true it execute otherwise dont execute the statement. Here is syntax of while loop statement: while (expression) { // statements } Here is a while loop statement demonstration program: #include <stdio.h> void main(){ int x = 10; int i = 0; // using while loop statement while(i < x){ i++; printf("%d\n",i); } // when number 5 found, escape loop body int numberFound= 5; int j = 1; while(j < x){ if(j == numberFound){ printf("number found\n"); break; } printf("%d...keep finding\n",j); j++; } }

Do While Loop:do while loop statement allows you to execute code block in loop body at least once. Here is do while loop syntax: do { // statements } while (expression); Here is an example of using do while loop statement: #include <stdio.h> void main(){ int x = 5; int i = 0; // using do while loop statement do{ i++; printf("%d\n",i); }while(i < x); } The Odd Loop Odd loop executed the statements within them a finite number of times. it execute the statements finite times in the loop. /* Execution of a loop an unknown number of times */ main( ) { char another ; int num ; do { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; } while ( another == 'y' ) ; } Bitwise operations & &= | |= ^

AND AND OR OR XOR

^= ~ << << >>= >>=

XOR one's compliment Shift Left Shift Left Shift Right Shift Right

AND OR and XOR These require two operands and will perform bit comparisons. AND & will copy a bit to the result if it exists in both operands. main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a & b; /* 12 = 0000 1100 */ } OR | will copy a bit if it exists in either operand. main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; } c = a | b; /* 61 = 0011 1101 */

XOR ^ copies the bit if it is set in one operand (but not both). main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a ^ b; } Ones Complement This operator is unary (requires one operand) and has the effect of 'flipping' bits. main() { /* 49 = 0011 0001 */

unsigned int Value = 4; Value = ~ Value; }

/* 4 = 0000 0100 */

/* 251 = 1111 1011 */

Bit shift. The following operators can be used for shifting bits left or right. <<,>>,<<=,>>= The left operands value is moved left or right by the number of bits specified by the right operand. For example: main() { unsigned int Value=4; unsigned int Shift=2; Value = Value << Shift; Value <<= Shift;

/* 4 = 0000 0100 */ /* 16 = 0001 0000 */ /* 64 = 0100 0000 */

printf("%d\n", Value); /* Prints 64 */ } 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. Logical operators:There are only three logical operator in C. 1. && AND 2. || OR 3. ! NOT The first two operator allows two or more conditions to be combined in an if statement. Example:main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; } Break Statement:break statement is used to break any type of loop such as while, do while and for loop. break statement terminates the loop body immediately. Example:#include <stdio.h> #define SIZE 10 void main(){ // demonstration of using break statement int items[SIZE] = {1,3,2,4,5,6,9,7,10,0}; int number_found = 4,i; for(i = 0; i < SIZE;i++){ if(items[i] == number_found){ printf("number found at position %d\n",i); break;// break the loop } printf("finding at position %d\n",i); } Continue Statement:continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions. Example continues:// demonstration of using continue statement for(i = 0; i < SIZE;i++){ if(items[i] != number_found){ printf("finding at position %d\n",i); continue;// break current iteration } // print number found and break the loop printf("number found at position %d\n",i); break; } } Switch Statement:-

The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. break keyword is used to signal the end of the block. Here are the common switch statement syntax: switch (expression){ case value1: /* execute unit of code 1 */ break; case value2: /* execute unit of code 2 */ break; ... default: /* execute default action */ break; } Here is an example of using C switch statement #include <stdio.h> const int RED = 1; const int GREEN = 2; const int BLUE = 3; void main(){ int color = 1; printf("Enter an integer to choose a color(red=1,green=2,blue=3):\n"); scanf("%d",&color); switch(color){ case RED: printf("you chose red color\n"); break; case GREEN:printf("you chose green color\n"); break; case BLUE:printf("you chose blue color\n"); break; default:printf("you did not choose any color\n"); } } Goto statement:The goto statement is use for a jump from one point to another point within a function. Example:#include <stdio.h> #include <conio.h> int main() { int n = 0; loop: ; printf("\n%d", n); n++; if (n<10) { goto loop; } getch();

return 0; } Functions:A function is a block of code that performs a particular task. It has a name and it is reusable and it can be executed from as many different parts in a C Program as required. It also optionally returns a value to the calling program So function in a C program has some properties discussed below. Every function has a unique name. This name is used to call function from main() function. A function can be called from within another function. A function is independent and it can perform its task without intervention from or interfering with other parts of the program. A function performs a specific task. A task is a distinct job that your program must perform as a part of its overall operation, such as adding two or more integer, sorting an array into numerical order, or calculating a cube root etc. A function returns a value to the calling program. This is optional and depends upon the task your function is going to accomplish. Suppose you want to just show few lines through function then it is not necessary to return a value. But if you are calculating area of rectangle and wanted to use result somewhere in program then you have to send back (return) value to the calling function. C language is collection of various inbuilt functions. If you have written a program in C then it is evident that you have used Cs inbuilt functions. Printf, scanf, clrscr etc. all are Cs inbuilt functions. You cannot imagine a C program without function.

Example:int sum (int x, int y) { int result; result = x + y; return (result); } Types of functions: A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values. 4. Functions that return multiple values. 5. Functions with no arguments and return values. #include<stdio.h> #include<conio.h> void add(int x,int y) { int result; result = x+y; printf("Sum of %d and %d is %d.\n\n",x,y,result); }void main() { clrscr();

add(10,15); add(55,64); add(168,325); getch(); } Call by value and Call by reference:The argument passed to a function can be of two types:1. value passed (call by value) 2. address passed (call by reference) Let's say we have an integer variable named x. A call to a function by value using x means (a copy of) the value that x stores is passed in the function call and no matter what the function does with that value, the value stored in x remains unchanged. A call to a function by reference using x means a reference (also called a pointer or alias) to the variable x is passed in the function call and so any changes the function makes using this reference will actually change the value stored in x. Pointer:In c a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type * variable name Example: int *ptr; float *string; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260. /* A program to illustrate pointer declaration*/ main()

{ int *ptr; int sum; sum=45; ptr= printf (\n Sum is %d\n, sum); printf (\n The sum pointer is %d, ptr); } /* Program to display the contents of the variable their address using pointer variable*/ #include< stdio.h > { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch=a; intptr=&x; cptr=&ch; floptr=&x; printf(Num %d stored at address %u\n,*intptr,intptr); printf(Value %f stored at address %u\n,*floptr,floptr); printf(Character %c stored at address %u\n,*cptr,cptr); } Pointer expressions & pointer arithmetic: Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the /* Program to display the contents of the variable their address using pointer variable*/ include< stdio.h > { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch=a; intptr=&x; cptr=&ch; floptr=&x; printf(Num %d stored at address %u\n,*intptr,intptr); printf(Value %f stored at address %u\n,*floptr,floptr); printf(Character %c stored at address %u\n,*cptr,cptr); } expression and pointer arithmetic*/ #include< stdio.h >

main() { int ptr1,ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 6; y=6*- *ptr1/ *ptr2 +30; printf(\nAddress of a +%u,ptr1); printf(\nAddress of b %u,ptr2); printf(\na=%d, b=%d,a,b); printf(\nx=%d,y=%d,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(\na=%d, b=%d,a,b); } Pointers and function: The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups. 1. Call by reference 2. Call by value. Call by value: We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters. #include< stdio.h > void main() { int x,y; x=20; y=30; printf(\n Value of a and b before function call =%d %d,a,b); fncn(x,y); printf(\n Value of a and b after function call =%d %d,a,b); } fncn(p,q) int p,q; { p=p+p; q=q+q; }

Call by Reference: When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. /* example of call by reference*/ #include< stdio.h > void main() { int x,y; x=20; y=30; printf(\n Value of a and b before function call =%d %d,a,b); fncn(&x,&y); printf(\n Value of a and b after function call =%d %d,a,b); } fncn(p,q) int p,q; { *p=*p+*p; *q=*q+*q; } Pointer to arrays: An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator. /* A program to display the contents of array using pointer*/ main() { int a[100]; int i,j,n; printf("\nEnter the elements of the array\n"); scanf(%d,&n); printf("Enter the array elements"); for(I=0;I< n;I++) scanf(%d,&a[I]); printf("Array element are"); for(ptr=a,ptr< (a+n);ptr++) printf("Value of a[%d]=%d stored at address %u",j+=,*ptr,ptr); } Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions. Pointers and structures:

We know the name of an array stands for the address of its zeroth element the same concept applies for names of arrays of structures. Suppose item is an array variable of struct type. Consider the following declaration: struct products { char name[30]; int manufac; float net; item[2],*ptr;

This statement declares item as array of two elements, each type struct products and ptr as a pointer data objects of type struct products, the assignment ptr=item; would assign the address of zeroth element to product[0]. Its members can be accessed by using the following notation. ptr- >name; ptr- >manufac; ptr- >net; The symbol - > is called arrow pointer and is made up of minus sign and greater than sign. Note that ptr- > is simple another way of writing product[0]. When the pointer is incremented by one it is made to pint to next record ie item[1]. The following statement will print the values of members of all the elements of the product array. for(ptr=item; ptr< item+2;ptr++) printf("%s%d%f\n",ptr- >name,ptr- >manufac,ptr- >net); We could also use the notation (*ptr).number to access the member number. The parenthesis around ptr are necessary because the member operator . Has a higher precedence than the operator *. Pointers on pointer: While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precautions using pointers to prevent errors. We should make sure that we know where each pointer is pointing in a program. Here are some general observations and common errors that might be useful to remember. A pointer contains garbage until it is initialized. Since compilers cannot detect un initialized or wrongly initialized pointers, the errors may not be known until we execute the program remember that even if we are able to locate a wrong result, it may not provide any evidence for us to suspect problems in the pointers. main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */

unsigned int c = 0; c = a & b; }

/* 12 = 0000 1100 */

C Basics Tutorial In Easy Way

1. About C 2. A First Program 3. Program computes a table of the sine function for angles between 0 and 360
degrees.

4. Data Types in C 5. Switch Case ,If Else 6. Loops in C 7. Operators in C 8. Auto ,Static, extern ,register
History C was developed at Bell Lab in 1972 by Dennis Richie ..CPL(Combined Programming Language) was developed with The purpose of High Level language n machine independent language but draw back of CPL is too longer code so that BCPL (Basic CPL ) was developed . In 1970 B language was developed by the Ken Thomson had adopt the feature of BCPL and in 1972 Co-Worker of Ken Thomson Dennis Ritchie developed C . Advantage of C C code are optimized so its small and very efficient. C has which is its application in Firmware programming (hardware). C language ability it is use/work with assembly and communicates directly with controllers, processors and other devices. Disadvantage of C C have no concept of runtime checking. C have no concept of no strict type checking. Example: An integer value can be pass for the floating data type.

float main() { float a; a=3;//here an error but it not detected.. return a; } As the program extends it is very difficult to fix the bugs. Identifier In C, an identifier is the combination of alphabetic character; underline .An identifier is used for any variable, function, data definition etc. In c the first character is an alphabetic character or an underline n remaining being any numeric digit, alphabet or underline. The significant character have only 31 character if its more then 31 then rest character may be ignored by any given compiler. Example: Number-suggest that this variable store numeric value. Most of the complier writer use variables first underscore and second character as capital letter so avoid this format. Declaration Vs Definition If we concerned about function declaration Vs definition in c . In C prototyping of function is called declaration that tells the compiler to essentials of that function such as the its name, return type, and number and type of its parameters. The function name, followed by the body of the function, defines the function .The function body contains set of statements, operators and local variables. Example: int fun(int); //Declare int fun(int){ //Define ... } If we concerned about variable declaration Vs definition in c . In Register and auto variable there is no difference between declaration and definition but in external variable memory allocated once ,to ensure that access to the variable always refers to the same cell. If an external variable if a variable is used in more then one file , then this variable needed to connect such a use with the uniquely defined that external variable cell allocated for it. This process of connecting the references of the same external variable in different files, is called resolving the references.

Keyword C provides 32 keywords which can not use for other purpose. auto break case char const continue default do printf() printf ()function is a standard library function . printf () function is followed by a parenthesized list of argument . printf() is a library function that print output . printf(" This is a c program \n"); "This is a c program \n"is the character string or string constant. double else enum extern float for goto it int long register return short signed sizeof static struct switch typeof union unsigned void volatile while

Format Specifiers: There are many format specifiers defined in C. Take a look at the following list: %i or %d

%c %f %lf %s

int char float double


string

Commonly used escape sequences are: \n \t \v \f \b \r newline tab vertical tab new page backspace carriage return

1. First Program We are staring C Tutorial by this Hello World example. #include < stdio.h> void main() { printf("\nHello World\n");

} Save the code in the file Hello.c or Hello.cpp, then compile it by typing: gcc Hello.c Output: Hello World In this example we including a library header file. Basically C language defines all methods into harder files which we need to include in our program before using these methods. To include any library header file C uses # include<nameofheaderfile.h> A C program contains functions and variables. There are two type of functions user define and function define by C Language. The functions specify the tasks to be performed by the program. Each program has a main() functions. The main function establishes the overall logic of the code. It is normally kept short and calls different functions to perform the necessary subtasks. All C codes must have a main() function. printf() This function is an output function from the I/O (input/output) library (defined in the file stdio.h). In this example we are using this function to display Hello World. \n is use to prints a "new line"character, which brings the cursor onto the next line We a can make above program as following. But result will same.

#include < stdio.h> void main() { printf("\n"); printf("Hello World"); printf("\n"); } Try leaving out the ``\n'' lines and see what happens. The first statement ``#include < stdio.h>'' includes a specification of the C I/O library. All variables in C must be explicitly defined before use: the ``.h'' files are by convention ``header files'' which contain definitions of variables and functions necessary for the functioning of a program, whether it be in a user-written section of code, or as part of the standard C libaries. The directive ``#include'' tells the C compiler to insert the contents of the specified file at that point in the code. The ``< ...>'' notation instructs the compiler to look for the file in certain ``standard'' system directories. The void preceeding ``main'' indicates that main is of ``void'' type--that is, it has no type associated with it, meaning that it cannot return a result on execution. The ``;'' denotes the end of a statement. Blocks of statements are put in braces {...}, as in the definition of functions. All C statements are defined in free format, i.e., with no specified layout or column assignment. Whitespace (tabs or spaces) is never significant, except inside quotes as part of a character string. The following program would produce exactly the same result as our earlier example: #include < stdio.h>

void main() { printf("\nHello World\n"); } The reasons for arranging your programs in lines and indenting to show structure should be obvious. 2. Let's Compute The following program computes a table of the sine function for angles between 0 and 360 degrees.

#include < stdio.h> #include < math.h> void main() { int angle_degree; double angle_radian, pi, value; // Print a message printf ("\nCompute a table of the sine function\n\n"); // obtain pi pi = 4.0*atan(1.0); printf ( " Value of PI = %f \n\n", pi ); printf ( " angle Sine \n" ); angle_degree=0; // initial angle value // scan over angle while ( angle_degree <= 360 ) // loop until angle_degree > 360 { angle_radian = pi * angle_degree/180.0 ; value = sin(angle_radian); printf ( " %3d %f \n ", angle_degree, value ); angle_degree = angle_degree + 10; // increment the loop index } } We will learn basic calculations and we learn how we can use deferent methods of deferent library header files in this example .Basically we are calculating the sine values from 0 to 360. Before exampling this example first you must know types of different variable. C uses the following standard variable types: int -> integer variable

short -> short integer long -> long integer float -> single precision real (floating point) variable double -> double precision real (floating point) variable char -> character variable (single byte) The compilers checks for consistency in the types of all variables used in any code. This feature is intended to prevent mistakes, in particular in mistyping variable names. Calculations done in the math library routines are usually done in double precision arithmetic (64 bits on most workstations). The actual number of bytes used in the internal storage of these data types depends on the machine being used. The printf function can be instructed to print integers, floats and strings properly. The general syntax is printf( "format", variables ); where "format" specifies the conversation specification and variables is a list of quantities to print. Some useful formats are %.nd integer (optional n = number of columns; if 0, pad with zeroes) %m.nf float or double (optional m = number of columns,n = number of decimal places) %ns string (optional n = number of columns) %c character \n \t to introduce new line or tab \g ring the bell (``beep'') on the terminal. Example descriptions: 1.Include header files: #include < stdio.h> #include < math.h> These two header files must be included first. first is included for printf()and main() methods as these methods are defined in this header file. Second <math.h> header file is included for sin function. In <math.h> header file all mathematical methods eg sin(),cose(),sqrt() etc. are define to use them we need to include this header file at top most in our progarm. We are using while loop for printing and calculating value of sin from 0 to 360. Integer Type Integer variable is whole number variable n the range of that variable is machine dependent. A programmer should always take care f the range of that variable n also take care of the storage capacity. Integer can be signed and unsigned. There are three classes of integer in c are Short int, integer, long int. the difference between these classes only of its range.

TYPE Int or Signed int Unsigned int Short int or Signed short int Unsigned short int Long int or signed long int Unsigned long int

SIZE (Bits) 16 16 8 8 32 32

Range -32768 to 32767 0 to 65535 -128 to 127 0 to 255 -2147483648 to 2147483647 0 to 4294967295

Example: int main( ) { int a=10 ; // a contain integer type value. return a; }

Data type Signed Integer Signed Short Integer Signed Long Integer Unsigned Integer Unsigned Short Integer Unsigned Long Integer

Keyword Equivalent signed int (or) int signed short int (or) short int (or) short signed long int (or) long int (or) long unsigned int (or) unsigned unsigned short int (or) unsigned short unsigned long int (or) unsigned long

Float Type Floating point variable represent a real number with 6 digits precision. Float keyword use for floating point number. The accuracy of floating point number is insufficient so use double .double is same as floating point number but range of precision is longer then the float. To extend the precision further we can use long double which consumes 80 bits of memory space. TYPE Float Double SIZE (Bits) Range 32 3.4 e-38 to 3.4 e+38 64 1.7e-308 to 1.7e+308 3.4 e-4932 to 3.4 e+4932

Long Double 80

Data type Floating Point Double Precision Floating Point Extended Double Precision Floating Point

Keyword Equivalent float double long double

Example: float main( ) { float a=10.344 ; // a contain float type value. return a; } char Type The capability of char is holding one character in the local character set. Characters are usually stored in 8 bits of internal storage or can say that one byte. In the char the qualifier

signed or unsigned can be explicit applied. While unsigned characters have values between 0 and 255, signed characters have values from 128 to 127. The character set in C Language can be grouped into the following categories. 1. Letters 2. Digits 3. Special Characters 4. White Spaces

Type SIZE (Bits) Character 8 Unsigned Character 8

Range -128 to 127 0 to 255

Data type Character Unsigned Character switch-case

Keyword Equivalent char unsigned char

The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switchcase-default, since these three keywords go together to make up the control statement. They most often appear as follows: switch ( char expression ) { case constant A: do this ; case constant B : do this ; case constant C : do this ; default : do this ; } The char expression following the keyword switch is any Cexpression that will yield an char value. It could be an char constant like a,b,c orA,B,C etc an expression that evaluates to an char. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The do this lines in the above form of switch represent any valid C statement. Example: switch( i ) { case -1: a++; printf("%d",a); break; case 0 : b++; printf("%d",b);

break; case 1 : c++; printf("%d",c); break; }

if - else statement In the if else statement if is a single line condition which contain set of statement with in the parenthesis and if if block condition is true then the control is not move on to the else .else block has no condition for check. NOTE: Expression will be assumed to be true if their evaluated value is non-zero. if statements take the following form:

if (expression) statement; *************or if (expression) { Block of statements; } if (expression) { Block of statements; } else { Block of statements; } ************* or if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; }

const const means that its not changeable, so the data that is declared with const as must not be give other value in any way during the run of a program.

const are of two type: 1.Primary Constant contain Integer Constant Real Constant Character Constant 2.Secondary Constant Array Constant Structure Constant Union Constant Enum Constant

volatile Variable can change their value any time during the program compiler should not make any assumption about which point of time the variable change its value . Normally compiler will assume that at the run time variable will behave like constant at runtime. This may a cause of error when checking a register value repeatedly. Because register variable may change its value any time. So for these kind of variables should be declared 'volatile' and it be checked each time appears in the code with out any assumption. void Void is empty data types normally used as return types in C functions declare that no value will be return by the function. Another used of void is to declare the pointer in C where it is not sure what data type is addressed by the pointer. Example: void main( ){ }

Odd Loop
/* odd loop using a for loop */ main( ) { char count = 'y' ; int number ; for ( ; count == 'y' ; ) { printf ( "Enter a number " ) ; scanf ( "%d", &number ) ; printf ( "square of %d is %d", number, number * number ) ; printf ( "\n Want to enter another number y/n " ) ; scanf ( " %c", &count ) ; } }

while

The simplest of all looping structure in C is the while statement. The general structure of the while statement is: while (test condition) { body of the loop } Here in the above example compiler check the condition if the condition is true then the body of the loop is executed else the control switch out of this block.

do-while
do while loop is similar to the while loop. In do while loop first the loop will be executed and then the condition will be checked. do { statement; } while( condition); Here the statement is executed, and then condition checked. If the condition is true then the body is executed again a. When the test condition becomes false the loop terminates. break In C language allow to the control is go to on statement to an other statement within the loop or out side the loop. The break statement is the feature of c that allows us to accomplish this. A break causes the innermost enclosing loop or switch to be exited immediately. break; continue statement In c the continue statement is similar as the break statement. In the continue the loop continued after jumping any statement for the next statement .The continue with the next iteration the format of the continue statement is simply. continue;

For
for (initialization condition; loop condition; increment expression){ } There are three parts which is separated by semi-colons in control block of the for loop. initialization condition is executed before execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part. The execution of the loop continues until the loop condition is false. This expression is checked at the beginning of each loop iteration. The increment condition, is usually used to increment the loop counter. This is executed at the end of each loop iteration.

Example:
//Here is an example of using for loop statement to print an integer five times

#include <stdio.h> void main(){ // using for loop statement int max = 10; int i = 0; for(i = 0; i < max;i++){ printf("%d\n",i); } }

return
Return statement can return a value with it to the calling function if the function is declared non - void such as int ,float ,char etc. The functions declared declare as void is not to return any value and hence a return statement with value when encountered in such a function generate to an error by compiler. Also a function declared non-void should always return a value of the respective type. Some compiler allow a relaxation which could lead to severe problems, they return garbage value if a return statement containing the value is not found in the function. General form of return statement is - return expression; Example: #include <stdio.h> int function (void) { int a; b = scanf ("%d", &a); return a; // returns the value of a to the calling function. } int main () { printf ("\n%d", function ()); return 0; }

gotogoto statement is a jump statements .goto is used for jumping from one point to
another point in your function means goto statement is work with in the function for change the control in one statement to an other statement. through goto statement its not possible that the control switch to one function to another function. Jump points or way points for goto are marked by label statements. Label statement can be anywhere in the function above or below the goto statement. Special situation in which goto find use is nested loops or if - else. General form of goto statement is .. goto label1;. . .. label1 : . . . label2 :. . .

. goto label2; Example: #include <stdio.h> int main ()// Print value 0 to 9 { int count = 1;

loop:; // label stament printf ("\n%d",count ); a++; if (count < 10) goto loop ; // jump statement

retrun 0; }

Note: Avoid the use of goto.


Operators Assignment Operator(=) The assignment operator assigns a value to a variable. There is two side in assignment operator : In assignment operator (=) left side value known as the lvalue (left value) contain variable. In assignment operator (=) right side value known as rvalue (right value) contain the value of that variable.

The in assignment operator (=) is variable has in lvalue and the value of that variable is depend in to the rvalue which may be either a variable, constant. The result of assignment operation any combination of these. int a=10; This statement assigns the integer value 10 to the variable a. Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the C language are:

+ addition - subtraction * multiplication

/ division % modulo Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) when want to change the current stored value of a variable by performing an operation we can use compound assignment operators: expression value += increase; a -= 5; a /= b; price *= units + 1; Example: int main () { int a, b=3; a = b; a+=10;// equivalent to a=a+10 printf("\n%d",a ); return 0; } Increase and decrease (++, --) Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus: 1 a++; 2 a+=1; 3 a=+1; Relational and equality operators ( ==, !=, >, < >=, <= ) Between two expressions if evaluated for comparison C language provide relational and equality operators. The result of a relational operation is a Boolean value when compare two expression that can only be true or false, according to its Boolean result. evaluation value = value + increase; a = a - 5; a = a / b; price = price * (units + 1)

== != > <

Equal to Not equal to Greater than Less than

>= <=

Greater than or equal to Less than or equal to

Logical Operator( && ,||,!) && OPERATOR In this when both conditions true then the result is true other wise in each condition the result will be false. a true true false false b true false true false a && b true false false false

|| OPERATOR
In this when both condition false then result false otherwise in each condition the result is true. a true true false false b true false true false a || b true true true false

Conditional operator ( ? :) The conditional operator evaluates an expression if the condition is true then return true value otherwise return the false value according to condition. condition ? true: false // conditional operator int main () { int a,b,c; a=10; b=20;

c = (a>b) ? a : b; printf("\n%d",c ); return 0; } In this example a was 10and b was 20, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 20. Comma operator ( , ) The comma operator (,) is used to separate two or more expressions where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. For example, the following code: a = (b=30, b+20); Would first assign the value 30 to b, and then assign b+20 to variable a. So, at the end, variable a would contain the value 50 while variable b would contain value 30. Bitwise Operators ( &, |, ^, ~, <<, >> )

Bitwise operators modify variables or shifting the bit left or right patterns that represent the values they store. operator asm equivalent description & AND Bitwise AND | OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary complement (bit inversion) << SHL Shift Left >> SHR Shift Right sizeof() This operator will accept one parameter, which can be a variable itself and returns the size of it in bytes of that type or object. a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. auto

auto variable is declared with its initial valve . The scope of the auto variable with in the block. By default if a variable declare with initial value then that variable is known as implicit auto variable. For explicit use auto key word. Example: int main() { auto int i = 0; // Explicitly declared as auto. int j = 0; // Implicitly auto. } Example: main() { auto int a=10; printf(%d,a); } Output: 10 Example: main() { auto int a1; printf(%d,a1); } Output: 1002 In example 1, a value is initialized to 10.So,output is 10. In example 2, a1 value is not initialized.So compiler reads a value is a1 garbage value. static Static Storage class is the default storage class for global variables. Static Storage class variable will be initialized to NULL in pointer. static variable by default initialized with 0. Static Storage class can be initialized at the time of compiled. Static variable have only one value during the program. If static variable declare as global then that's value cannot be changed during the program for local declaration value can be change. int main() { // Initial value is zero; a is visible only within main: static int a; } Example :

main() { add(); add(); } add() { static int a=10; printf("\n%d",a); a+=1; } Output: 10 11

extern external variable is if defined with in the block then the scope of the variable is with in the block .if the external variable is global then the scope of the variable is in entire program. for external variable used extern keyword. Example: int main( ) { // Reference to a, defined below: extern int a; } Example : int i=10; main() { int i=2; printf("%d",i); display(); } display() { printf("\n%d",i); } Output: 2 10 In above example i declared in two time .One is above the main(),second is within main().Within main() i is used in within main() only. Before main() i is used to out of the main() functions i.e, display() uses the i value as 10. register

register storage classes are used in the case of frequently used variables. register variable stored in CPU registers. . Initially register variable is use for global variables value. Access of the register variable is faster then other type of storage classes. Scope of the register variable is with in the block where that variable is defined when register variable declare as local Learn C in 7 days

Learning C in a days
1. C Programming Fundamentals ,History 2. Advantages and Disadvantages of C Language 3. The Program Flow 4. Data Types In C Language 5. Primary Data Type 6. Primitive and None Primitive Data Types 7.Secondary Data Types 8. Pointers ,Pointer Declaration, Syntax For Pointers 9. Errors in languages 10. Data in C 11. Variables 12. C Instruction 13. Integer And Float Conversions 14. Difference Between C and C++ 15. Difference between Definition and Declaration 16. Storage Classes In C Language 17. Types Of operators In C Language 18. Control Statements In C Language 18. Looping Statements 19. C Input And Output 20. Creating Compiling And Running Program in C

Programming Fundamental Programming is a way to give the instruction to the computer to perform specific tasks. We have to know that what output we want and what we should have as input for that. We have to know that what logic we provide for better output. History Of C Language Ken Thompson developed B language then Dennis Ritchie give some advance features, functionality to B Language for developing C. C language is developed by Dennis Ritchie in 1972. C language depends on ANSI (American National Standard Institute). ANSI is a standard that is made for every compilers working in same manner. This standard tells what the language should do and what is happening. Some C programs are not portable such as if we make it on Microsoft windows then we cant move it on Apple Macintosh or IBM operating system. About C language Powerful features as simple syntax, portability and improvability etc. C is a case-sensitive language. C has 32 keywords. C language is widely used in the development of operating systems. An Operating System (OS) is a software (collection of programs) that controls the various functions of a computer. C is a structured programming language, which means that it allows you to develop programs using well-defined control structures C is often called a middle-level language.

Areas where C language is used: Embedded Systems Computer Graphics Game Programming Many others Why you should learn C language? C is simple in syntax. C programs run faster than programs written in most other languages. C enables easy communication. Characteristics of C language : It is a portable language. Portable means we can run the programs on verity of computers. C is a structured language. C is a small size programming language. C language has pointer implementation. Advantages Of C Language

C is a building block for many other currently known languages. Take a look at Python for example a fully Object-Oriented High-Level programming language. It is written in C (perhaps C++ too). That tells you if you ever want to know what is going on under the hood in other languages; understanding C and how it works is essential. C is a compiled language versus an interpreted language. Explained simply, this means that the code is compacted into executable instruction (in the case of windows anyway) rather than being "translated" on the fly at run time. This feature also lends heavily to the speed of C programs.

A lot of libraries are written in C. The main advantages of C language is that there is not much vocabulary to learn, and that the programmer can arrange for the program is very fast. C programming language is very easier to learn. C programming language is still a practical and compact language. It comprises a good semantic. Syntax is of C is clear also. C language is very near to assembly programming i.e. the hard use of pointers for example is a very powerful mechanism.

C has features that allow the programmer to organize programs in a clear, easy, logical way. For example, C allows meaningful names for variables without any loss of efficiency, yet it gives a complete freedom of programming style, including flexible ways of making decisions, and a set of flexible commands for performing tasks repetitively (for, while, do).

C is a portable language.

Disadvantages Of C Language

C does not have OOPS feature that's why C++ is developed. If you know any other
modern programming language then you already know its disadvantages.

There is no runtime checking in C language.

There is no strict type checking (for ex: we can pass an integer value for the floating
data type).

C doesn't have the concept of namespace.

C doesn't have the concept of constructors and destructors.


Understanding The Program Flow #include< stdio.h> : #include : The #include in the first line of the program is called a preprocessor directive. A preprocessor is a program that processes the C program before the compiler. All the lines in the C program beginning with a hash (#) sign are processed by the preprocessor. stdio.h stdio.h, stands for "Standard Input/Output Header", stdio.h refers to a file supplied along with the C compiler. It contains ordinary C statements. These statements give information about many other functions that perform input-output roles. Library functions are declared in header files. For example. Stdio.h provide the information to printf() that what should it do. main() function : The next statement is the main() function. As you already know, this is the place where the execution of the C program begins. Without this function, your C program cannot execute. Open and closing brasses { } : Open and closinng brasses tells the starting and ending of the statement. Data Types In C Language A C language programmer has to tell the system the type of numbers or characters he is using in his program. these are data types. There are many data types in C language. Data types are used to store various types of data.. C has a concept of 'data types' which are used to define a variable before its use. A C programmer use appropriate data type as per his requirement. C supports various data types such as character, integer and floatingpoint types. Please note that there is not a Boolean data type. All the data types are made up of units of memory called bytes. In order of size, starting with the smallest, the integer types are char, short, int, long and long long. The smaller types take less memory, the larger types takes more space in memory,. C has different data types for different types of data and they are classified as: Primary Data Type Secondary Data Types These data types are further divided as.

C Keywords Keywords are the words whose meaning has already been explained to the C compiler. The keyword can't be used as variable names because if we do so, we are trying to assign a new meaning to the keyword, which is not allowed by the computer. The keywords are also called the Reserved Keywords. There are only 32 keywords available in C. Some Important Keywords In C Language : int, char, double, float, switch, case, if, else, for, while, long, short etc. Note : Compiler vendors provide their own keywords apart from mentioned above. These include Extended keywords like near, far, asm, etc. Such compiler specific keywords should be preceded by two underscore sign AS __far. Data Type Modifiers In C The data type modifiers are : short, long : Used only for int (integers), to change size of the data type for save memory space. The short modifier reduces the size of the data type to half its regular storage capabilities. unsigned, signed : Also used only for int. Unsigned modifies int to positive number range. Signed is the default modifier for all of the data types. unsigned restricts the data type so that it can only store positive values. By default all data types are signed. Signed means that the data type is capable of storing both positive and negative values.

long long : The size of long long modifier is at least 64 bits. Again was with both the short and long we have two types of the long long, signed and unsigned. Primary Data Types :

1. Integer Data Type : Integers are whole numbers with a range of values, Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32768. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. Integer Data Types are denoted by int. Syntax For Integer Data Types : Syntax : int <variable name>; For Example : int num1; short int num2; long int num3; Memory Occupied By Integer : short int (1 Byte) int (2 Bytes) long int (4 Bytes)

2. Floating Point Types : The float data type is used to store fractional numbers (real numbers). Floating point numbers are denoted by the keyword float. The double is same as float but it takes double space (8 bytes) than float. Syntax For Floating Point Types : Syntax : float <variable name>; For Example : float num1; double num2; long double num3; Memory Occupied by Float: float (4 bytes) double (8 bytes) long double (10 bytes)

3.Character Types : Character type variable can hold a single character. As there are singed and

unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from 128 to 127. Character is declared by char. Syntax For Character Types : Syntax : char <variable name>; For Example : char ch='m'; char name='P'; Void Type : The void type has no values therefore we cannot declare it as variable as we did in case of integer and float. Void data type used with function to specify its type. Like in a simple C program we declared main() as void type because it does not return any value. Primitive Data Types Built in data type is called as primitive data types. The basic primitive data types in C are such as Character, (char); Integer (short int, int, long int, long long int); Floating-point number (float, double); Boolean; and etc. Non Primitive Data Types : Non primitive types are called java reference types and they have name starting with capital letter. Example Integer, Float etc. An instance for nonprimitive data type can not be created. .A non-primitive data type is an abstract data type. Non-primrtive data types built out of primitive data types - linked list, queue, stack, etc. What Is Long Integer long integer is a data type that can represent a whole number whose range is greater than or equal to that of a standard integer on the same machine. The range of long integer is -2147483648 to 2147483647. Declaration of long int : Syntax : long int color; OR long color; What Is Short Integer The range of short int is -32768 to -32767.'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. short int must be at least 16 bits long. Declaration of short int : short int yellow; What Is Unsigned Integer

unsigned int has a range of 0 - 65535. "int" can be negative, but "unsigned int" cannot be negative. %u Prints an unsigned integer. The size can range from 2 to 8, or (again) whatever the implementation provides. Declaration of unsigned integer : unsigned int x; unsigned char grey; What Is Signed Integer %d Prints a signed integer. Range of signed int is -32768 to 32767. Declaration of signed integer : signed int y; signed char white; What Is Signed And Unsigned Char In C C allows the character type char to be signed or unsigned, depending on the platform and compiler. With an unsigned char, the variable c takes the value 255, but with a signed char it becomes -1. If the signed or unsigned version of char is explicitly required at certain points in a program, it can be specified using the declarations signed char or unsigned char. Declaration of signed and unsigned char : unsigned char grey; signed char white; Secondary Data Types :

1. Arrays : An array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C data-types int, float, and char. So an integer array can only hold integer values and cannot hold values other than integer. Types of Arrays: One Dimensional Array Two Dimensional Array Multi Dimensional Array

Declaration Of Arrays : Syntax : type var_name[size]; 2. Structures : We used variable in our C program to store value but one variable can store only single piece information (an integer can hold only one integer value) and to store similar type of values we had to declare many variables. To overcome this problem we used array which can hold numbers of similar data type. But array too have some limitations, like in our real world application we deal with set of dissimilar data types and single array cannot store dissimilar data. For example : Think about storing book information or product information, a product can have different information to store like product code (an integer), product name (a char

array), product price (a float) etc. And to store 20 products information we can declare integer array for product code, 2D character array for storing product name and float array to store product price. This approach definitely achieves your goals, but try to consider these things too. What if you wanted to add more products than 20, what if you want to add more information on products like stock, discount, tax etc? It will become difficult to differentiate these variables with other variables declared for calculation etc. To solve this problem C language has a unique data type called Structure. C structure is nothing but collection of different related data types. If we are using C structure then we are combining different related data types in one group so that we can use and manage those variables easily. Here related data type means, a structure holding information about book will contains variable and array related to book. Syntax For Structures : Syntax : struct structure_name { data type member1; data type member2; };

For Example : struct products { char name[20]; int stock; float price; }; Pointers : In C a pointer is a variable that points to or references a memory location in which data is stored. By usimg the pointer we change the content of the memory location. Pointer Declaration : A pointer is a variable that contains the memory location of another variable. The asterisk tells the compiler that you are creating a pointer variable. Finally we have to give the name of the variable. Syntax For Pointers : variable name; For Example : int *ptr; float *string Syntax Errors : If we are missing a semicolon then it is a syntax error. Logical Errors: If we want to add two numbers but we are writing result=a*b then this is called a logical error. Runtime Errors: When we want to divide a number by zero then the program compiled but not run this is called Runtime Error.

Data Type in C Constant Variable

Constant : The value of constant never be change. We can declare const before or after type. For ex. int const num=56; Or const int num=78; both are correct .

Types Of Constants Constant divided into two main types : Primary Constants Secondary Constants These constants are further categorized as Primary Constants (Integer Constants, Real Constants, Character Constants) Secondary Constants (Array, Pointer, Structure, Enum ect) Rules For Constructing Integer Constant : It must not have a decimal point. It can be either positive or negative. No commas and blanks are allowed within an integer constant. The allowable range for integer constant is -32768 to 32767. Examples of Integer Constant : 426 +786 -7605 etc. Rules For Creating Real Constants Real Constants are often called Floating Point Constants. The Real Constant could be written in two forms Fractional Form and Exponential form. o o o o A real constant must have at least one digit. It must have a decimal point. It could be either positive or negative. Default sign is positive.

No commas and blanks are allowed within a Real Constant. Examples Of Real Constants : +325.34 426.0 -32.67 etc. The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. In exponential form of representation the Real Constant is represented in two parts. The first part present before 'e' is

called Mantissa and the part following 'e' is called Exponent. For ex. .000342 can be written in Exponential form as 3.42e-4. Rules For Constructing Character Constants o A Character Constant is a single alphabet, a single digit, a special symbol enclosed within a single inverted commas For ex. 'A'.

The maximum length a character constant can be 1 character For ex. 'A', 'I', '=' etc.

Rules For Constructing Variable Names In C o o o o A Variable name is any combination of 1 to 31 alphabets, digits or underscore. The first character in variable name must be an alphabet or underscore. No commas or blanks are allowed within a variable name. No special symbol other than an underscore can be in a variable name. For Example : si_int; m_hra; etc The maximum allowable length of a variable name is 31 character.

Variables Variable may be change at runtime. A variable data object can be modified.

Types of variables: integer, char, string etc. Each type of variable has their own size and range. For ex. Range of integer is -32768 to 32767 and the range for it is 2, 4 bytes (1 byte = 8 bits). The size of a char is 1 byte. And range is from 1 to 255.

Initialization of variable : Initialize a variable in c to assign it a starting value. Without this we can't get whatever happened to memory at that moment. C does not initialize variables automatically. So if you do not initialize them properly, you can get unexpected results. Fortunately, C makes it easy to initialize variables when you declare them. For Example : int x=45; int month_lengths[] = {23,34,43,56,32,12,24}; struct role = { "Hamlet", 7, FALSE, "Prince of Denmark ", "Kenneth Branagh"}; Note : The initialization of variable is a good process in programming.

Scope And Life Span Of A Variable : The area of the program where that variable is valid, the amount of time that a variable is retained, as well as where it can be accessed from, depends on its specified location and type. The life span of that variable, i.e. the length of time that the variable remains in memory. C Instruction C instruction are of basically three types : Type declaration instruction Arithmetic Instruction Control Instruction

Type Declaration Instructions In C Language This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statements is written at the beginning of the main() function. The main purpose of type declaration instruction is to declare the type of variable C program. For Example : int num; char c; // Type Declaration float f; main() { Some Statements There are several suitable variations of the type declaration instruction: While declaring the type of the variable we can also initialize it. For Example : int num=10, j=23; float a=1.05, b=1-55+24; The order in which we define the variable is sometimes important sometimes not. For Example : int i=10, j=25; is same as int j=25, i=10; However, float a=1.5, b=a+3.1; is alright but float b=a+3.1, a=1.5; is not alright The following statements would work int a, b, c, d; a=b=c=d=10; However the following statement would not work.

int a=b=c=d=10; because here once again we are trying to use b without defining it. The Arithmetic Instruction in C A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of = The variable and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, * and /. A C arithmetic statement could be of 3 types : (a) Integer mode arithmetic statement : This is an arithmetic statement which all operands are either integer or integer constants. For Example : int i, j, l, m; i=i+1; m=i* j +l; (b) Real Mode Arithmetic Statement : These are arithmetic statement in which all operands are either real constant or real variable. For Example : float si, roi, p, q ; si = roi*p*q/100.0; (c) Mixed mode arithmetic statements : this is an arithmetic statement in which some of the operands are integer and some of the operands are real. For Example : int a, b, c, num ; avg = ( a + b+ c + num)/4; Integer And Float Conversions In order to effectively develop C program , it will be necessary to understand the rule that are used for the implicit conversion of floating point and integer values in C. These are mentioned below note them carefully: (a) An arithmetic operation between an integer and integer always yields an integer results. (b) An operation between a real and always yields a real result. (c) An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then operation is performed. Hence the result is real. Hierarchy Of Operations In C While executing an arithmetic statement, which has two or more operators, we may have some problem as to how exactly does it get executed. Priority 1st Operators *, / , % Description multiplication, division, modular

division 2nd 3rd +, = addition, subtraction assignment

For Example : /4+8-2+5/8 i=6/4+4+8-2+5/8 i=1+4/4+8-2+5/8 i=1+1+8-2+5/8 i=1+1+8-2+0 i=2+8-2+0 i=10-2+0 i=8+0 i=8 Difference Between C and C++ C is a procedural or structural language while C++ is Object Oriented Language. In C printf and scanf is used as input and output function while in C++ cin and cout is used as input and output. In C we use <#include stdio.h> as preprocessor while in C++ we use <iostream.h>. C language does not use namespaces while C++ uses namespaces to reduce collision. In C memory is allocated by malloc while in C++ memory is allocated by new keyword. C does not use the concept of constructor while C++ uses constructor and destructor. C++ adds many more features in C language. C does not use reference variable while C++ uses reference variables. C language follows Top Down approach while C++ follows Bottom Up approach. C++ uses the concept of class, object and inheritance etc while C doesnt use these concepts

Difference between Definition and Declaration Both objects and functions can be defined and declared. When we declare a variable or object then its attribute is known to the compiler. When we define a object then the attribute is known to the compiler and the object is also be created. Definition means where a variable or function is defined and memory is allocated for variable or function. Whenever a variable is defined within the function then it has local scope (local scope means that variable con only access locally). While when a variable is defined outside the function then it has global scope (global scope means we can access the variable globally or anywhere). Example of definition and declaration :

void fun(int num) {

int n; // Declaration of variable n= num; // Definition of variable } Here we are passing integer type parameter to fun function and we are also declaring n as integer which is known by compiler that is called Declaration and are assigning the value num to n is called definition. Example For Global Scope Of Variable : int num; char letter; // int num and char are global variables main() { num=23; letter=A; } Example For Local Scope Of Variable : main() { int num; // int num and char ch are local variables char ch; num=2; ch=a; } Storage Classes In C Language Storage classes define the scope and lifetime of the variable and function within a C program. Types of storage classes in C : Auto storage class Register storage class Static storage class Extern storage class Auto storage class : This is the default storage class for local variable. For example: { int num; auto int month; } Register storage class : This is used to define the local variable that should be stored in register instead of RAM. For example. { register int miles; }

Static storage class : This is the default storage class for global variables. For example. { int num; static int count; main() printf(%d,count); } Extern storage class : Extern is used to give a reference of a global variable that is visible to all the program files. File 1: main.c

int count=5; main() { write_extern(); } File 2: write.c void write_extern(void); extern int count; void write_extern(void) { printf("count is %i\n", count); } Here extern keyword is being used to declare count in another file. Types Of operators In C Language

What is an operator: If we take an expression 9+5=14, here 9 and 5 are operands and + is an operator. Types of operator : Arithmetic Operators Logical Operators Assignment Operators Bitwise Operator Misc Operator Arithmetic Operators: The arithmetic operators are +, -, *, %, /, ++, -For ex. If a variable A=10 then A++=11 and A--=9 Relational) Operators : ==, !=, >, <, &&, ||, <=, >= are the logical operators. For Example. If variable A =10 and B=23 then (A=B) is false, (A<B) is true etc.

Bitwise Operators: Bitwise operators works on bits and perform bit by bit operation. Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 and B = 0000 1101 A&B = 0000 1000 Assignment Operators : =, +=, -=, /=, %= &=, |= etc are the assignment operators. For Example. C = A + B will assign value of A + B into C and C+= A means C=C+A. Misc Operators : These are some special kind of operators such as sizeof(), *(Pointer), &(address). For Example. sizeof (a) means that If a is integer then it returns value 4. *a means a will be a pointer to 'a' variable. Control Statements In C Language

C language provides 2 types of control statements Branching Statements Looping Statements

Branching Statements : In branching statement what action is to be performed is decided. Ex. of branching statements are 1. If Statements : Syntax for if statements:

if (expression) statement; if (expression) { Block of statements; } if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; }

2. Switch case statements : Syntax for switch Case statements

switch( expression ) { [case constant-expression1: statements1;] [case constant-expression2: statements2;] [case constant-expression3: statements3;] [default: statements4;] } Looping Statements: In looping statement how many times the action is to be perform. Ex. of looping statements : 1. While loop: while ( expression ) { Single statement or Block of statements; } 2. Do While loop: do { Single statement or statements; } while(expression); 3. For loop : for ( expression1; expression2; expression3) { Single statement or Block of statements; } Nesting Of Loops In C Nested loop, means one loop in the other loop. For Example : for (i=0; i<10; ++i) {

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

Multiple Initialization In A For Loop This means , we can initialize more than one variable within one loop. For Example : for (int i=0,int j=10 ; i<5&&j<10 ; i++ , j--) { some block of statements } Odd Loop In C Loop is define as "the repetition of data according to the given conditions " so odd loop is that loop which only repeat the odd numbers & it leave the even numbers". Break Statement In C The break command allows you to terminate and exit a loop (that is, do, for, and while). You can place a break command only in the body of a looping command or in the body of a switch command. The break keyword must be lowercase and cannot be abbreviated. In a looping statement, the break command ends the loop and moves control to the next command outside the loop. Within nested statements, the break command ends only the smallest enclosing do, for, switch, or while commands. In a switch body, the break command ends the execution of the switch body and transfers control to the next command outside the switch body. For Example : #include <stdio.h> #include <conio.h> void main() { clrscr(); int n; printf(" \nEnter the number :"); scanf("%d", &n); if (n < 0) { break; } } The Continue Statement In C The continue statement can only appear in a loop body. It skipped the rest of the statement body in the loop. Syntax : continue;

For Examples: for (loop=0;loop<100;loop++) { if (loop==50) continue; printf ("%i\n", loop); } Output: The numbers 0 through 99 are printed except for 50. goto Statement In C goto is used for jumping from one statement to another. It is very negative approch to use goto in our program due its inherent properties of breaking the code. Syntax : goto label;

The goto statement is often combined with the if statement. Syntax : if condition then goto label; For Example : #include <stdio.h> #include <conio.h> int main() { int n = 0; loop: ; printf("\n%d", n); n++; if (n<10) goto loop; } getch(); return 0; } Output will be displayed as: 0 1 2 3 4 5 6 7 8 9 Disadvantages Of goto Statement

Goto should not really be used in programs at all because they have a tendency to make code unstructured and they make programs difficult to manage when they become significantly large. C Input And Output

printf() Function: This is one of the most frequently used functions in C for output. For example. #include <stdio.h> main() { int num = 5; char str[] = "mini"; char ch = 's'; float pi = 3.14; printf("%d %s %f %c\n", num, str, pi, ch); } Scanf() Function: This is one of the most frequently used functions in C for intput. For Example. #include <stdio.h> main() int num ; char str[] = "mini"; char ch = 's'; float pi = 3.14; printf(enter the value of num); scanf(%d,&num); // take the value of num as input printf("%d %c %f", num,str,pi); // print the values of num,str,pi,ch } Creating Compiling And Running Program in C The steps involved in building a C program are: 1. Create a program by using any text editor and the file is stored with extension as .c. 2. Next the program is compiled. There are many compilers available like GNU C compiler called as gcc, Sun compiler, Borland compiler which is popular with PC system and so on. Lots of options are available for compiling. The command used for compilation is cc name of the file.c. At this stage errors like typing mistake, mistake in key words, syntax usage errors will be detected and will displayed which the programmer can correct. But a programmer must note that compiler cannot detect logical errors. 3. After this process the compiled or executable code by default gets stored in a . out. If

one wants to store the executable code in a filename instead of in a . out this can be done by using the -o option along with cc -o sample sample.c 4. After compilation the program is executed by using the executable file name. At this stage runtime errors or incorrect output due to logical or functional errors may be seen in output which is corrected further and the process is repeated until the correct result is displayed.

Fig. The C Compilation Model

Fig. The C Compilation Model

26 Points about C basics 79 Points About C Basics

1. INTRODUCTION OF C LANGUAGE 2. DATA TYPES

3. SIGNED AND UNSIGNED 4. FLOATS AND DOUBLES 5. KEYWORDS and DATA TYPE 6. CONSTANTS AND VARIABLES 7. HOW TO MAKE A SIMPLE C PROGRAM 8. COMPILATION AND EXECUTION 9. RECEIVING INPUT 10. C- INSTRUCTION 11. INTEGER AND FLOAT CONVERSION 12. OPERATORS 13. DECISION CONTROL STRUCTURE

14. DECISION USING SWITCH


15. LOOP CONTROL STRUCTURE 16. FUNCTION 17. WHAT IS A FUNCTION 18. CALL BY VALUE AND CALL BY REFERENCE 19. POINTER 20. POINTER EXPRESSION AND POINTER ARITHMETIC 21. RECURSION 22. ADDING FUNCTION TO THE LIBRARY 23. STORAGE CLASS IN C 24. C PRE-PROCESSOR 25. MACROS VS FUNCTION

26. FILE INCLUSION


INTRODUCTION OF C LANGUAGE C is a computer language developed by Dennis Ritchie at bell laboratories in 1972.The ANSI standard for c replaced the standard written by Kernighan and Ritchie in 1978.The structure of C is similar to PL/I which is a popular language used on IBMs mainframe computers. C is a simple language which has small group of key words and there is no support for I/O and advance math. C can address and manipulate memory by direct address. C has a powerful library function which enables programmers to perform I/O and work with strings. But before understanding any language and its contents we have to know some basic concept. HISTORY OF C C is a programming language developed at AT & Ts Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In that time some languages were there like Algol-60 and Pascal. C language is member of Algol-60 based languages. CPL( Combined Programming Language) was built but it never implemented after BCPL(Basic CPL) came as implemented language. It was rewritten by Ken Thompson in 1970 named B specially for UNIX Operating System. Dennis M. Ritche added some new features and introduced a new language called C language. The major advance of C over the languages B and BCPL was its typing structure. C language adopted some features from Algol-68 also. ADVANTAGES OF C 1.C is very suitable for system programming. 2.C encourages the code reusability. 3.C encourages the structured programming. 4. the different modules can be present in different source files and they can be compiled separately. 5. C is one of the most portable languages. 6. C supports a number of data types. STRUCTURE OF A C PROGRAM a typical c program has 3 section1.preprocessor directives 2.global declarations 3.function(s) DATA TYPES

The C language supports a number of data types, all of which are necessary in writing programs. Because most CPUs generally support these data types directly, it is unnecessary for the compiler to convert the data types into the types the CPU understands. In addition to the standard types, new data types are needed, which are often unique to a given application, and C provides the mechanisms to create and use types of data created by the programmer. INTEGER DATA TYPE int 2 or 4 bytes Used for integer values. FLOAT DATA TYPE float 4 bytes Floating-point numbers. CHAR DATA TYPE char 1 byte Used for characters or integer variables. INTEGERS LONG AND SHORT the range of an Integer constant depends upon the compiler. C offers a variation of the integer data type that provides what are called short and long integer values. Though not a rule, short and long integers would usually occupy two and four bytes respectively. Each compiler can decide appropriate sizes depending on the operating system and hardware for which it is being written, subject to the following rules: (a) shorts are at least 2 bytes big (b )longs are at least 4 bytes big (c) shorts are never bigger than ints (d) ints are never bigger than longs If there are such things as longs, symmetry requires shorts as wellintegers that need less space in memory and thus help speed up program execution. short integer variables are declared as, short int j ; short int height ; C allows the abbreviation of short int to short and of long int to long. So the declarations made above can be written as, long i ; long abc ; short j ; short height ; INTEGERS SIGNED AND UNSIGNED we know in advance that the value stored in a given integer variable will always be positive when it is being used to only count things, for example. In such a case we can declare the

variable to be unsigned, as in, unsigned int num_students ; an unsigned integer still occupies two bytes. This is how an unsigned integer can be declared: unsigned int i ; unsigned i ; Like an unsigned int, there also exists a short unsigned int and a long unsigned int. By default a short int is a signed short int and a long int is a signed long int.

CHAR SIGNED AND UNSIGNED Parallel to signed and unsigned ints (either short or long), similarly there also exist signed and unsigned chars, both occupying one byte each, but having different ranges. To begin with it might appear strange as to how a char can have a sign. Consider the statement char ch = 'A' ; Here what gets stored in ch is the binary equivalent of the ASCII value of A (i.e. binary of 65). And if 65s binary can be stored, then -54s binary can also be stored (in a signed char). A signed char is same as an ordinary char and has a range from -128 to +127; if we are bent upon writing the program using unsigned char, it can be done as shown below. The program is definitely less elegant, but workable all the same.

main( ) { unsigned char ch ; for ( ch = 0 ; ch <= 254 ; ch++ ) printf ( "\n%d %c", ch, ch ) ; printf ( "\n%d %c", ch, ch ) ; } FLOATS AND DOUBLES A float occupies four bytes in memory and can range from -3.4e38 to +3.4e38. If this is insufficient then C offers a double data type that occupies 8 bytes in memory and has a range from -1.7e308 to +1.7e308. A variable of type double can be declared as, double a, population ; If the situation demands usage of real numbers that lie even beyond the range offered by double data type, then there exists along double that can range from -1.7e4932 to +1.7e4932. A long double occupies 10 bytes in memory. some of the data types are given below with their range n how much space they required.

DATA TYPES

RANGE -128 to + 127

BYTE

FORMAT

signed char unsigned char short signed int short unsigned int signed int unsigned int long signed int long unsigned int float double long double

0 to 255 -32768 to +32767 0 to 65535 -32768 to +32767 0 to 65535 -2147483648 to +2147483647 0 to 4294967295 -3.4e38 to +3.4e38 -1.7e308 to +1.7e308 -1.7e4932 to +1.7e4932

1 1 2 2 2 2 4 4 4 8 10

%c %c %d %u %d %u %ld %lu %f %lf %Lf

C KEYWORDS The meaning of keywords has already been explained to the C compiler. The key word cannot be used as variable name because if we do so we are trying to assign new meaning to the keyword, which is not allowed by the computer. The keywords are also called RESERVED WORDS.

There are 32 keywords used in C language. which are

"auto, double, int, struct, break, else, long, switch, case, enum, register, typedef, char, extern, return, union, const, float, short, unsigned, continue, for, signed, void, default, goto, sizeof, volatile, do, if, static, while"

14-DATA TYPE MODIFIERS IN C1- long-Forces a type int to be 4 bytes (32 bits) long and forces a typebdouble to be larger than a double (but the actual size is implementation defined). Cannot be used with short.

2- short- short Forces a type int to be 2 bytes (16 bits) long. Cannot be used with long. 3- unsigned- unsigned Causes the compiler (and CPU) to treat the number as containing only positive values. Because a 16-bit signed integer can hold values between 32,768 and 32,767, an unsigned integer can hold values between 0 and 65,535. The unsigned modifier can be used with char, long, and short (integer) types. CONSTANTS AND VARIABLES A constant is an entity that doesnt change whereas a variable is an entity that may change. In any program we typically do many calculations and the result of these calculation are stored in computers memory. To make the retrieval and usage of the value easy these memory locations are given names. Since the value stored in each location may change the names given to these locations are called variable names. TYPES OF C VARIABLES As we know that an entity that may vary during the program execution is called variable .variable names are names given to location in memory. the rules of constructing different type of constants is different. SCOPE OF VARIABLES The scope of a variable is often one of the things programmers dont understand at first. Depending on where they are declared, variables can be either visible or not visible. LIFE SPAN OF VARIABLE Determining how long a variable will be kept is another problem that perplexes aspiring programmers. Lets look at the keyword modifier static. This modifier has several purposes that, unfortunately, are related. When static is used on a variable found within a function or block, it tells the compiler never to discard or reallocate the variable. The variable is created at compile time and is initialized to zero. The opposite of static in this situation is auto (the default). That variable, found inside a function or block, is reallocated every time the function or block is entered. When static is used on a variable that is defined outside any functions or blocks, its meaning is that the variable is known to only those functions contained in the specified source file, and are not known outside the source file. When a variable is known outside the source file, it is called an external variable. (Dont confuse this with the keyword extern.) The extern keyword tells the compiler that the variable is being defined (and not declared). Because extern and static conflict, they cannot be used together. RULES FOR CONSTRUCTING VARIABLE NAMES a. a variable name is any combination of 1 to 31 alphabets, digits or underscores. b. The first character in the variable name must be an alphabet or an underscore. c. No commas or blanks are allowed with in variable name. d. No special symbol other than underscore can be used in a variable name. Ex -- gross salary TYPES OF C CONSTANTS Primary constants

1. integer constants 2. real constants 3. character constants Secondary constants 1. array 2. pointer 3. structure 4. union etc.

RULES OF CONSTRUCTING INTEGER CONSTANTS a. an integer constant must have at least one digit. b. It must not have a decimal point. c. It can be either positive or negative. d. The allowable range for constants is -32768 to 32767 In fact the range of integer constants depends upon compiler. For ex. 435 +786 -7000 CONSTRUCTING REAL CONSTANTS a. A real constants must have at least one digit b. it must have a decimal point. c. it could be either positive or negative. d. default sign is positive. For ex. +325.34 426.0 In exponential form of representation, the real constants is represented in two parts. The part appearing before e is called mantissa where as the part following e is called exponent. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Ex. +3.2e-5 RULES OF CONSTRUCTING CHARACTER CONSTANTS a. a character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. b. The maximum length of character constant can be one character. Ex `A` WHAT IS AN IDENTIFIER An identifier is used for any variable, function, data definition. If we talk about C then an identifier is a combination of alphanumeric characters. There are some rules which are used in naming identifiers. DIFFERENCE BETWEEN DEFINITION AND DECLARATION Both objects and functions can be defined and declared. When we declare a variable or object then its attribute is known to the compiler. When we define a object then the attribute is known to the compiler and the object is also be created. Whenever a variable is defined within the function then it has local scope (local scope means that variable con only access locally). While when a variable is defined outside the

function then it has global scope (global scope means we can access the variable globally or anywhere). The simplest declaration of a variable is shown in the following code fragment: void OurFunction(int nType) { int nTest; nTest = nType; } In the fragment, an integer variable is defined. That is, both its attributes (the variable is an integer) were made known to the compiler, and storage was allocated. HOW TO MAKE A SIMPLE C PROGRAM There are some rules by the help of which we can make a simple C program. The rules are given below. a. Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements. b. The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate jump or transfer of control to a statement, which is out of sequence. c. Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword. d. All statements are entered in small case letters. e. Every C statement must end with a ;. Thus ; acts as statement terminator. Let us take an example to understand the first C program /* Calculation of simple interest main( ) { int p, n ; float r, si; p = 1000; n = 3; r = 8.5; /* formula for simple interest */ si = p * n * r / 100 ; Printf ("%f", si); } main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below. main ( ) { statement 1; Statement 2; } Technically speaking main () is a function.

Any variable used in the program must be declared before using it Ex. int p, n; The printf () function is used to display the value. The general form of the printf () function is Printf (<format string>", <list of variables> ) ; <format string> can contain, %f for printing real values %d for printing integer values %c for printing character values COMPILATION AND EXECUTION Once you have written the program you need to type it and instruct the machine to execute it. To type your C program you need another program called Editor. Once the program has been typed it needs to be converted to machine language (0s and 1s) before the machine can execute it. To carry out this conversion we need another program called Compiler. Compiler vendors provide an Integrated Development Environment (IDE) which consists of an Editor as well as the Compiler. If you are a beginner you would be better off using a simple compiler like Turbo C or Turbo C++.here are the steps that you need to follow to compile and execute your first C program

(a) Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\BIN directory). (b) Select New from the File menu. (c) Type the program. (d) Save the program using F2 under a proper name (say Program1.c). (e) Use Ctrl + F9 to compile and execute the program. (f) Use Alt + F5 to view the output. If you run this program in Turbo C++ compiler, you may get an error The function printf should have a prototype. To get rid of this error, perform the following steps and then recompile the program. (a) Select Options menu and then select Compiler | C++ Options. In the dialog box that pops up, select CPP always in the Use C++ Compiler options. (b) Again select Options menu and then select Environment | Editor. Make sure that the default extension is C rather than CPP. RECEIVING INPUT To make the program general the program itself should ask the user to supply the values through the keyboard during execution. This can be achieved using a function called scanf( ). This function is a counter-part of the printf( ) function. printf( ) outputs the values to the screen whereas scanf( ) receives them from the keyboard. This is illustrated in the program shown below.

/* Calculation of simple interest */ /* Author gekay Date 25/05/2004 */

main( ) { int p, n ; float r, si ; printf ( "Enter values of p, n, r" ) ; scanf ( "%d %d %f", &p, &n, &r ) ; si = p * n * r / 100 ; printf ( "%f" , si ) ; }

in the above program The first printf( ) outputs the message Enter values of p, n, r on the screen.the value of the program can be received by the function scanf( ) C INSTRUCTION There are basically 3 types of instruction in c. 1. type declaration instruction 2. arithmetic instruction 3. control instruction

TYPE DECLARATION INSTRUCTION To declare the type of variables used in c program. Ex- int bas ; float rs, gross Sal ; char name, code;

ARITHMETIC INSTRUCTION To perform arithmetic operation between constants and variables. Ex- int ad ; float kot, deta, alpha, beta, gamma ; ad = 3200 ; kot = 0.0056 ; deta = alpha * beta / gamma + 3.2 * 2 / 5 ; Here, *, /, -, + are the arithmetic operators. = is the assignment operator. 2, 5 and 3200 are integer constants. 3.2 and 0.0056 are real constants. ad is an integer variable. kot, deta, alpha, beta, gamma are real variables CONTROL INSTRUCTION

To control the sequence of execution of various statements in c program. (a) Sequence Control Instruction (b) Selection or Decision Control Instruction (c) Repetition or Loop Control Instruction (d) Case Control Instruction INTEGER AND FLOAT CONVERSION In order to effectively develop C programs, it will be necessary to understand the rules that are used for the implicit conversion of floating point and integer values in C. These are mentioned below. (a) An arithmetic operation between an integer and integer always yields an integer result. (b) An operation between a real and real always yields a real result. (c) An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then the operation is performed. Hence the result is real. example- operation 5/2 5.0 / 2 result 2 2.5

TYPE CONVERSION IN ASSIGNMENT It may so happen that the type of the expression and the type of the variable on the lefthand side of the assignment operator may not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of =. For example, consider the following assignment statements. int i ; float b ; i = 3.5 ; b = 30 ; Here in the first assignment statement though the expressions value is a float (3.5) it cannot be stored in i since it is an int. In such a case the float is demoted to an int and then its value is stored. Hence what gets stored in i is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b being a float variable cannot hold anything except a float value. Instead of a simple expression used in the above examples if a complex expression occurs, still the same rules apply. For example, consider the following program fragment. float a, b, c ; int s ; s = a * b * c / 100 + 32 / 4 - 3 * 1.1 ; Here, in the assignment statement some operands are ints whereas others are floats. As we know, during evaluation of the expression the ints would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to s it is again demoted to an int and then stored in s.

HIERARCHY OF OPERATORS There are some operators which are given bellow with their mean. The higher the position of an operator is, higher is its priority.

Operator !

Type

Logical NOT Arithmetic and modulus Arithmetic Relational Relational Logical AND Logical OR Assignment

*/ % +<> <=>= ==!= && || =

ASSOCIATIVITY OF OPERATOR When an expression contains two operators of equal priority the tie between them is settled using the associatively of the operators. Associatively can be of two typesLeft to Right or Right to Left. Left to Right associatively means that the left operand must be unambiguous. Unambiguous in what sense? It must not be involved in evaluation of any other sub-expression. Similarly, in case of Right to Left associatively the right operand must be unambiguous. Let us understand this with an example. Consider the expression a=3/2*5; Here there is a tie between operators of same priority, that is between / and *. This tie is settled using the associatively of / and *. But both enjoy Left to Right associatively. LOGICAL OPERATORS: a There are only three logical operator in C. 1. && AND

2.
3. !

||

OR
NOT

The first two operator allows two or more conditions to be combined in an if statement.

! Operator: The third logical operator is !(NOT) operator. This operator reverses the result of the expression evaluates to a non-zero value, then applying ! operator to it results into a 0.

USE OF LOGICAL OPERATORS C allows usage of three logical operators, namely, &&, || and !.These are to be read as AND OR and NOT respectively. here we can take an example to under stand the logical operators which is given belowmain( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; } As can be seen from the second if statement, the && operator is used to combine two conditions. Second division gets printed if both the conditions evaluate to true. If one of the conditions evaluate to false then the whole thing is treated as false. By the above example we can understand the else if condition which is only the arrangement of else with if. BITWISE OPERATOR One of Cs powerful features is a set of bit manipulation operators. These permit the programmer to access and manipulate individual bits within a piece of data. The various Bitwise Operators available in C are shown belowoperator meaning ~ >> << & | ^ one's compliment right shift left shift bitwise AND bitwise OR bitwise XOR (exlucive OR)

These operators can operate upon ints and chars but not on floats and doubles. Before moving on to the details of the operators. 1. one's compliment operator-

On taking ones complement of a number, all 1s present in the number are changed to 0s and all 0s are changed to 1s. For example ones complement of 1010 is 0101. Similarly, ones complement of 1111 is 0000. 2. right shift operatorThe right shift operator is represented by >>. It needs two operands. It shifts each bit in its left operand to the right. The number of places the bits are shifted depends on the number following the operator (i.e. its right operand). For example, if the variable ch contains the bit pattern 11010111, then, ch >> 1 would give 01101011 and ch >> 2 would give 00110101. 3. left shift operatorThis is similar to the right shift operator, the only difference being that the bits are shifted to the left, and for each bit shifted, a 0 is added to the right of the number. 4. bitwise AND operatorThis operator is represented as &. Remember it is different than &&, the logical AND operator. The & operator operates on two operands. While operating upon these two operands they are compared on a bit-by-bit basis. Hence both the operands must be of the same type (either char or int). The second operand is often called an AND mask. The & operator operates on a pair of bits to yield a resultant bit. we can make a truth table for this operator which is given below& 0 1 0 1

0 0 1 0

bitwise OR operator- Another important bitwise operator is the OR operator which is represented as |. The rules that govern the value of the resulting bit obtained after ORing of two bits is shown in the truth table below. | 0 1 0 0 1 0 1 1

Using the Truth table confirm the result obtained on ORing the two operands as shown below. 11010000 Original bit pattern

00000111 OR mask

------------11010111 Resulting bit pattern

Bitwise OR operator is usually used to put ON a particular bit in a number. 5. bitwise XOR operatorThe XOR operator is represented as ^ and is also called an Exclusive OR Operator. The OR operator returns 1, when any one of the two bits or both the bits are 1, whereas XOR returns 1 only if one of the two bits is 1. The truth table for the XOR operator is given below. ^ 0 0 0 1 1 0 1 1

XOR operator is used to toggle a bit ON or OFF. A number XORed with another number twice gives the original number. CONDITIONAL OPERATORS The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is, expression expression 2 : expression 3 the mean of the above form is ''if expression1 is true then the value returned will be expression2 otherwise the value returned will be expression3. The following points may be noted about the conditional operators: a. Its not necessary that the conditional operators should be used only in arithmetic statements. This is illustrated in the following examples:

Ex.: int i ; scanf ( "%d", &i ) ; ( i == 1 ? printf ( "Amit" ) : printf ( "All and sundry" ) ) ; b. The conditional operators can be nested as shown below. int big, a, b, c ; big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ; c. Check out the following conditional expression: a>b?g=a:g=b; This will give you an error Lvalue Required. The error can be overcome by enclosing the statement in the : part within a pair of parenthesis. This is shown below: a>b?g=a:(g=b);

In absence of parentheses the compiler believes that b is being assigned to the result of the expression to the left of second =. Hence it reports an error. The limitation of the conditional operators is that after the ? or after the : only one C statement can occur. In practice rarely is this the requirement. Therefore, in serious C programming conditional operators arent as frequently used as the if-else. DECISION CONTROL STRUCTURE In C programming we want the program to be executed sequentially. we want a set of instruction to be executed at one time and an entirely set of instruction to be executed in another situation. in this type of situation will have to use the decision control structure.

IF STATEMENT- Like most languages c uses the keyword if to implement the decision control instruction. The general form of the if statement is given belowif this condition is true) execute the statement; the keyword if tells the compiler to follow the decision control instruction. Any condition which follow the if keyword, always enclosed within pair of parentheses. We express a condition using Cs relational operators which allow us to compare two values to see whether they are equal, unequal or one is greater than other. We can explain these operators like belowthis expression is true if x == y x is equal to y x != y x is not equal to y x < y x is less than y x > y x is greater than y x <= y x is less than or equal to y x >= y x is greater than or equal to y

here is an example which shows the use of if and relation operator--/* Demonstration of if statement */ main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; } Explanation- when we execute the above program then if you type the number less than 10 then you will get a message on screen through printf(). If you type the number which is greater than 10 then program will do nothing. As we generally mention the form of if as below if(condition) statement; but trually speaking the form of if is given bellow

if(expression) statement;

IF-ELSE CONDITION The if statement by itself will execute the single statement or a group of statement when the expression follow if evaluates true and another expression with in single group of statement followif evaluates falls then we generally use th if-else condition. To understand the if-else condition we can take an example which is given below/* Calculation of gross salary */ main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; }

NESTED 'IF-ELSE' Nested if-elses It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called nestingof ifs. This is shown in the following program. /* A quick demo of nested if-else */ main( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You would go to heaven !" ) ; else { if ( i == 2 ) printf ( "Hell was created with you in mind" ) ; else printf ( "How about mother earth !" ) ; }

} MULTIPLE STATEMENT WITHIN 'IF' It may so happen that in a program we want more than one statement to be executed if the expression following if is satisfied. If such multiple statements are to be executed then they must be placed within a pair of braces as illustrated in the following example. /* Calculation of bonus */ main( ) { int bonus, cy, yoj, yr_of_ser ; printf ( "Enter current year and year of joining " ) ; scanf ( "%d %d", &cy, &yoj ) ; yr_of_ser = cy - yoj ; if ( yr_of_ser > 3 ) { bonus = 2500 ; printf ( "Bonus = Rs. %d", bonus ) ; } } Observe that here the two statements to be executed on satisfaction of the condition have been enclosed within a pair of braces. If a pair of braces is not used then the C compiler assumes that the programmer wants only the immediately next statement after the if to be executed on satisfaction of the condition. In other words we can say that the default scope of the if statement is the immediately next statement after it. FORM OF 'IF' The if statement can take any of the following forms: (a) if ( condition ) do this ;

(b) if ( condition ) { do this ; and this ; }

(c) if ( condition ) do this ; else do this ;

(d) if ( condition ) { do this ; and this ; }

else { do this ; and this ; }

(e) if ( condition ) do this ; else { if ( condition ) do this ; else { do this ; and this ; } }

(f) if ( condition ) { if ( condition ) do this ; else { do this ; and this ; } } else do this ;

'ELSE IF' CONDITION else if condition is nothing but this this a way to arrange the else with the if that follows it. if ( i == 2 ) printf ( "With you" ) ; else if(j==2) { printf("All the time"); }

DECISION USING SWITCH- the control statement that allows us to make a decision from the number of choices is called "switch". the switch is look as following-: switch ( integer { case constant 1 do this ; case constant 2 do this ; case constant 3 do this ; default : do this ; } expression ) : : :

we can take an example of the switch case to understand easily it in deepmain( ) { int i = 2 ; switch ( i ) { case 1 : printf ( "I am in case 1 \n" ) ; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; } } The output of this program would be: I am in case 2 I am in case 3 I am in default USE OF SWITCH WITH DECISION CONTROL STATEMENT 1. Every statement in a switch must belong to some case or the other. 2. we can also use char values in case and switch. 3. If we have no default case, then the program simply falls through the entire switch and continues with the next instruction (if any,) that follows the closing brace of switch. 4.switch is a replacement for 'if' because it offers a better way of writing program as compared to if.

5.The advantage of switch over if is that it leads to a more structured program and the level of indentation is manageable, more so if there are multiple statements within each case of a switch. 6.The break statement when used in a switch takes the control outside the switch. However, use of continue will not take the control to the beginning of switch as one is likely to believe. SWITCH VERSUS IF-ELSE LADDER 1. A float expression cannot be tested using a switch. 2. Cases can never have variable expressions (for example it is wrong to say case a +3 : ). 3.Multiple cases cannot use same expressions. Thus the following switch is illegal:

switch ( a ) { case 3 : ... case 1 + 2 : ... } LOOP CONTROL STRUCTURE LOOP-The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times until particular condition is being satisfied. there are methods by way of which we can repeat a part of program. TYPES OF LOOP 1- using a for statement 2- using a while statement 3- using a do while statement WHILE LOOP this is the case when you want to do something a fixed number of times. for example-- if we want to calculate the gross salary of 10 people then the while loop is best suited for that process. the general form of the while loop is given below-initialize loop counter; while(test loop counter using a condition)

{ do this; and this; increment loop counter; } SOME CONDITIONS FOR WHILE LOOP 1.the statement within the while loop would keep on getting executed till condition being tested remains true. 2.if condition becomes falls the control passes to the first statement that follows the body of the while loop. 3. the condition being tested may use may use relational or logical operators. for example--

while(i<=10) while(i>=10&&j<=5)

4. the statement within the loop may be a single line or a block of statement.

for example--while ( i <= 10 ) i = i + 1; is same as while ( i <= 10) { i=i+1; } 5. it is not necessary that a loop counter must be an int. it can be float also. main( ) { float a=10.0; while(float a<=10.5) { printf("raindrops on roses"); a=A+0.1; } } 'FOR' LOOP

the 'for' allows us to specify three things about a loop in a single line-a- setting a loop counter to an initial value. b- testing the loop counter to determine whether it's value has reached the number of repetition desired. c-increasing the value of loop counter each time the program segment with in the loop has been executed. the general form of 'for' statement is as follows

for(initialize counter;test counter;increment counter) { do this; and this; and this; } example/* Calculation of simple interest for 3 sets of p, n and r */ main ( ) { int p, n, count ; float r, si ; for ( count = 1 ; count <= 3 ; count = count + 1 ) { printf ( "Enter values of p, n, and r " ) ; scanf ( "%d %d %f", &p, &n, &r ) ; si = p * n * r / 100 ; printf ( "Simple Interest = Rs.%f\n", si ) ; } }

the execution process for the above program is given as follows When the for statement is executed for the first time, the value of count is set to an initial value 1. Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time. Upon reaching the closing brace of for, control is sent back to the for statement, where the value of count gets incremented by 1. Again the test is performed to check whether the new value of count exceeds 3. If the value of count is still within the range 1 to 3, the statements within the braces of for are executed again. The body of the for loop continues to get executed till count doesnt exceed the final value 3. When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for.

MULTIPLE INITIALIZATION IN FOR LOOP one statement separated by a comma. For example, for ( i = 1, j = 2 ; j <= 10 ; j++ ) Multiple statements can also be used in the incrementation expression of for loop; i.e., you can increment (or decrement) two or more variables at the same time. However, only one expression is allowed in the test expression. This expression may contain several conditions linked together using logical operators. Use of multiple statements in the initialisation expression also demonstrates why semicolons are used to separate the three expressions in the for loop. If commas had been used, they could not also have been used to separate multiple statements in the initialisation expression, without confusing the compiler. THE 'DO WHILE' LOOP The do-while loop looks like this: do { this ; and this ; and this ; and this ; } while ( this condition is true ) ;

the major difference between the while loop and dowhile loop is that The while tests the condition before executing any of the statements within the while loop. As against this, the do-while tests the condition after having executed the statements within the loop. example-

main( ) { do { printf ( "Hello there \n") ; } while ( 4 < 1 ) ; }

In this program the printf( ) would be executed once, since first the body of the loop is executed and then the condition is tested. break and continue are used with do-while just as they would be in a while or a for loop. A break takes you out of the do-while bypassing the conditional test. A continue sends you straight to the test at the end of the loop. NESTING OF LOOPS The way if statements can be nested, similarly whiles and fors can also be nested. To understand how nested loops work, look at the program given below:

/* Demonstration of nested loops */ main( ) { int r, c, sum ; for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ { for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */ { sum = r + c ; printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ; } } } When you run this program you will get the following output: r = 1 c = 1 sum = 2 r = 1 c = 2 sum = 3 r = 2 c = 1 sum = 3 r = 2 c = 2 sum = 4 r = 3 c = 1 sum = 4 r = 3 c = 2 sum = 5 Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2. The inner loop terminates when the value of c exceeds 2, and the outer loop terminates when the value of r exceeds 3. As you can see, the body of the outer for loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the program easier to understand. Instead of using two statements, one to calculate sum and another to print it out, we can compact this into one single statement by saying: printf ( "r = %d c = %d sum = %d\n", r, c, r + c ) ; The way for loops have been nested here, similarly, two while loops can also be nested. Not only this, a for loop can occur within a while loop, or a while within a for. THE ODD LOOP The loops that we have used so far executed the statements within them a finite number of times. for example/* Execution of a loop an unknown number of times */ main( ) { char another ; int num ; do { printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; } while ( another == 'y' ) ; } And here is the sample output... Enter a number 5 square of 5 is 25 Want to enter another number y/n y Enter a number 7 square of 7 is 49

In this program the do-while loop would keep getting executed till the user continues to answer y. The moment he answers n, the loop terminates, since the condition ( another == 'y' ) fails. Note that this loop ensures that statements within it are executed at least once even if n is supplied first time itself. Though it is simpler to program such a requirement using a do while loop, the same functionality if required, can also be accomplished using for and while loops as shown below:

/* odd loop using a for loop */ main( ) { char another = 'y' ; int num ; for ( ; another == 'y' ; ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; } } /* odd loop using a while loop */ main( ) { char another = 'y' ; int num ; while ( another == 'y' ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\want to enter another number y/n " ) ; scanf ( " %c", &another ) ; }

} THE BREAK STATEMENT when we want to jump out of a loop instantly, with out waiting to get back to the conditional test then we use the 'break' keyword. when 'break' encountered inside any loop, control automatically passes to the first statement after the loop. a 'break' is usually associated with an 'if'. Example: Write a program to determine whether a number is prime or not. A prime number is one, which is divisible only by 1 or itself. main( ) { int num, i ; printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; i=2; while ( i <= num - 1 ) { if ( num % i == 0 ) { printf ( "Not a prime number" ) ; break ; } i++ ; } if ( i == num ) printf ( "Prime number" ) ; } In this program the moment num % i turns out to be zero, (i.e.num is exactly divisible by i) the message Not a prime number is printed and the control breaks out of the while loop. Why does the program require the if statement after the while loop at all? Well, there are two ways the control could have reached outside the while loop: (a) It jumped out because the number proved to be not a prime .The loop came to an end because the value of i became equal to num. (b) When the loop terminates in the second case, it means that there was no number between 2 to num - 1 that could exactly divide num. That is, num is indeed a prime. If this is true, the program should print out the message Prime number. 'CONTINUE' STATEMENT at the time of making the program when we want to take the control to the beginning of the loop, bypassing the statement inside the loop which has not been executed then the keyword 'continue' allows us to do so. A continue is usually associated with an if. As an example, let's consider the following program. main( ) { int i, j ;

for ( i = 1 ; i <= 2 ; i++ ) { for ( j = 1 ; j <= 2 ; j++ ) { if ( i == j ) continue ; printf ( "\n%d %d\n", i, j ) ; } } } The output of the above program would be... 12 21 CASE CONTROL STRUCTURE C provides a special control statement that allows us to handle the difficult programming and to make a decision from the number of choices. THE "GOTO KEYWORD" In a difficult programming situation it seems so easy to use a goto to take the control where you want. by the following example we can understand the use of goto keyword-: main( ) { int goals ; printf ( "Enter the number of goals scored against India" ) ; scanf ( "%d", &goals ) ; if ( goals <= 5 ) goto sos ; else { printf ( "About time soccer players learnt C\n" ) ; printf ( "and said goodbye! adieu! to soccer" ) ; exit( ) ; /* terminates program execution */ } sos : printf ( "To err is human!" ) }

about the programIf the condition is satisfied the goto statement transfers control to the label sos, causing printf( ) following sos to be executed. The label can be on a separate line or on the same line as the statement following it, as in, sos : printf ( "To err is human!" ) ; Any number of gotos can take the control to the same label.

The exit( ) function is a standard library function which terminates the execution of the program. It is necessary to use this function since we don't want the statement printf ( "To err is human!" ) to get executed after execution of the else block. The only programming situation in favour of using goto is when we want to take the control out of the loop that is contained in several other loops. WHY USE FUNCTION basically there are two reason because of that we use the 'function' 1. Writing functions avoids rewriting the same code over and over. for example- if you have a section of code in a program which calculates the area of triangle. again you want to calculate the area of different triangle then you would not want to write the same code again and again for triangle then you would prefer to jump a "section of code" which calculate the area of the triangle and then jump back to the place where you left off. that section of code is called 'function'. 2. using function it becomes easier to write a program and keep track of what they are doing. If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code into modular functions also makes the program easier to design and understand. PASSING VALUES BETWEEN FUNCTIONS The mechanism used to convey information to the function is the argument. You have unknowingly used the arguments in the printf( ) and scanf( ) functions; the format string and the list of variables used inside the parentheses in these functions are arguments. The arguments are sometimes also called parameters. for example/* Sending and receiving values between functions */ main( ) { int a, b, c, sum ; printf ( "\nEnter any three numbers " ) ; scanf ( "%d %d %d", &a, &b, &c ) ; sum = calsum ( a, b, c ) ; printf ( "\nSum = %d", sum ) ; } calsum ( x, y, z ) int x, y, z ; { int d ; d=x+y+z; return ( d ) ; } And here is the output... Enter any three numbers 10 20 30

In above program, in main( ) we receive the values of a, b and c through the keyboard and then output the sum of a, b and c. However, the calculation of sum is done in a different function called calsum( ). If sum is to be calculated in calsum( ) and values of a, b and c are received in main( ), then we must pass on these values to calsum( ), and once calsum( ) calculates the sum we must return it from calsum( ) back to main( ). here the return statement serves two purposes: (1) On executing the return statement it immediately transfers the control back to the calling program. (2) It returns the value present in the parentheses after return, to the calling program. In the above program the value of sum of three numbers is being returned. SCOPE RULE OF FUNCTION let us take an example to understand the scope rule of the functionmain( ) { int i = 20 ; display ( i ) ; } display ( int j ) { int k = 35 ; printf ( "\n%d", j ) ; printf ( "\n%d", k ) ; } In above program it is necessary to pass the value of the variable i to the function display( ). it will not become automatically available to the function display( ) Because by default the scope of a variable is local to the function in which it is defined. The presence of i is known only to the function main( ) and not to any other function. Similarly, the variable k is local to the function display( ) and hence it is not available to main( ). That is why to make the value of i available to display( ) we have to explicitly pass it to display( ). Likewise, if we want k to be available to main( ) we will have to return it to main( ) using the return statement. In general we can say that the scope of a variable is local to the function in which it is defined. CALLING CONVENTION Calling convention indicates the order in which arguments are passed to a function when a function call is encountered. There are two possibilities here: (a) Arguments might be passed from left to right. (b) Arguments might be passed from right to left. C language follows the second order. Consider the following function call: fun (a, b, c, d ) ; In this call it doesnt matter whether the arguments are passed from left to right or from

right to left. However, in some function call the order of passing arguments becomes an important consideration. For example:

int a = 1 ; printf ( "%d %d %d", a, ++a, a++ ) ; It appears that this printf( ) would output 1 2 3. This however is not the case. Surprisingly, it outputs 3 3 1. This is because Cs calling convention is from right to left. That is, firstly 1 is passed through the expression a++ and then a is incremented to 2. Then result of ++a is passed. That is, a is incremented to 3 and then passed. Finally, latest value of a, i.e. 3, is passed. Thus in right to left order 1, 3, 3 get passed. Once printf( ) collects them it prints them in the order in which we have asked it to get them printed (and not the order in which they were passed). Thus 3 3 1 gets printed. ADVANCE FEATURES OF FUNCTION (a) Function Declaration and Prototypes (b) Calling functions by value or by reference (c) Recursion FUNCTION DECLARATION AND PROTOTYPE Any C function by default returns an int value.More specifically, whenever a call is made to a function, the compiler assumes that this function would return a value of the type int. If we desire that a function should return a value other than an int, then it is necessary to explicitly mention so in the calling function as well as in the called function. Suppose we want to find out square of a number using a function. then the program will be given asmain( ) { float a, b ; printf ( "\nEnter any number " ) ; scanf ( "%f", &a ) ; b = square ( a ) ; printf ( "\nSquare of %f is %f", a, b ) ; } square ( float x ) { float y ; y=x*x; return ( y ) ; } And here are three sample runs of this program... Enter any number 3

Square of Enter any Square of Enter any Square of

3 is 9.000000 number 1.5 1.5 is 2.000000 number 2.5 2.5 is 6.000000

WHAT IS A FUNCTION A function is a self-contained block of statements that perform a coherent task of some kind. for examplemain( ) { message( ) ; printf ( "\nCry, and you stop the monotony!" ) ; } message( ) { printf ( "\nSmile, and the world smiles with you..." ) ; } The output will be-- Smile, and the world smiles with you... Cry, and you stop the monotony! In the above program the main() itself is a function. through the main we are calling the function message().that mean the control passes to the function message(). when the message() function runs out of statement to execute, the control returns to the main().thus main() becomes the "calling function" where as the message() becomes the "called function". some important points in the the C for functions are given below Any C program contains at least one function. If a program contains only one function, it must be main( ). If a C program contains more than one function, then one (and only one) of these functions must be main( ), because program execution always begins with main( ). There is no limit on the number of functions that might be present in a C program. Each function in a program is called in the sequence specified by the function calls in main( ). After each function has done its thing, control returns to main( ).When main( ) runs out of function calls, the program ends. thus we can say that - a C program is a collection of one or more function. - a function gets called when the function name is followed by a semicolon. for example-main( ) { argentina( ) ; }

A function is defined when function name is followed by a pair of braces in which one or more statements may be present. For example-argentina( ) { statement 1 ; statement 2 ; statement 3 ; } - Any function can be called from any other function. Even main( ) can be called from other functions. For example-main( ) { message( ) ; } message( ) { printf ( "\nCan't imagine life without C" ) ; main( ) ; } A function can be called any number of times. For example--

main( ) { message( ) ; message( ) ; } message( ) { printf ( "\nJewel Thief!!" ) ; }

Types of functions: There are basically two types of function1. library function (printf(), scanf()) 2. user defined function (brazil(), usa()) We can also describe the category of the function under it's type A function may belong to any one of the following categories: 1. 2. 3. Functions with no arguments and no return values. Functions with arguments and no return values. Functions with arguments and return values.

4. 5.

Functions that return multiple values. Functions with no arguments and return values.

#include<stdio.h> #include<conio.h> void add(int x,int y) { int result; result = x+y; printf("Sum of %d and %d is %d.\n\n",x,y,result); } void main() { clrscr(); add(10,15); add(55,64); add(168,325); getch(); } Library functions are nothing but commonly required functions grouped together and stored in what is called a Library.

CALL BY VALUE AND CALL BY REFERENCE whenever we called a function and passed something to it we have always passed the values of variables to the called function. Such function calls are called calls by value. By this what we mean is, on calling a function we are passing values of variables to it. The examples of call by value are shown below: sum = calsum ( a, b, c ) ; f = factr ( a ) ; another example of call by valuemain( ) { int a = 10, b = 20 ; swapv ( a, b ) ; printf ( "\na = %d b = %d", a, b ) ; } swapv ( int x, int y ) { int t ; t=x; x=y;

y=t; printf ( "\nx = %d y = %d", x, y ) ; } The output of the above program would be: x = 20 y = 10 a = 10 b = 20 Note that values of a and b remain unchanged even after exchanging the values of x and y. We have also learnt that variables are stored somewhere in memory. So instead of passing the value of a variable, we can pass the location number (also called address) of the variable to a function. so it would become a call by reference. What purpose a call by reference serves we would find out a little later. First we must equip ourselves with knowledge of how to make a call by reference. This feature of C functions needs at least an elementary knowledge of a concept called pointers. POINTER Generally a pointer is a variable which keeps the address of another variable. pointer points to a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location. through the pointer we can change the contents of memory locations.

POINTER DECLARATION A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type * variable name Example: int *ptr; float *string; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260. another declaration to the pointer is given belowint*alpha;

char*ch; float*s; here above alpha,ch and s are declared as the pointer variable and trually these three can hold the address of next variable according to above declaration. so we can say that pointers are variables that contain addresses, and since addresses are always whole numbers, pointers would always contain whole numbers /* A program to illustrate pointer declaration*/ main() { int *ptr; int multiplication; multiplication=20; ptr=* printf (\n Sum is %d\n, sum); printf (\n The sum pointer is %d, ptr); } we will get the same result by assigning the address of num to a regular(non pointer) variable. The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we are not interested in the value 21260 but in the value stored in that memory location. While the value of pointer is 21260 the value of sum is 45 however we can assign a value to the pointer * ptr as in *ptr=45. This means place the value 45 in the memory address pointer by the variable ptr. Since the pointer contains the address 21260 the value 45 is placed in that memory location. And since this is the location of the variable num the value also becomes 45. this shows how we can change the value of pointer directly using a pointer and the indirection pointer. /* Program to display the contents of the variable their address using pointer variable*/ include< stdio.h > { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch=a; intptr=&x; cptr=&ch; floptr=&x; printf(Num %d stored at address %u\n,*intptr,intptr); printf(Value %f stored at address %u\n,*floptr,floptr); printf(Character %c stored at address %u\n,*cptr,cptr); } POINTER EXPRESSION AND POINTER ARITHMETIC Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. y=*p1**p2;

sum=sum+*p1; z= 5* - *p2/p1; *p2= *p2 + 10; C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc., we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed. /*Program to illustrate the pointer expression and pointer arithmetic*/ #include< stdio.h > main() { int ptr1,ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 6; y=6*- *ptr1/ *ptr2 +30; printf(\nAddress of a +%u,ptr1); printf(\nAddress of b %u,ptr2); printf(\na=%d, b=%d,a,b); printf(\nx=%d,y=%d,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(\na=%d, b=%d,a,b); } Some other points related to function are given below(a) If we want that the value of an actual argument should not get changed in the function being called, pass the actual argument by value. (b) If we want that the value of an actual argument should get changed in the function being called, pass the actual argument by reference. (c) If a function is to be made to return more than one value at a time then return these values indirectly by using a call by reference. RECURSIONA function is called recursive if a statement within the body of a function calls the same function. Sometimes called circular definition, recursion is thus the process of defining something in terms of itself. example of recursion--

/*factorial of a number*/ main( ) { int a, fact ;

printf ( "\nEnter any number " ) ; scanf ( "%d", &a ) ; fact = rec ( a ) ; printf ( "Factorial value = %d", fact ) ; } rec ( int x ) { int f ; if ( x == 1 ) return ( 1 ) ; else f = x * rec ( x - 1 ) ; return ( f ) ; } And here is the output for four runs of the program Enter any number 1 Factorial value = 1 Enter any number 2 Factorial value = 2 Enter any number 3 Factorial value = 6 Enter any number 5 Factorial value = 120

explanation of the programIn the first run when the number entered through scanf( ) is 1, let us see what action does rec( ) take. The value of a (i.e. 1) is copied into x. Since x turns out to be 1 the condition if ( x == 1 ) is satisfied and hence 1 (which indeed is the value of 1 factorial) is returned through the return statement. When the number entered through scanf( ) is 2, the ( x == 1 ) test fails, so we reach the statement, f = x * rec ( x - 1 ) ; And here is where we meet recursion. How do we handle the expression x * rec ( x - 1 )? We multiply x by rec ( x 1 ). Since the current value of x is 2, it is same as saying that we must calculate the value (2 * rec ( 1 )). We know that the value returned by rec ( 1 ) is 1, so the expression reduces to (2 * 1), or simply 2. Thus the statement, x * rec ( x - 1 ) ; evaluates to 2, which is stored in the variable f, and is returned to main( ), where it is duly printed as Factorial value = 2 RECURSION AND STACK There are different ways in which data can be organized. For example, if you are to store five numbers then we can store them in five different variables, an array, a linked list, a binary tree, etc. All these different ways of organizing the data are known as data structures. The compiler uses one such data structure called stack for implementing normal as well as recursive function calls.

A stack is a Last In First Out (LIFO) data structure. This means that the last item to get stored on the stack (often called Push operation) is the first one to get out of it (often called as Pop operation). for examplemain( ) { int a = 5, b = 2, c ; c = add ( a, b ) ; printf ( "sum = %d", c ) ; } add ( int i, int j ) { int sum ; sum = i + j ; return sum ; } In this program before transferring the execution control to the function fun( ) the values of parameters a and b are pushed onto the stack. Following this the address of the statement printf( ) is pushed on the stack and the control is transferred to fun( ). It is necessary to push this address on the stack. In fun( ) the values of a and b that were pushed on the stack are referred as i and j. In fun( ) the local variable sum gets pushed on the stack. When value of sum is returned sum is popped up from the stack. Next the address of the statement where the control should be returned is popped up from the stack. Using this address the control returns to the printf( ) statement in main( ). Before execution of printf( ) begins the two integers that were earlier pushed on the stack arenow popped off.

ADDING FUNCTION TO THE LIBRARYWe can add user-defined functions to the library. It makes sense in doing so as the functions that are to be added to the library are first compiled and then added. When we use these functions (by calling them) we save on their compilation time as they are available in the library in the compiled form. compilers provide a utility called tlib.exe (Turbo Librarian). Let us use this utility to add a function factorial( ) to the library. Given below are the steps to do so: (a) Write the function definition of factorial( ) in some file, say fact.c. int factorial ( int num ) { int i, f = 1 ; for ( i = 1 ; i <= num ; i++ ) f=f*i; return ( f ) ;

} (b) Compile the fact.c file using Alt F9. A new file called fact.obj would get created containing the compiled code in machine language. (c) Add the function to the library by issuing the command C:\>tlib math.lib + c:\fact.obj Here, math.lib is a library filename, + is a switch, which means we want to add new function to library and c:\fact.obj is the path of the .obj file. (d) Declare the prototype of the factorial( ) function in the header file, say fact.h. This file should be included while calling the function. (e) To use the function present inside the library, create a program as shown below:

#include "c:\\fact.h"

main( )

int f ;

f = factorial ( 5 ) ;

printf ( "%d", f ) ;

} (f) Compile and execute the program using Ctrl F9. STORAGE CLASS IN C From C compilers point of view, a variable name identifies some physical location within the computer where the string of bits representing the variables value is stored. There are basically two kinds of locations in a computer where such a value may be kept Memory and CPU registers. It is the variables storage class that determines in which of these two locations the value is stored. Moreover, a variables storage class tells us: (a) Where the variable would be stored. (b) What will be the initial value of the variable, if initial value is not specifically assigned.(i.e. the default initial value). (c) What is the scope of the variable; i.e. in which functions the value of the variable would be available. (d) What is the life of the variable; i.e. how long would the variable exist. There are four storage classes in C: (a) Automatic storage class (b) Register storage class (c) Static storage class (d) External storage class AUTOMATIC STORAGE CLASS The features of a variable defined to have an automatic storage class are as under: Storage Memory. Default initial value An unpredictable value, which is often called a garbage value. Scope Local to the block in which the variable is defined. Life Till the control remains within the block in which the variable is defined. Following program shows how an automatic storage class variable is declared, and the fact that if the variable is not initialized it contains a garbage value. main( ) { auto int i, j ; printf ( "\n%d %d", i, j ) ; }

The output of the above program could be... 1211 221 where, 1211 and 221 are garbage values of i and j. When you run this program you may get different values, since garbage values are unpredictable. So always make it a point that you initialize the automatic variables properly, otherwise you are likely to get unexpected results. Note that the keyword for this storage class is auto, and not automatic.

REGISTER STORAGE CLASS The features of a variable defined to be of register storage class are as under: Storage - CPU registers. Default initial value - Garbage value. Scope - Local to the block in which the variable is defined. Life - Till the control remains within the block in which the variable is defined. STATIC STORAGE CLASS The features of a variable defined to have a static storage class are as under: Storage Memory. Default initial value Zero. Scope Local to the block in which the variable is defined. Life Value of the variable persists between different function calls. EXTERNAL STORAGE CLASS The features of a variable whose storage class has been defined as external are as follows: Storage Memory. Default initial value Zero. Scope Global. Life As long as the programs execution doesnt come to an end. External variables differ from those we have already discussed in b that their scope is global, not local. External variables are declared outside all functions. for example-

main( ) { printf ( "\ni = %d", i ) ; increment( ) ; increment( ) ; decrement( ) ; decrement( ) ; } increment( ) {

i=i+1; printf ( "\non incrementing i = %d", i ) ; } decrement( ) { i=i-1; printf ( "\non decrementing i = %d", i ) ; } The output would be: i=0 on incrementing i = 1 on incrementing i = 2 on decrementing i = 1 on decrementing i = 0 As is obvious from the above output, the value of i is available to the functions increment( ) and decrement( ) since i has been declared outside all functions. C PRE-PROCESSOR It is a program that processes our source program before it is passed to the compiler. FEATURES OF PRE-PROCESSORThe pre-processor offers several features called pre-processor directives. Each of these preprocessor directives begin with a # symbol. The directives can be placed anywhere in a program but are most often placed at the beginning of a program, before the first function definition. We would learn the following pre-processor directives here: (a) Macro expansion (b) File inclusion (c) Conditional Compilation (d) Miscellaneous directives MACRO EXPANSION Have a look at the following program. #define UPPER 25 main( ) { int i ; for ( i = 1 ; i <= UPPER ; i++ ) printf ( "\n%d", i ) ; }

In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has already been defined before main( ) through the statement,#define UPPER 25 This statement is called macro definition or more commonly, just a macro. What purpose does it serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program with 25. When we compile the program, before the source code passes to the compiler it is examined by the C preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program in search of the macro templates; wherever it finds one, it replaces the macro template with the appropriate macro expansion. In C programming it is customary to use capital letters for macro template. This makes it easy for programmers to pick out all the macro templates when reading through the program. Note that a macro template and its macro expansion are separated by blanks or tabs. A space between # and define is optional. Remember that a macro definition is never to be terminated by a semicolon. MACROS WITH ARGUMENTThe macros that we have used so far are called simple macros. Macros can have arguments, just as functions can. Here is an example that illustrates this fact.

#define Area) ( 3.14 * x * x ) main( ) { float r1 = 6.25, r2 = 2.5, a ; a = AREA ( r1 ) ; printf ( "\area of circle = %f", a ) ; a = AREA ( r2 ) ; printf ( "\area of circle = %f", a ) ; } Heres the output of the program... Area of circle = 122.656250 Area of circle = 19.625000 In this program wherever the pre-processor finds the phrase Area) it expands it into the statement ( 3.14 * x * x ). However, thats not all that it does. The x in the macro template Area) is an argument that matches the x in the macro expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the statement AREA(r1) is equivalent to: ( 3.14 * r1 * r1 ) After the above source code has passed through the pre-processor, what the compiler gets to work on will be this:

main( ) { float r1 = 6.25, r2 = 2.5, a ; a = 3.14 * r1 *r1 ;

printf ( "Area of circle = %f\n", a ) ; a = 3.14 *r2 * r2 ; printf ( "Area of circle = %f", a ) ; } Here is another example of macros with arguments: #define ISDIGIT(y) ( y >= 48 && y <= 57 ) main( ) { char ch ; printf ( "Enter any digit " ) ; scanf ( "%c", &ch ) ; if ( ISDIGIT ( ch ) ) printf ( "\nYou entered a digit" ) ; else printf ( "\nIllegal input" ) ; }

MACROS VS FUNCTION In a macro call the pre-processor replaces the macro template with its macro expansion, in a stupid, unthinking, literal way. As against this, in a function call the control is passed to a function along with certain arguments, some calculations are performed in the function and a useful value is returned back from the function. Usually macros make the program run faster but increase the program size, whereas functions make the program smaller and compact. If we use a macro hundred times in a program, the macro expansion goes into our source code at hundred different places, thus increasing the program size. On the other hand, if a function is used, then even if it is called from hundred different places in the program, it would take the same amount of space in the program. FILE INCLUSION The second pre-processor directive well explore in this chapter is file inclusion. This directive causes one file to be included in another. The pre-processor command for file inclusion looks like this: #include "filename" If we have a very large program, the code is best divided into several different files, each containing a set of related functions. It is a good programming practice to keep different sections of a large program separate. These files are #included at the beginning of main program file. CONDITIONAL COMPILATION We can, if we want, have the compiler skip over part of a source code by inserting the preprocessing commands #ifdef and #endif, which have the general form:

#ifdef macroname statement 1 ; statement 2 ; statement 3 ; #endif If macroname has been #defined, the block of code will be processed as usual; otherwise not. #IF AND #ELIF DIRECTIVES The #if directive can be used to test whether an expression evaluates to a nonzero value or not. If the result of the expression is nonzero, then subsequent lines upto a #else, #elif or #endif are compiled, otherwise they are skipped. A simple example of #if directive is shown below: main( ) { #if TEST <= 5 statement 1 ; statement 2 ; statement 3 ; #else statement 4 ; statement 5 ; statement 6 ; #endif } If the expression, TEST <= 5 evaluates to true then statements 1, 2 and 3 are compiled otherwise statements 4, 5 and 6 are compiled. In place of the expression TEST <= 5 other expressions like ( LEVEL == HIGH || LEVEL == LOW ) or ADAPTER == CGA can also be used. program using #elif directive can be rewritten as shown below. #if ADAPTER == VGA code for video graphics array #elif ADAPTER == SVGA code for super video graphics array #else code for extended graphics adapter #endif MISCELLANEOUS DIRECTIVES There are two more preprocessor directives available, though they are not very commonly used. They are: (a) #undef (b) #pragma #UNDEF

On some occasions it may be desirable to cause a defined name to become undefined. This can be accomplished by means of the #undef directive. In order to undefine a macro that has been earlier #defined, the directive, #undef macro template can be used. Thus the statement, #undef PENTIUM would cause the definition of PENTIUM to be removed from the system. All subsequent #ifdef PENTIUM statements would evaluate to false. #PRAGMA This directive is another special-purpose directive that you can use to turn on or off certain features. Pragmas vary from one compiler to another. There are certain pragmas available with Microsoft C compiler that deal with formatting source listings and placing comments in the object file generated by the compiler. (a) #pragma startup and #pragma exit: These directives allow us to specify functions that are called upon program startup (before main( )) or program exit (just before the program terminates). Their usage is as follows: void fun1( ) ; void fun2( ) ; #pragma startup fun1 #pragma exit fun2 main( ) { printf ( "\nInside maim" ) ; } void fun1( ) { printf ( "\nInside fun1" ) ; } void fun2( ) { printf ( "\nInside fun2" ) ; } And here is the output of the program. Inside fun1 Inside main Inside fun2 Note that the functions fun1( ) and fun2( ) should neither receive nor return any value. If we want two functions to get executed at startup then their pragmas should be defined in the reverse order in which you want to get them called. (b) #pragma warn: This directive tells the compiler whether or not we want to suppress a specific warning. Usage of this pragma is shown below. #pragma warn rvl /* return value */ #pragma warn par /* parameter not used */ #pragma warn rch /* unreachable code */

int f1( ) { int a = 5 ; } void f2 ( int x ) { printf ( "\nInside f2" ) ; } int f3( ) { int x = 6 ; return x ; x++ ; } void main( ) { f1( ) ; f2 ( 7 ) ; f3( ) ; } If you go through the program you can notice three problems immediately. These are: (a) Though promised, f1( ) doesnt return a value. (b) The parameter x that is passed to f2( ) is not being used anywhere in f2( ). (c) The control can never reach x++ in f3( ). If we compile the program we should expect warnings indicating the above problems.

You might also like