Why use C?
In the today world of computer programming, there are many high-level language to choose from, such as C, Pascal, BASIC, and Java. These are all excellent language suited for most programming tasks. Even so, there are several reasons why computer professional feel that C at the top of the list:
• C is a powerful and Flexi able Language. What you can accomplish with C is limited only by your imagination .The language itself places no constraints on you. C is used for Projects as diverse as operating System, Word Processing, Graphics, Spreadsheets, and even compiler for other languages.
• C is a popular Language preferred by Professional programmers. As a result, a wide variety of C compilers and useful accessories are available.
• C is a Portable Language .Portable mean that a C program written for one computer system (an IBM PC, for Example) can be compiler and run on another system(a DEC VAX System, perhaps) with little or no modification.
• C is a Language of the few words, containing only a handful of terms, called KEYWORD.
• C is a modular. C code can (and should) be written in routines called FUNCTION. These functions can be reused in other application or programs.
Where C stands
Let us now see how C compares with other programming language. All th programming language can be divided into two different categories.
A. Problem oriented Language or high level Language:
These Language have been designed to give a better programming efficiency, i.e. faster program development .Example of Language falling in this category are FORTRAN, BASIC, PASCAL etc.
B. Machine Oriented Language or Low level Language:]
These Languages have been designed to give a better Machine efficiency, i.e. faster program execution. Examples of Language falling in this category are Assembly Language and Machine Language.
C stands in between these two categories .That’s why it is often called a Middle Level Language, since it was designed to have both: a relatively good programming efficiency (as compared to Machine oriented Languages) and a relatively good efficiency (as compared to Problem oriented Language).
Steps of Starting With C
The C Character Set
A character Denotes any alphabet, digit or Special symbols used to represent information. Following tables shows the valid alphabets, numbers and Special symbols allowed in C
Variables:
Variables is a quantity which may vary (change) during program executive. Variables names are names givens to locations in the memory of computer where different constants are stored. This location can contain integer, float, and characters constants. They are fundamental requirement of any languages. Every Language has its own rules from naming the variables.
Rules for Constructing Variable Names
1. A variables name is any combination of alphabets, digits.
2. A first character in the variables name must be an alphabet.
3. No comas or blanks are allowed within a variables name.
4. No special symbols others than underscore (as in stn_name) can be used in a variable name.
5. The maximum length of the variables name should be eight characters.
6. Upper case and lower case letter are distinct (separate, different).
7. A keyword can not be used as a variable name.
8. A variable can not start with digits.
Keywords:
Keywords are the words whose meaning has already explained to the C compiler (or in a Broad sense to the Computer). It can not be used in the variable names. The keywords are also called reserved word. There are 32 keyword available in C.
Auto double if static break else int struct case enum long switch char extern near typedef const float register union continue far return unsigned default for shot void do goto signed while
Constants:
The value that does not change during executive of the program is called constant. A constant is sometime referred to as literal (accurate). This quantity can be stored at location in the memory of the computer.
A variable can be considered as a name given to the location in the memory where this constant is stored. Naturally the contents of the variable can change. For Example in the Equation:-
3X+Y=20
Since 3 and 20 cannot change, they are called constants, where the quantities X & Y can change hence are called variables.
There are three types of Constants:-
1. String Constants
2. Numeric Constants
3. Characters Constants
Strings Constants:-
A string constant is a Sequence of alphanumeric characters enclosed in double quotation marks whose maximum length is 255 characters following are the example of valid string constants:-
• “The Grade XI
• “Rs 500.00”
• “ Hello, how are you”
Following are the some example invalid
• Katmandu {char are not enclosed in double quotation}
• “ Katmandu {closing double quotation missing}
• ‘ Katmandu ’ {char are not enclosed in double quotaion}
Numeric Constants:
Numeric constants are positive or negative number. There are four (4) types of numeric constants:
1. Decimal Integer Constant
2. Floating point Constant
3. Hex Integer Constant
4. Octal Integer Constant
1. Decimal Integer Constant:-
An Integer constant is an integer-valued numbers. Integer’s constants do not contain decimals points.
Rules for constructing integer constant
• An Integer constant much have at least one digit.
• It must not have decimal points.
• It could be either positive or negative.
• No comma and brackets are allowed in integer constants.
• It no signed is assumed than in integer constant, it is assumed to be positive.
2. Floating point Constant
Numeric constant that contain decimal point are called real constants or floating constants. The floating point constant can be written in two form that are as followed
• Fractional form
• Exponential form
Notes Cont………….
Character Constants:
A character represented within single quotes denoted a charter constant
E.G:-
‘A’ , ‘a’ , ‘2’ etc.
Character constants have integer values. Most computers makes of the ASCII (i.e. American Standard Code for Information Interchange) character set, in which individual character in numerically encoded with its own unique 7-bit combination ( hence a total of 27 =128 different characters).
Data Types
A data type defines a set of values that a variable can store along with a set of operator that can be performed on that variable. There are basic data types in C namely char, int, float and double. These data types are called fundamental or buit-data types.
Input Output
A B C
T T T
T F T
F T T
F F F
Logical OR Operation
Logical NOT: The result of the Logical operation will be true if the operand is false and the result is false if the operand is true. The result can be changed from false to true to false with the negation operator !.
The general syntax is
! (Expression)
Input Output
T F
F T
Logical NOT Operation
Bitwise Operator :
One of C’s 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 Operator available in C are as shown in figure :
Operator
Meaning
~
>>
<< & | ^ One’s complement Right shift Left shift Bitwise AND Bitwise OR Bitwise XOR( Exclusive OR) Conditional Operator The conditional operator ? and : are sometimes called ternary operators since they takes three arguments. In fact, they are a kind of foreshortened if-then-else. Their general form is, Expression 1 ? Expression 2 : Expression 3 What this expression says is: “if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2 otherwise the value returned will be expression 3” Example: int x,y; scanf(“%d”,&x); y=(x>5?1:2);
if(x>5)
y=1
else
y=2
Control statements
Operation that terminates the sequential execution of instruction by transferring control to a statement else where in the program based on specific condition.
Conditional Expression:
A statement that is executed only a certain condition within a program has met is called conditional expression. The conditional expressions are mainly used for decision making. The following statements are used to perform the tasks of the conditional Operator:
1. If Statement
2. If-else Statement
3. Nested If-else Statement
1. If Statement:
The if statement is used to express conditional expressions. The general form of if statement is
If (expression)
{
statement_1;
statement_2;
statement_3;
??????????
statement_n;
}
The expression must be placed in placed in parenthesis (aside). In the form, the set of statements within braces will be executed only the expression has a value of zero. Then the set of statements will be ignored.
2. If-else statements:
The if statements by itself will execute a single statement, or a group of statements, when the condition following if is true. It does nothing when the condition is false. Can we execute one group of statements if the condition is true and another group of statements if the condition is false?
The general form of if-else statements is
If (expression)
{
statements_1a;
statements_2a;
?????????????
statements_n;
}
Else
{
statements_1b’
statements_2b;
?????????????
statements_3b;
}
If the expression is true then statements_1a, statements_2a ……. Will be executed and if the statements is false then statement
3. Nested if-else Statements:
If we write entire if-else statements either within the body of the if statements or within the body of the else statements then it is called nested if-else.
The general form of Nested if-Else/Else-if statements is
If (expression)
{
Statements_1
Statements_n
}
Else
{
If (expression)
{
Statements_1
Statements_n
}
Else
{
Statements_1
Statements_n
}
}
Decision Using Switch
Switch Statements:
The Control statements which allows us to make a decision from the number of choice is called a switch, or more correctly a switch-case default, since these three keyword go together to make up the control statement. They most often appear as follows.
Syntax:-
Switch (integer expression)
{
case constant 1:
statements_1;
case constant_2:
statements_2;
case constant_3:
statements_3;
case constant_4:
statements_4;
default:
statements_5;
}
The Output of this Program
If we Input Integer Value 3
Result/output = Statement_3
Statement_4
Statement_5
As shown in example it will output all the statements after value execute, that we don’t expect the output will also be display as a result.
If you want that only certain statements should be executed, it is upto you to get out of the control structure then there by using a Break statement the following example shows who this is done
Note: that there is no need for break statements after the default, since the control comes to the end anyway.
Int a=3;
Switch (a)
{
case constant 1:
statements_1;
break;
case constant_2:
statements_2;
break;
case constant_3:
statements_3;
break;
case constant_4:
statements_4;
break;
default:
statements_5;
}
The Output of this Program
Result/output = Statement_3
Loops
The flexibility (versatility) of the computer lies in its ability to perform a set of instruction repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. The respective operation is done through a loop control statements.
There are three methods by way of which we can repeat a part of a program. They are:
• Using a for statement
• Using a while statement
• Using a do-while statement
Each of the following method are discussed in the following pages.
The while loop
It is often the case in programming that you want to do something a fixed number of times. Perhaps you want to calculate gross salaries of 10 different person or you want to convert temperature from centigrade to Fahrenheit for 15 different cities. The while loop is ideally suited for such cases. Syntax for while loop is given below
While (condition)
{
Statement
}
Example using while loop
}
Int Count=1, p, n;
Float r, si;
While (count<=3) { printf(“enter the value”); scanf(“%d %d %d”, &p, &n, &r); si = P*n*r/100; printf(“Simple Interest=rs.%d,si); count=count+1; } } The program executes all the statement after the while 3 times. The logic for calculating the simple interest is written within a pair of braces immediately after the while keyboard. The parentheses after the while is contain a condition. So long as the condition remains true all statements within the body of the while loop keep get executed repeatedly. Note :- the variable count is many a times called either a ‘loop counter’ or an ‘index variable’ Flowchart after using while loop is shown below Fales True The condition being tested may use relational or logical operators as shown in the following example While (i<=10) While (i<=10 && j<=15) While (i>=10 && (b<15 || c<20) Do-While Loop The syntax for the do-while loop is as given below Do { statement_1; statement_2; statement_1 } While (this condition is true); There is the minor different between the working of while and do while loops. The different is the place where the condition is tested. 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. This mean do while would execute its statements at least once, Cont…. Even if the condition fails for the first time itself. The while, on the other hand will not execute its statements if the condition fails for the first time. This difference is bought about more clearly by the following program. Main() { while(4<1) printf(“Cit”); } here, since the condition fails for the first time itself the printf() will not executed at all. Let’s now write the same program using a do-while loop. Main() { do { printf(“Cit”); }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. Apart from this peculiarity(habit) of the do-while, the while and do-while behave exactly identically, do-while loops are rarely used in C programs, since there are comparatively fewer occasions when we want to execute a loop at lest once no matter what. Flowcharts after using do-while loop is shown below True False For loop Perhaps one reason why few programmers use while is that they are too busy using the for, which is probably the most popular looping control. The allows us to specify three things about a loop in a single line: 1. Setting a loop counter to an initial value. 2. Testing the loop counter to determine whether its value has reached the number of repetitions desired. 3. Increasing the value of loop counter each time the program segment within the loop has been executed. The general form of for statement is under. For(initialise counter ; test counter ; increment counter) { statements_1; statements_2 statements_n } lets us write sown the simple interest program using for main() { int p,n,count; float r,si; for(count=1;count<=3;count++) { printf(“Enter the value of P,t,r”); scanf(“%d %d %d”,&p,&n,&r); si=P*n*r/100; printf(“Simple interest=%f”,si); } } Nesting of Loop The way if statements can be nested, similarly whiles and for can also be nested. To understand how nested loop work, look at the program given below. Main() { int a,b,sum; for(a=1;a<=3;a++) { for(b=1;b<=3;b++) { sum=a+b; printf(“a=%d b=%d sum=%d”,a,b,sum); } } } The out put of the following program are as given below: a=1 b=1 sum=2 a=1 b=2 sum=3 a=2 b=1 sum=3 a=2 b=2 sum=4 a=3 b=1 sum=4 a=3 b=3 sum=5 ARRAY An array is a collection of homogeneous data, which are stored in consecutive(repeated) memory location under a common variable name. E.g : - Void main( ) { int i ; i = 1; i = 5; i = 10; Printf(“%d”,i); } This program will print the value of i as 10, because when a value of 10is assigned to i, the value of i i.e. 1 and 5 is lost. Thus, the ordinary variables are capable of holding only one value at a time. For e.g. Suppose we whish to arrange the percentage marks obtain by 100 students, in such case we have two option to store this percentage, marks in memory. • Construct 100 variables to store percentage marks obtain by 100 different students, each variable containing one student marks. • Construct 1 variable called array capable of storing 100 subject variables. The second alternative option is better because it would be much easiers to handle one variable than handling one different variable. An array is a collection of similar elements or is a set of homogeneous data item which could be all integer or all floats or all characters (char) , but we cannot have an array of 10 no’s of which five are integers or 5 are floats. A simple program using Array Void main( ) { float avg,sum=0; int i; int marks[30]; for(i=0;i<=29;i++) { printf(“Enter marks”); scanf(“%d”,&marks[i]); } for(i=0;i<=29;i++) { sum=sum+marks[i]; } printf(“%d”,sum); } Array Declaration To began with, like other variable an array needs to be declared so that the compiler will know that kind of an array and how large an array we want. Int marks[29]; Here int specifies the type of the variable, just as it does with ordinary variables and the words marks specifies the name of the variable. The [30] however is new. The number 30 tells how many elements of the type int will be in our array. This nimber is often called the dimension of the array. The bracket ([]) tells the compiler that we are dealing with an array. WAP to find the greatest No among 3 No ? Void main( ) { int n1,n2,n3; int great=0; printf(“Enter any 3 no to compare=”0; sacnf(“%d %d %d”,&n1,&n2,&n3); if(n2>n1 && n2>n3)
{
great=n2;
}
else if(n1
max=num[i];
}
printf(“%d”,max);
getch( );
}
Array Initialization
Let’s see how to initialize an array while declaring it. Following are a few examples which demonstrate this.
Int num[6]={5,3,1,7,8,9};
Int n[]={9,6,2,1,4,6};
Floate press[]={33.2,45.2,14.6};
Notes the following points carefully.
1. Till the array elements are not given any specific values, they are supposed to contain garbage values.
2. If the array is initialized where it is declared mentioning the dimension of the array is optional as in the 2nd example above.
More than One Dimension
So far we have explored array with only one dimension. It is also possible for array to have two or more dimension. The two dimensional array is also called matrix.
Here is a sample program that stores roll number and marks obtained by a student side by side a matrix.
Void main()
{
int stud[4][2];
int I,j;
for(i=0,i<=3;i++) { printf(“Enter the roll and marks of the students?”); scanf(“%d %d”,&stud[i][0],&stud[i][1]); } for(i=0;i<=3;i++) { printf(“%d %d”,stud[i][0],stud[i][1]); } getch(); } Col no. 0 Col no. 1 1111 55 1111 22 3333 66 7777 88 Row no.0 Row no.1 Row no.2 Row no.3 Memory Thus 1111 is stored in stud[0][0], 55 is stored in [0][1] and so on. The above arrangement highlights the facts that a two dimensional array is nothing but a collection of a number of one dimensional array placed one below the other. Initializing a 2-dimnesional array How we can initialize a two dimensional array? As a simple as this int stud[4][2]= { {1111,55}, {1111,22}, {3333,66}, {7777,88} }; or even this would work int stud[4][2]= (1111,55,1111,22,3333,66,7777,88}; It is important to remember that while initialization an array it is necessary to mention the second (column) dimension, where first dimension (row) is optional. Int an[2][3]={36,25,47,89,21,45}; Int an[][3]={77,89,65,35,46,59}; Where as Int an[2][]={36,65,98,47,12,54}; Int an[][]={89,47,12,35,46,58}; Would never work. String The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character array. Character array are manly a times also called string. Characters arrays or strings are used by programming languages to manipulate test such as words and sentences. A string constant is a one dimensional array of characters terminated by a null (‘/0’). For example, Char name[]={‘c’,’I’,’t’,’c’,’o’,’l’,’l’,’e’,’g’,’e’,’\0’}; Here ‘/0’ is called null character, note that ‘\0’ and ’0’ are not same. ascii value of ‘/0’is 0, where ascii value of ‘0’ is 48. The terminating null (‘\0’) is important, because it is only way the function that work with a string can know where the string ends. In fact a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters. C concedes the fact that you would use strings very often and hence provides a shortcut for initializing strings. For example the string used above can be initialized as, Char name[]=”citcollege”; Note that in this declaration ‘\0’ is not necessary. C inserts the null characters automatically. While entering the string using scanf() we must be cautions about two things. • The length of the string should not exceed the dimension of the character array. Hence, if you carelessly exceed the bounds there is always a danger of overwriting. • Scanf() is not capable of receiving multi-word strings. There fore names such as “Cit College” would be unacceptable. The way to get around this limitation is by using the function gets(). The usage of function gets() and its counterpart puts() is Shown below Void main() { char name[25]; printf(“Enter your name?”); gets(name); puts(“Hello”); puts(name); and here is the output Enter your name Hello Cit college Standard Library String Function With every C compiler a large set of useful string handling library function are provided. The following list are the some of the important library function. Strlen Finds length of the string Strlwr Convert a string to lower Strupr Convert a string to upper Strcat Appends one string at the end of another Strcpy Copies a string to another Strcmp Compares two strings Strrev Reverse string Strlen( ) This function counts the number of characters present in a string. Their usage is illustrated in the following program. Void main( ) { char name[]=”Citcollege”; int len1,len2; len1=strlen(name); len2=strlen(“Cit College”); printf(“%d”,len1); printf(“%d”,len2); The output would be 10 11 Note that in the first call to the function strlen( ), we are passing the base address of the string, and the function in turn returns the length of the string. While calculating the length it doesn’t count ‘\0’. Strcpy( ) This function copies the contents of one string into another. The base addresses of the source and target string should be supplied to this function. Here is an example of strcpy( ) in action…… Void main( ) { char source[]=”CIT”; char target[10]; strcpy( target,source); printf(“%s”,source); printf(“%s”,target); And here is the output CIT CIT. On supplying the base addresses, strcpy( ) goes on copying on copying the characters in source string into the target string till it doesn’t encounter the end of source string (‘\0’). Strcmp( ) This is the function which compare two strings to find out whether they are same or different. The two string are compared characters by characters until there is a mismatch or end of one of the string is reached , whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re nit, it returns the numeric difference between the ascii values of the non-matching characters. Here is the program using strcmp. Void main( ) { char string1[]=”Cit”; char string2[]=”College”; int a,b; a=strcmp(string1,”Cit”); b=strcmp(string1,string2); here is the output of the following 0 4 question • write a program to read names of 10 person in an array and enter any one name and search the name whether it is in the list or not . • Write a program to enter a phase and check whether it is palindrome or not. • Write a program to read some line of text and convert it into upper case. • Write a program to read some line of text and convert it into lower case. Strcat( ) This function concatenates the source string at the end of the target string. For example “CIT” and “COLLEGE” on concatenations would result into a string “CITCOLLEGE”. Here is the example of strcat( ) at work. Void main( ) { char name[]= “CIT”; char ame[]= “COLLEGE”; strcat(target,source); printf(“%s %s”, name,ame); } and here is the output source string = COLLEGE target string = CITCOLLEGE Question Intput 5 differents name and output it into alphabetically order ? #include
#include
#include
void main()
{
char a[5][15],b[15];
int i,j;
clrscr();
fflush(stdin); /* to refresh the buffer*/
for(i=1;i<5;i++) { printf("\n\nType the name:"); gets(a[i]); fflush(stdin); } for(i=1;i<5;i++) { for(j=1;j<=5-i;j++) { if(strcmp(a[j-1],a[j])>0)
{
strcpy(b,a[j-1]);
strcpy(a[j-1],a[j]);
strcpy(a[j],b);
}
}
}
for(i=1;i<5;i++) { puts(\na[i]); } getch(); } Structure We have seen earlier how ordinary variables can hold one piece of information and how arrays can hold a number of pieces of information of the same data type. There two data types can handle a great variety of situations. But quite often we deal with entities that are collection of dissimilar data types. For examples, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int). if data about say 3 such books is to stored, then we can follow two approaches. a) Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages. b) Use a structure variable. Using first approach Void main( ) { char name[3]; float price[3]; int page[3]; int a; printf(“Enter the name, price and pages of the book ?”); for(a=0;a<3;a++) { scanf(“%c %f %d”,&name[a],&price[a],&page[a]); } for(a=0;a<3;a++) { printf(“%c %f %d\n\n”,name[a],price[a],page[a]); } getch( ); } The program became more difficult to handle as the number of item relating to the book go on increasing. For examples, we would be required to used a number of arrays. If we also decided to store name of the publisher, dare of purchase of book etc. to solved this types of problem C programming provides special data types ………..Structure Structure A structure contains a number of data types grouped together. These data types may or may not be of the same types. The examples using structure Void main( ) { struct book { char name; float price; int page; }; struct book b1,b2,b3; printf(“Enter the name, price and pages of the book ?”); scanf(“%c %f %d”,&b1.name,&b1.price,&b1.page); scanf(“%c %f %d”,&b2.name,&b2.price,&b2.page); scanf(“%c %f %d”,&b3.name,&b3.price,&b3.page); printf(“%c %f %d”,b1.name,b1.price,b1.page); printf(“%c %f %d”,b2.name,b2.price,b2.page); printf(“%c %f %d”,b3.name,b3.price,b3.page); getch( ); } Declaring a structure In our Program, the following statements declares the structure types. Struct book { char name; float price; int page; }; this statement define a new data type called struct book, each variable of this data type will consist of a variable called name, a float variable called price and an integer variable called pages. The general form of a struct declaration statements is given below. Struct
{
statements_1;
statements_2;
statements_3;
};
Once the new structure data type has been defined once or more variables can be declared to be of that type. For the example the variables b1,b2,b3 can be declared to be of the type struct book, as
Struct book b1,b2,b3;
It makes available space to hold all the elements in the structure. In this case 7 bytes reserved.
Declaration
Struct book
{
char name;
float price;
int page;
};
struct book b1,b2,b3;
or
Struct book
{
char name;
float price;
int page;
}b1,b2,b3;
or
Struct
{
char name;
float price;
int page;
}b1,b2,b3;
Typedef
The typedef feature allows us to define new data-type. It’s purpose is to redefine the name of an existing variable types.
The general form of the typedef is as followes :
Typedef data_type new_data_type;
Where typedef is a keyword for declaring the new data items, data_type refers to the existing data type and new_type refers to the new user_defined data_type. It should be clear that the new data type will be new is name only. In reality, this new data type will not be fundamentally different form one of the standared data types.
For Example
Typedef int integer;
Typedef float real;
Integer 1,j;
Real k,m;
Union
This is another data structure just like array and structure; there are many similarities than differences between array, structure and union. It is more near to structure because it can store multiple data types with the dame name. but, only the big difference is that, array and structure reserves memory cells in advance for each of the elements declared where as union saves memory space by declaring only one(for the biggest elements) memory cell. So, care must be taken where handling union, because where we assign one elements and again assign another, then the first one is erased from the memory and the same place is taken up the second elements.
Function.
C supports the modular features of programming. Due to which, a program can be decomposed into different program segments or blocks, so that the particular set of instructions (module) defined for specific task can be reused at any part of the other modules.
A function is a self-combined block of instruction or set of instruction that perform the specific operations on the program. A function defined once in the program can be used at any time and location in the same function can be defined in two ways.
i.e.
1. Within the program: which is used in the same program only.
2. Library function: that can be used in any program after defining as header file.
Advantage of Function
Elimination of code repetition.
Short program length.
Structured program, clearly readable, understandable, easy evaluation and modified.
Re-usability of codes.
Programming is easy due to decomposition of large program into small pieces.
There are 2 different types of function used in C that are as followes.
1. Library function.
2. user-defined function
1. Library function:
These functions are provided by C compilers. Before calling the library functions the header file containing the particular function is to be linked are the top of the program like, #include
scanf( ), printf( ), pow( ), toupper( ) etc. these are verities of C functions available separately designed and defined for string, mathematical and complex mathematical operation.
2. User-defined function:
The libraries function re not sufficient to solve all the problems of user or programmers in case of some specific operations. Hence, in such cases C has provided a facility to create function regarding the specific problem. A programmer can declare, define and call his/her own function in the program as per the need.
Void sumodd(void)
Void sumodd(int y);
Int sumodd(int y);
Float sqr(int x);
Double mul(float x, float y);
Mul(……..);
Here, in the function declarations, the keyboard at first defines the type of function, and the listings inside pair of braces are called function parameters or arguments. Function may or may not have the type declaration and arguments. If no function type, it is automatically known as integer types. The arguments may be of different types, if a value of one type is passed to the function and the function is of different type then the value is automatically converted to the function type while returning it (from small to larger).
Void refers to no value to carry
In C, main is the first program which is defined and executed, other programs are called by main. Any function can be called in any others functions and itself also.
Types of function Call
1. Call by value and
2. Call by reference
By now we are well familiar with how to call functions. But, if you observe carefully, whenever we called a function and passed something to it we have always passed the ‘value’ of variables to the called functions. Such function calls are called ‘calls by value’. By this what we mean is, on calling a function we are passing a values of variables to it. The examples of call by value are shown below.
Sum=calsum(a,b,c);
F=factr(a);
We have also learnt that variables are stored somewhere in memory. So instead of passing the value of a variable, can we not pass the location number (also call address) of the variable to a function? If we are able to do so it would become 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 ‘Pointer’.
In the first method the ‘value’ of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. The following program illustrates the “call by value”.
Main( )
{
int a=10,b=20;
swapv(a,b);
printf(“%d %d”,a,b);
getch( );
}
void swapv(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(“%d %d”,x,y);
}
o/p : x=20,y=10
: a=10,b=20
Note that the values of a and b remain unchanged even after exchanging the value of x and y.
The second method (call by reference) the address of actual arguments in the calling function are copied into formal arguments of the calling function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them. The following program illustrates this fact.
Main( )
{
int a=10,b=20;
swapv(&a,&b);
printf(“%d %d”,a,b);
}
void swapv(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Pointer:-
A Pointer is nothing but a variable that contains the address of another variable. Consider an Example.
Int a= 10;
Here, ‘a’ is the name of variable that stores the value 10 and is stored in memory in the address say 108. this could be represented as
108:- The address of the variable.
109 108
ptr-a a
Pointer Declaration.
Int *ptr-a;
Here ptr-a is a pointer pointing to a variable of type int. The unary operator ‘*’, makes all the difference between an ordinary variable and a pointer type variable. In this e.g. ptr-a return 108 where as ‘a’ return 10.
Initialization:- we have to initialization a pointer as soon as it is declare. Since a pointer is just an address, it, if un-initialize may randomly point to some location in memory. The uniary operator ‘&’ also called the address operator, where applied to a variable refers to the address of that variable.
Ptr-a=&a
When the initialization is made, the address of the variable ‘a’ is assigned to ptr-a as its value.
File Handling.
The input to the C-Program and the output generated by that remains inside the memory of Computer. As Soon as power goes down, everything vanishes. How can we store the output of program permanently? Unless we have mechanism to store the results of our program, we can’t realize the essence of our programming. The answer for this problem is a new data-Structure, Which is FILE.
FILE is a data-Structure where we can permanently store the data. Putting in other words, FILE is data-Structure which helps us to store out data permanently on the secondary storage devices (e.g. hard-disk, floppy-disk, etc).
We can visualize “.txt” file as FILE. One can create, open, modify and close a file. The syntax for creating file is a following.
FILE *fp;
Where file must be in capital letter and ‘fp’ is a pointer of the FILE type. Everything that is done with FILE is to be done with file Pointer. Following are the steps for creating file handler:
STEP:1 Creating a Pointer variable of File data-type. For Example;
Syntax: FILE file_pointer
Example: FILE *fp
STEP:2 The file must be opened before using it. It can be done using the following syntax:
Syntax: file_pointer-fopen(“file_name”,”mode”);
Example: fp=fopen(“abc.txt”,”w”);
Where :
File_name can be any valid file name. Rules for a valid file name is an follows:
• File name should be as per the operating System specification. For example –MS-DOS supports files not more than 8 characters and windows supports files not more than 256 characters.
• Spaces are not allowed in between the file name in MS-DOS mode where it is allowed in windows.
• Any alpha-numeric characters (e.g. a,b,c,d,1,2,3,etc) are accepted.
‘Mode’ can be any one of the following.
Mode Description
R open file for reading or display
W open file for writing
A open file for appending
The similarity between ‘w’ mode and ‘a’ mode is that both are used for writing in a file. The difference is that –previous contains are erased and new contents are added when file is open in ‘w’ mode , where as precious contents are preserved and new contents are also added at the end of file in ‘a’ mode.
Opening file for writing
1. Create a FILE pointer.
2. Open File in write (w or a) mode.
3. Perform general I/O operations.
4. Save the I/O results using following syntax:
Fprintf(file_pointer,”format specifier lists”,variable lists);
5. Close the file using fclose(file_pointer)
Example.
Write a program which asks name and age of a person and store it in a file “Record.dat”.
#include
#include
void main( )
{
int age;
char *name;
FILE *fp;
Fp=fopen(“Record.dat”,”w”);
Printf(“Enter your name”);
Scanf(“%s”,name);
Printf(“Enter your age”);
Scanf(”%d”,&age);
Fprintf(“”%s %d”,name,age);
Fclose(fp);
}
Open the file for Reading
1. Create a FILE pointer.
2. Open File in read (r) mode.
3. Perform general I/O operations.
4. Read data from file using following syntax:
Fscantf(file_pointer,”format specifier lists”,variable lists);
5. Display the data as required
6. Close the file using fclose(file_pointer)
#include
#include
void main( )
{
int age;
char *name;
FILE *fp;
Fp=fopen(“Record.dat”,”w”);
Fscanf(fp,“%s %d”,name,&age);
Printf(“your name %s”name,);
Printf(“your age %d”,age);
Fclose(fp);
}
Graphics
Function
Meaning
Putpixel(x1,y1);
Line(x1,y1,x2,y2);
Circle(xc,yc,rad);
Size
Rectangle(x1,y1,x2,y2);
Ellipse(xc,yc,start,end,rad,yard);
Arc(xc,yc,start,end,rad);
List the pixel at (x1,y1)
Draw a line from (x1,y1) to (x2,y2).
Draw a Circle with center (xc,yc) and radius rad.
Draw a rectangle with (x1,y1) and (x2,y2) as corners.
Draw a ellipse with (xc,yc) as center with xrad and yrad as x and y radius. If start is 0 and end is 180 only the upper half of the ellipse is drawn.
Draw an arc with (xc,yc) as center, rad as radius and start and end as the starting and ending angles.
Some of the function if the graphics they are as follows.
• Setlinestyle(linestyle,1,thicknes);
Syntax :- Setlinestyle(0-4,1,1-3);
• Settextstyle(font,direction,size);
Syntax :- Settextstyle(0-4,0=h 1=v,0-10);
• Outtextxy(x,y,text);
Syntax :- Outtextxy(x,y,text);
• Outtext(text);
Syntax :- Outtext(text);
• Setcolor(color);
Syntax :- Setcolor(RED);
• Cleardevice( ); / clrscr( );
Syntax :- cleardevice( ) ;
• Closegraph( );
No comments:
Post a Comment