Sei sulla pagina 1di 15

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI

*** C-FUNDAMENTALS ***


Introduction: - C is programming language developed at AT & Ts Bell Laboratories of U.S.A. in 1970.
It was designed & written by Dennis Ritchie. C can be called as the middle level language because of its compatibility with the high-level language programming as well as the low-level language programming. C provides various statements, which can be flexibly used to the program to get the result of anything. It provides various utilities such as Arrays, Function, Pointers etc. It also provides the facility of the files, which can stores no of records together & these records can be easily retrieved, updated or stored. In the advanced C we have the concept of data structure by which we can manipulate the records as per conveyance. C also provides the graphics utility by which we can design the objects using different statements than that of the statements normally used in the program.

Advantages of C-Language: 1] C is highly portable i.e. C program written for one computer can be run on another computer with little or no modification. 2] C has a rich set of operators & built in functions. 3] Programs written in C are efficient & fast due to its variety of data types & powerful operators. 4] C has only 32 Keywords. 5] C is highly structured language i.e. each C program is a logical collection of one or more functions or modules. 6] C is extensible i.e. we can continuously add our own functions to the C library.

General Format of C-programming: #include <stdio.h> #include <conio.h> main( ) { variable declaration; input; process; output; } Example: - /* Sample C program showing addition of two numbers */ #include <stdio.h> /* Header files */ #include <conio.h> main( ) /* Compiler read the program from the main( ) function */ { /* Open body of main( ) function */ int a, b, sum; /* Variable declaration along with data_type */ clrscr( ); /* Function used to clear the previous screen */ printf(Enter any two numbers a & b: ); /* print the message on the screen */ scanf(%d%d,&a, &b); /* Received the values of variable from the keyboard */ sum = a + b; /* Process */ printf(Sum of two numbers %d & %d is = %d,a,b,sum); /* output */ getch( ); /* get the character on the screen */ return; /* return the control to the main( ) function */ } /* Closed body of main( ) Function */ Explanation: 1] Header File: A header file is an ASCII type of file, which is available in the include directory. The required header file can be placed in a program by #include statement, which instruct the compiler to place the contents of the specified file in a program. e.g. #include <stdio.h> inform the compiler to linked the contents of the header file stdio.h from the library which contain the declaration for standard input & output functions. 2] Every C program start with main function. 3] The body of the program must be enclosed within the pair of braces { }. 4] The first step will be declaration of variables, which we are using in a program. 5] All statements must be terminated with semicolon ; 6] All keywords are in lowercase. 7] Comment about the program should be enclosed within /* */.

Compiler & Interpreters: - A Compiler is a computer program that read a program & translates it into object
code. An interpreter is similar to that of compiler but it read a statement in a program once at a time & translates it into machine code.

Running a Program: - After entering a program, compile it using the compile option or Alt+F9. If there are few
errors in the program the message alongwith the line numbers will be displayed is a separate message window. Correct it & save the program using . C extension. Then execute the program by using run option or Ctrl+F9.

-1-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI

Data Types in C: The five basic data types in C are as follows:


Data_type Character Character string Integer Float Double Meaning Single Alphabet Set of Alphabet Whole numbers decimal values[6] decimal values[15] Keyword used char char int float double Bytes Used 1 Unspecified 2 4 8 Conversion Specification %c %s %d %f %lf Range Minimum Maximum -128 -32,768 3.4 x 10-38 1.7x 10-308 +128 +32,767 3.4 x 10+38 1.7x10+308

Modifiers: - C provides the Modifiers: signed, unsigned, long & short which are generally used with data_types to
increase the range of values. 1] signed Modifier: - It is used to store the values in positive to negative range. By default all of the data_type are signed type. Therefore the declaration: int a; signed int a; Both will stored the values in the range of 32768 to + 32767. 2] unsigned Modifier: - It can store only the positive values, which are twice large as an ordinary integer. There the declaration: unsigned int a; will stored the values in the range 0 to 65535. 3] long Modifier: - This modifier can be applied to int & double data_type to increase the range of values. The declaration: long int a; will stored the values in the range 2,147,483,648 to +2,147,483,647. 4] short Modifier: - It is used to modify the memory requirement of different data_type. The memory requirement is not the same for all computers. Ex: The declaration int a; required two bytes in IBM PCs & four bytes in Macintosh & VAX. So the declaration short int a; & int a having same required i.e. of two bytes in IBM PCs. And the declaration int a; Will required four bytes & short int a; will required two byes for Macintosh PCs.

Data Types in C with Modifiers:


Data_type Char Unsigned char Int Unsigned int long int Unsigned long int Float Double long double Minimum -128 0 -32767 0 -2,147,483,648 0 3.4 x 10-38 1.7 x 10-308 3.4 x 10-4932 Range Maximum +128 255 +32768 65,535 +2,147,483,647 4,294,967,295 3.4 x 10+38 1.7 x 10+308 1.1 x 10+4932 Number of bytes used 1 1 2 2 4 4 4 8 10 Conv. Specification %c %c %d %u %ld %ud %f %lf %Lf

Variables Declaration:
Variables are the symbolic name for a memory location, in which a value of the variable is stored. The general format for variable declaration is: Data_type Variable_Name; [Ex: int age;] While declaring the more variables in one statement then it must be separated by comma operator. [int age,height;] We can also assign the values to the variables at the time of declaration. Data_type Variable_Name = Constant; [Ex. int age = 35;]

Keywords: C Provides 32 keywords which are all in lower-case.


Auto Long Switch Volatile double int struct break goto Return sizeof union else case const default enum if Short static unsigned float char continue do extern register Signed typedef void for while Constant: if we assign the values to the variables at the time of declaration then this value will be constant through out the program. In C the following types of constant may be declared. 1] Integer Constant: Assigning without decimal places numbers to the variable is called as integer constant. 2] Real Constant: Assigning numbers containing fractional parts are called as real constant. 3] Single Character Constant: While assigning a single character, it must be enclosed within a pair of single quote. i.e. A, 45. 4] String Constant: While assigning a string, it must be enclosed within a pair of double quote. i.e. PRAVIN. Operators in C: C has a very rich collection of operators, which are used to perform mathematical & logical operations. 1] Arithmetic Operators: C provides five basic Arithmetic Operators. Operator Meaning + Addition Subtraction * Multiplication / Division % Remainder

-2-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI 2] Relational Operator: C has six relational operators which are used to test the relationship between two variables. Operator Meaning < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to != Not equal to 3] Logical Operators: C has three logical operators which are used to checkout the condition based on multiple variables. Operator Meaning && Logical And || Logical OR ! Logical Not 4] Assignment Operators: These operators are used to assign the result of an expression to a variable. Simple assignment Operator Shorthand Operator a=a+1 a+=1 a=a1 a -=1 a = a * (m+1) a *=m+1 a = a / (m+1) a /=m+1 a=a%b a %=b 5] Increment & decrement operators: Increment & Decrement operators in C are ++ and respectively which one generally uses in for & while loop to increase or decrease the initial value of the variable. It takes the following form: m ++ => m = m + 1 => m + = 1; m -- => m = m 1 => m - = 1;

Standard input/output Statements in C:


1] scanf( ) Function: The standard library function scanf( ) is used to received the values of the variables from the keyboard. The general format for using the scan( ) function is: scanf(Conversion Specification,&List of Variables); where & is an address of operator used to stored the value of the variable at the proper address in memory. 2] printf( ) Function: The standard library function printf( ) is used to display the store values in the variables on the screen. The general format for using the printf( ) function is: printf(Conversion Specification,List of Variables); /* Used to print the values stored in the variable */ printf(Statement); /* Used to print the message only */ Example: /* Calculation of Simple interest */ #include<stdio.h> #include<conio.h> main( ) { int time; float prin_amount, rate, si; clrscr( ); printf(Enter Principle, Rate of Interest & Time\n); scanf(%f%f%d,&prim_amount,&rate,&time); si = prin_amount * rate * time/100.0; printf(Principle Amount = Rs.%.2f\n,prin_amount); printf(Rate of Interest = Rs.%.2f\n,rate); printf(Duration = Yrs%d\n,time); printf(Simple Interest = Rs.%.2f\n,si); getch( ); return; }

Control Flow Statements in C:


C has the following control flow statements which are also be called as Decision making Statements. 1] The if statement: It is used to control the flow of execution of statements which having the general format: if(test_expression) { statement_block; } statement - x; If the condition satisfied the statement_block will be executed otherwise the statement_block will be skipped and the control will passed to the x-statement. Example: /* Calculation of Total Expences using if statement */ #include<stdio.h> main( )

-3-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI { int quantity, discount = 0; float rate, dis_amount, net_amount, tot_amount; clrscr( ); printf(Enter Total Quantity Purchase: ); scanf(%d,&quantity); printf(Enter Rate Per Quantity : ); scanf(%f,&rate); net_amount = rate * quantity; printf( Total Quantity Purchase = %d\n, quantity); printf( Rate Per Quantity = Rs.%.2f\n, rate); printf( Net Amount = Rs.%.2f\n, net_amount); if(net_amount >= 2500) { dis = 10; dis_amount = net_amount * dis/100.0; tot_amount = net_amount dis_amount; printf(Discount Amount [10 Percent] = Rs.%.2f\n, dis_amount); printf(Total Amount to be paid = Rs.%.2f\n, tot_amount); } printf(Thank You); getch( ); return; } 2] The if-else Statement: It is used to check out the condition based on either a single variable or multiple variables. The general format is: if(test_expression) { true_statements block; } else { false_statement block; } statement x; If the condition is satisfied then the true_statement block will be execute otherwise the false_statement block will be execute and in both the cases control will be transferred to the x-statement. Example: #include<stdio.h> main( ) { char name[20]; int age; clrscr( ); printf(Enter the Name: ); scanf(%s,&name); printf(Enter Age : ); scanf(%d,&age); printf(Name : %s\n , name); printf(Age : %d\n ,age); if(age >= 18) { printf(Eligible for Driving License \n); } else { printf( Not Eligible for Driving License); } printf(Try at the age of 18); getch( ); return; } 3] Nested if-else statement: When an if-statement itself contains another if-statement is known as nested if-else statement. The general format is: if(test_condition 1) { statement 1; } else if(test_condition 2)

-4-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI { statement 2; } else if(test_condition 3) { statement 3; } ------------------------------------else { statement x; } Example: /* Program to check the person is eligible for marriage or not */ #define <stdio.h> main( ) { char sex; int age; clrscr( ); printf(Enter the Age of Person : ); scanf(%d,&age); printf(Enter the Sex of Person : ); fflush(stdin); scanf(%s,&sex); if(sex == M || sex == m && age >=21) { printf(Person is Eligible for Marriage\n); } else if(sex == F || sex == f && age >= 18) { printf(Person is Eligible for Marriage\n); } else { printf(Person is Not Eligible for Marriage\n); } getch( ); return; } 4] The Switch Statement: It is used to execute the statement from the number of choices by passing the parameter through switch statement later it will be compared with the case statement & the related case statement will be execute. The general format of Switch Statement is: switch( choice ) or ( integer expression) { case 1: Statement 1; [Note: Colon to case & default Statement.] break; case 2: Statement 2; break; ------------------------------------------------case n: Statement n; break; default: Statement; } The break statement at the end of each statement used to immediate exit from the switch statement. The default statement will be executed if the choice does not match with the case statements. Example: /* Showing the use of Switch statement */ #define <stdio.h> main( ) { int choice; clrscr( ); printf(Who was the First P.M. of India?\n); printf(Your Choices are:\n);

-5-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI printf(\n1. Mahatma Gandhi\n2. Sardar Patel\n3. Dr.Ambedkar\n4. Jawaharlal Nehru\n); printf(Enter your Choice: ); scanf( %d, &choice); switch(choice) { case 1: printf(Wof ! Aapaka Jawab Galat Hai); break; case 2: printf(Wof ! Aapaka Jawab Galat Hai); break; case 3: printf(Wof ! Aapaka Jawab Galat Hai); break; case 4: printf(Yeh Hui na baat); break; default: printf(Sorry ! Aapaki Sabhi Life Line Chali Gai Hai); } /* End of switch Statement */ getch( ); return; } /* End of Main( ) function */

Decision Making & Looping Statements in C:


C provides three loop statements, which are generally used to execute the statement-specified number of times. 1] The for Statement: It is a continuous looping structure use to execute the statements no of times till the condition is not get satisfied. The general format is: for ( initialization; test_condition; increment ) { Statements; } Example: /* Program to print the number from 1 to 10 */ #define <stdio.h> main( ) { int num; clrscr( ); for ( num = 1; num <= 10 ; num++) { printf (%3d,num); } getch( ); return; } 2] The While Statement: While loop is similar to that of for loop but the difference is that it is separately initialized the variable as well as the condition & the step value. The general format is: initialization; while(test_condition) { Statements; Increment; } Example: /* Program to print the number from 1 to 10 using while loop */ #include <stdio.h> main( ) { int num; clrscr( ); num = 1; while(num <= 10) { printf(%3d,num); num + +; } getch( ); return; } 3] The do-while loop: We know that while loop tests the condition before executing the body of the loop whereas do-while tests the condition after executing the body of the loop. The general format is: initialization; do { statements; increment; }

-6-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI while(test_condition); Example: /* Program to print the number from 1 to 10 using do-while loop */ #include <stdio.h> main( ) { int num; clrscr( ); num = 1; do { printf(%3d,num); num + +; } while(num <= 10); getch( ); return; } 4] The Odd loop: It is used to execute the statements in the loop finite no of times. Example: /* Program showing the use of Odd Loop */ #include <stdio.h> main( ) { char choice = y; int num, square; while( choice == y || choice == Y) { printf(Enter a Number: ); scanf(%d,&num); square = num * num; printf(Square of %d is %d\n, num, square); printf(Do you want to Continue[Y/N]: ); scanf(%c,&choice); } getch( ); return; }

Breaking Control Statements in C:


These statements are generally used in loop statements to jump from one statement to another as well as to jump out of the loop. 1] break statement: It is used to immediately exit from the loop statements & then it continue the statement immediately following the loop. The general format is: break; 2] continue statement: It is used to skip the error statement & then pass the flow of control to the next statement in loop statements. Example: /* Program showing the use of break & continue statements */ #include <stdio.h> main( ) { int number, square, count; clrscr( ); printf(Enter 101 to Stop\n); count = 0; while(count <=100) { printf(Enter the Number less than or equal to 100: ); scanf(%d,&number); if(number == 101) { break; } if( number < 0) { printf(Number is Negative\n); } square = number * number; printf(Number = %d\nSquare = %d\n,number, square); count + +; }

-7-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI printf(Number of items Done = %d\n,count); getch( ); return; } ***** FUNCTIONS IN C ***** Introduction: If a large program is divided into functional parts then each part may be independently coded & later combined into a single unit. These subprograms are called as Functions. Thus a Function is a self-contained program used to break the large programs into smaller parts so that the program will become easy to understand & modify. C functions are of two types: 1] Library Functions: These functions have already been defined in standard library header file to provide prototype declaration. So that we can use them in a program without writing a definition for it. The required function can be use in a program by #include statement, which instruct the compiler to link the specified functions from the library. Example: /* Program to calculate square root of a number using sqrt( ) function from the math library */ #include < stdio.h > #include < math.h > main( ) { int num, s; clrscr( ); printf(Enter the Number\n); scanf(%d,&num); s = sqrt( num ); printf(Number = %d : Square Root = %d\n, num, s); getch( ); return; } 2] User Defined Functions: The functions developed by the programmer at the time of writing a program are called as User Defined Functions. These functions can also be kept in some libraries for future use in different programs. Declaring the function [Calling Function]: The user-defined function must be declared before we use them in a program. This declaration of the function in a main program is known as the calling function. The general format for function declaration is: Data_type function_name(data_type argument 1, data_type argument 2, --------- ) Example: void sum( ); The data_type of the function is used to return the type of the value by the called function to the calling portion of the program. If we have not specified the data_type to return a value then by default the called function will return the integer value. If we do not have to return any value to the calling portion of the program then declared the data_type as void. The function name is the user-defined name, which follows the same rule of variable names. Defining a function [Called Function]: The general format for called function definition is: Data_type function_name(data_type argument 1, data_type argument 2, ------------ ) { body of the function; ----------------------return( something to the calling function); } The Function, which called the another function, is known as calling function & the function, which is called, is known as called function. The semicolon terminates the calling function because it behaves like a statement whereas the called function is not terminated with semicolon. Actual argument: The variables present in a function declaration are called as Actual Arguments. Formal argument: The variables present in a function definition are called as Formal Argument or Parameters. When the function is invoked the formal parameters are replaced by the actual arguments. Actual arguments & Formal arguments may have the different names but the data_type should be same in both the blocks. Note: Each argument must be independently declared with data_type & name & must be separated by commas. Example: /* Program showing the use of function */ #include<stdio.h> main( ) { int a, b, c; clrscr( ); printf(Enter the Values of a & b\n); scanf(%d%d, &a, &b); c = sum(a ,b); /* Function declaration containing Actual Arguments [ Calling Function ] */ printf(Addition of a and b is = %d\n, c); } add(x ,y) /* Called Function with formal Arguments */

-8-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI int d, x, y; { d = x + y; return( d ); } [ Note: The Actual Arguments pass the values to the formal argument in a called function ] Passing the Arguments: In general, Functions communicate with each other by passing arguments. These arguments can be passed in two different ways. 1] Call by Value: In C by default all function arguments are passed by value. When the calling function invokes it pass the control to the called function where formal arguments are replaced by the actual argument. When the control is transferred back from the called function to the calling portion of the program the actual values are not transferred back. This type of passing formal arguments to a function is known as call by value. Example: /* Program showing passing arguments to a function call by value */ #include <stdio.h > main( ) { int a, b, c; clrscr( ); printf(Enter the Values of a & b\n); scanf(%d%d,&a, &b); c = add(a,b); printf(In main( ) Function\n); printf(Value of a = %d : Value of b = %d\n, a, b); printf(Sum = %d\n,c); getch( ); return; } add(int a, int b) { int c; c = a + b; a = a * a; b = b + 10; printf(In add( ) Function\n); printf(Value of a = %d : Value of b = %d\n, a, b); printf(Sum = %d\n,c); return( c ); } 2] Call by Reference: The process of calling a function using pointers to pass the address of the variables is known as call by reference. The function, which is called by reference, can change the value of the variable used in the called function. Example: /* Program showing the use of pointer to exchange the values stored in two locations in memory */ #include <stdio.h> main( ) { int a = 200, b = 100; clrscr( ); printf(Before Exchange\n); printf(Value of a = %d : Value of b = %d\n, a, b); swap(&a, &b); /* Call by Reference */ printf(After Exchange\n); printf(Value of a = %d : Value of b = %d\n, a, b); getch( ); return; } swap(int *a, int *b) { int temp; temp = *a; /* Assign the value at address a to temp */ *a = *b; /* Put value of b in to a */ *b = temp; /* Put Value of temp in to b */ }

Types of Functions:- User Defined functions may be classified in to three ways as follows:
Type 1: Functions with no Arguments & no return Values. When a function has no arguments it will not receive any data from the calling function. Similarly when it will not return any value, the calling function will not receive any data from the called function. It means there is no data communication between the calling portion of the program & a called function block. Example: /* Program showing there is no data communication between the calling function & a called function */ Void main( ) { clrscr( );

-9-

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI printline( ); /* Calling Functions */ program( ); printline( ); getch( ); } printline( ) /* Called function Contains no argument */ { int i; for(i = 1 ; i <= 25 ; i++) { printf(=*=); } printf(\n); return; } program( ) /* Called function Contains no argument */ { int rate,time; float principle, simple_interest; printf(Enter Principle, Rate, Time\n); scanf(%f%d%d,&principle,&rate,&time); simple_interest = principle * rate * time; printf(Principle Amount = Rs. %.2f\n,principle); printf(Rate of Interest = Rs. %d\n,rate); printf(Time = Yrs.%d\n,time); printf(Simple Interest = Rs. %.2f\n,simple_interest); return; } Type 2: Functions with Arguments & no return Values. In this case, the calling function passes the values of the actual arguments to the formal argument in the called function but the function does not return back any value to the calling function. It means that, there is one way data communication between the calling portion of the program & a called function block. Example: /* Program showing the one way data communication between the calling function & a called function */ Void main( ) { int rate,time; float principle; clrscr( ); printf(Enter Principle, Rate, Time\n); scanf(%f%d%d,&principle,&rate,&time); printline(Z ); /* Calling Functions */ program( principle,rate,time); printline(O ); getch( ); } printline(ch) /* Called function Contains no argument */ char ch; { int i; for(i = 1 ; i <= 45 ; i++) { printf(%c,ch); } printf(\n); return; } program(float p, int r, int t ) /* Called function Contains no argument */ { float simple_interest; simple_interest = principle * rate * time; printf(Principle Amount = Rs. %.2f\n,p); printf(Rate of Interest = Rs. %d\n,r); printf(Time = Yrs.%d\n,t); printf(Simple Interest = Rs. %.2f\n,simple_interest); return; } Type 3: Functions with Arguments & return Values. In this case, the calling function passes the values of the actual arguments to the formal argument in the called function and the calculated value, if any is transfer back to the calling function. It means that, there is a two-way data communication between the calling portion of the program & a called function block. Example: /* Program showing the Two-way data communication between the calling function & a called function */ void main( ) { int rate,time;

- 10 -

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI float principle, simple_interest;; clrscr( ); printf(Enter Principle, Rate, Time\n); scanf(%f%d%d,&principle,&rate,&time); printline(*,35); /* Calling Functions */ simple_interest = program( principle,rate,time); printf(Principle Amount = Rs. %.2f\n,p); printf(Rate of Interest = Rs. %d\n,r); printf(Time = Yrs.%d\n,t); printf(Simple Interest = Rs. %.2f\n,simple_interest); printline(=,35); getch( ); } printline(char ch, int len) /* Called function Contains no argument */ { int i; for(i = 1 ; i <= len ; i++) { printf(%c,ch); } printf(\n); return; } program(float p, int r, int t ) /* Called function Contains no argument */ { float simple_interest; simple_interest = principle * rate * time; return(simple_interest); /* return simple interest to calling portion */ }

Recursive Function: A function is said to be recursive if a statement in the body of the function calls the function
itself again & again. The normal functions are invoked by the main function, whenever the function name is used and the recursive function is invoked by itself directly or indirectly as long as the given condition is satisfied. These functions must be terminating with exit statement. Example: /* A program to find the factorial of the given number using the recursive function. */ long int fact(long int); /* Local Function Declaration */ Void main( ) { int x, number; printf(Enter the Number\n); scanf(%d,&number); x = fact(number); printf(The number = %d and Factorial = %ld,number,x); } long int fact(long int number) /* Recursive Function */ { int value = 1; if(number == 1) return(value); else { value = number * fact(number 1); return(value); }

Preprocessors in C:
The Preprocessors is the program that processes the source code before it passes through the compiler. All preprocessors directives begins with # sign. It is used to include the contents of a file during compilation in a program. The statement #include <filename> will searched the file in the standard directories where as the statement #include filename will searched the file in the current directories & then in the standard directories. Similarly the statement #define, known as macro definition is used to define constants in a program. The general format to define constant is: #define identifier_string; => Ex: The statement # define PI 3.1416 replace all occurrence of PI with 3.1416 in the program. Example: /* Program to calculate the area, diameter & perimeter of the circle */ #define PI 3.1416 #define P printf main( ) { int radius; float area, diameter, perimeter; P(Enter the radius of the circle\n);

- 11 -

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI scanf(%d,&radius); area = PI * radius * radius; diameter = 2.0 * radius; perimeter = 2.0 * PI * radius; P(Radius of the Circle = %d\n,radius); P(Area of the Circle = %f\n,area); P(Diameter of the Circle = %f\n,diameter); P(Perimeter of the Circle = %f\n,perimeter); } Storage Class Specifiers: Storage classes are used with the data_types to provide information about the visibility, lifetime & location of the variable. C provides four different storage class Specifiers as follows: 1] Automatic Variable: Automatic variables are nothing but the local variables, which allocate temporary memory space. They allocate memory space automatically when the function is invoked & destroyed automatically when the function is exited. The general format is to declare automatic variable: auto data_type variable_name; => auto int x; /*By default the variables declared inside the function without storage_class are automatic variables */ or int x; 2] Register Variable: It is used to access the data much faster than the memory access. So the variables which are repeatedly used can be placed in the machine registers to the faster execution of the program. The general format is to declare register variable: register data_type variable_name; register int count; 3] Static Variable: Static variables are used to assign the constant values to the variables at the time of declaration. So the compiler, automatically assign the initial value zero to the variable which is not initialized. The general format is to declare static variable: static data_type variable_name; static int i = 0; 4] External Variables: The Variables, which are declared outside the main( ) function are called external or global variables. These variables can be accessed by any function in the program & can change its value. The general format to declare external variable is: extern data_type variable_name; extern int x, y; This concept is useful in multiple programs to share the declared variables in one file. If we have declared the global variable int m ; in one file then this variable can be accessed in another file by declaring the gobal variable as extern i.e. extern int m;

ARRAYS:
Definition: We know that the ordinary variables can be hold only one value at a time. But if we want to store more than one value at a time in a single variable then we must use the concept of an Array, which stored the values in the consecutive memory location under one name. Thus Array can be defined as the group of same data elements that share a common variable name, data_type ,storage class & characteristics. Declaration of Arrays: [1] One Dimensional Array:- Before using an array in a program we must provide the following information to the compiler that the type of an array, name of an array, the number of subscripts in the array i.e. the dimension of an array & the number of maximum elements in each subscript. The general format for declaring the Array is: Storage_class Data_type Array_name[size]; Ex: int number[10]; Represents the number as an array can hold maximum of 10 different integer elements. Array can be initialized at the time of declaration using the format: Storage_class Data_type Array_name[size] = {element_1, element_2, ---------------- element_n}; Ex: int number[5] = {4,6,7,8,9}; Reserve five storage locations in memory each of size two bytes & then assign the values to the array elements as follows: number[0] = 4; number[1] = 6; number[2] = 7; number[3] = 8; number[4] = 9; Each dimension of an array is index from 0 to its maximum_size 1. Example: /* Program to calculate Total = Sum of Xi2 Where [i = 1,2,3,-------n]. */ main( ) { int i; float num[10],total = 0.0; clrscr( ); printf(Enter the 10 Real numbers :\n); /* Reading values in to arrays */ for(i = 0; i< 10 ; i + +) { scanf(%f,&num[i] ); } for(i = 0; i< 10 ; i + +) { total = total + num[i] * num[i]; } /* Total Calculation */ for(i = 0; i< 10 ; i + +) /* Print numbers & total */ { printf(num[%2d] = %5.2f\n, i, num[i] ); printf(\nTotal = %.2f\n,total ); getch( );

- 12 -

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI return; } [2] Two Dimensional Array:- It is used to store the data in the form of rows & columns. The general format for declaring the Two dimensional Array is: Storage_class Data_type Array_name[row_size][column_size]; Ex: int number[10][10]; Represents the number as an array having 10 rows & 10 columns can hold maximum of 100 elements. Similar to one-dimensional Array, two-dimensional Array can be initialized at the time of declaration as follows: Ex: int number[3][4] = {{4,6,7,8},{3,6,5,8},{2,9,1,0}}; The values can be assign to the array elements as follows: number[0][0] = 4; number[0][1] = 6; number[0][2] = 7; number[0][3] = 8; number[1][0] = 3; number[1][1] = 6; number[1][2] = 5; number[1][3] = 8; number[2][0] = 2; number[2][1] = 9; number[2][2] = 1; number[2][3] = 0; Example: /* Program to print the elements in the matrix form */ main( ) { int row, col, a[10][10], i, j; clrscr( ); printf(Enter the Order of Matrix\n); scanf(%d%d, &row, &col); printf(Enter the elements of Matrix\n); for( i = 0; i < row; i + + ) { for( j = 0; j < col; j + + ) { scanf(%d,&a[i][j] ); } } printf(\nThe Matrix is of Order %d X %d is:\n,row,col); for( i = 0; i < row; i + + ) { for( j = 0; j < col; j + + ) { printf(%3d,a[i][j] ); } printf(\n); } getch( ); return; }

Functions with Arrays:


Similar to simple variables array elements can be passed to a function by calling the function by value. An array name can be used as an argument for the function declaration. The subscripts are not required to invoke a function using arrays. Example: /* Program to sort an array of integers in ascending order using the function sort( ) */ main( ) { int i, number[10]; clrscr( ); printf(Enter the Numbers:\n); for( i = 0; i < 10; i++) { scanf(%d,&number[i]); } printf(Numbers Before Sorting:\n ); for( i = 0; i < 10 ; i++) { printf(Number[%2d] = %d\n,i,number[i] ); } sort( 10, number); /* function declaration */ printf(Numbers After Sorting:\n ); for( i = 0; i < 10 ; i++) { printf(Number[%2d] = %d\n,i,number[i] ); } getch( ); return; } sort( m, x) /* Called Function */ int m, x[ ]; { int i, j, temp; for( i = 0; i < m ; i++) { for( j = 0; j < m-i ; j++) { if ( x[j 1] > x[ j ] )

- 13 -

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI { temp = x[j 1]; x[j 1] = x[ j ]; x[ j ] = temp; } } } return; }

- 14 -

PRU

SAICOM COMPUTER EDUCATION CENTRE, SAINAGAR, AMRAVATI

- 15 -

PRU

Potrebbero piacerti anche