C has evolved from a succession of programming languages developed by Bell Laboratories in the early 1970s. The increasing popularity of the unix operating system, which has C as its “Standard” programming language, further enhanced the usefulness of C making it arguably the most popular of the programming languages.
We now start with the fundamentals of the language. Any language, as you know is made of sentences, which are made up of words, which in turn are made up of characters i.e. we start learning the characters, then learn how to combine them into words, combine the words into sentences, and so on.
Characters of C
C makes use of the normal characters of English – a to z, 0 – 9 and several special characters like + – * / , . % # $ & “ = ; ( ) { } \ and so on. Most of the compilers are also case sensitive. i.e. they do differentiate between capital and small letters so you should not go about mixing them. It is a good practice and also pleasing to type all program with small letters.
Variables of C
Just as a language is made up of names, verbs, adjectives, adverbs etc., C programs are made up of variables, constants, arithmetic operators etc. We learn them one after another in the following sections. A variable in a program is a name to which you can associate a value. For ex. with the name A you can associate, say, a number 10, so that whenever the number A is called/used, you get the value 10.
Rules for framing variables.
They begin with a letter or underscore(_), and may be followed by any number of letters, underscores or digits (0-9). But you cannot have special characters or blankspaces in a variable name.
The following are valid variables:
Prod sum_total I J _sysflag.
The following are invalid variables:
Sum $ total part total 5load int
Now based on the previous definition, we leave it to you to decide why they are invalid. But the last word int appears to be valid as per the definition. It is a invalid variable,because it is a “Reserved name”. The C compiler, uses a reserved name with a special name and you can not use it with your own definition. As we go about, we pickup a large number of such reserved words and their meanings.
One sound advise for choosing the names of variables. You can practically use any name to store any value. For example A or M can be used to store sum, product, quotient any thing as long as you know what is it that you have stored. However, it is a good practice to use meaningful names to store data. You can store the result of addition in sum, product of two numbers in prod, etc.. When your are writing long programs, such practices help you a lot in checking the correctness (technically called debugging) and understand the programs.
Data types and constants of C
The concept of variables that we have just introduced to is just to initiate you to the various ways in which data can be stored in C. We now seek a more formal and complete description of the various ways in which data can be manipulated in C.
A variable name is one which the stored data can be changed during the execution of the program. For example if you have store 10 in A initially, you can add or subtract something to it or even store a totally different value. i.e the data A is “variable”. On the other hand you can also have certain constants, whose values do not change during execution.
Variables themselves come in different types. They can be integers (whole numbers), floats (fractional numbers) doubles and characters. Characters as the name suggests are used to store characters. A number of characters in a string are sometimes called the string (Str) variables. The data type doubles need some introduction. Normally a C compiler can store numbers of certain size only. The actual size depends on the computer you are using and the compiler in use. If you suspect that you are likely to use numbers bigger than this, you should use double declaration, which will give you twice the number of places. i.e. if your original limit was 5 places, you may now get to use up to 10 places which will suffice in most cases.
C expects you to list the variables you are using in your program at the beginning itself and also their types. For example:
Int a,b,c Float no,n1,n2; Char name, title;
makes a,b,c available for storing integer numbers (like 10,20,30), no,n1,n2 store fractional numbers (like 10.42, 13.56, 15.7 etc) and name and title store character strings (like rama, student etc.).
The semicolon (;) at the end is used extensively in C to demarcate one statement from another (Just as . is used in English).
Arithmetic Expressions
Once you have learnt about integers, float etc, the next stage is to combine them. They can be combined with the usual addition, subtraction symbols.
For ex. A + B, a – c, a * b etc. can be used. However, mere such operations are not enough.The data that you get after the operation is to be stored in a variables name. Hence, you can write.
a = a + 10; Sum = a+b; X=y*z; etc.
In the first case, 10 is added to the original value of a (what ever it was) and is stored as the new value of a. (the original value is lost). In the second case a and b are added and the result is stored in sum. In this case, since a and b are not being overwritten, their values continue to be available to you. In the third case, the product of y and z is stored in x.
Before you can start writing small programs, we also conclude about precedence of operators. In a long expression with a number of such operators, which one is evaluated first?
The answer is first all multiplication and division operators are completed. Then all addition and subtraction are taken up. For example, if we write:
A = b + 2 * c;
2 * c is evaluated first (multiplication) and this is then added to b.
If there are more than one multiplication, addition, etc. the computations are done from left to right. For example:
a = b + c / d + e * f
c / d is evaluated first, then e * f then b is added to the result of c / d and finally the result of e * f is added. The entire value is stored in a.
Try yourself: Suppose b is 4, c is 8, d is 2, e is 4 and f is 2, what value is store in a?
Sometimes, we may like to override the precedence of operators of C. Suppose in the above example, I want b + c to be added first and then divided by d. I can still do it, simply enclosing b + c within parentheses (b+c). The rule is whatever is within the parentheses is evaluated first. So (b+c) is evaluated first and then is divided by d.
Try evaluating a = (b + c)/d+ e*f with the above given values for a, b, c, d, e and f.You notice that, by enclosing them within parentheses, we have changed the result. So, whenever you are evaluating long expressions, it is always desirable to be careful about the precedence of operators. However, one golden rule is that whenever in doubt, use parentheses. For ex; in our original example, you want c/d to be evaluated first, there is no need for parentheses to be used. However, if you are not confident of your judgement,simply enclose them in parentheses as in a = b + (c / d) + (e * f).
You should note that the expression within brackets need not be as simple as we have illustrated. They can be as long as you like, there can be parentheses within parentheses and so on. Again, within these parentheses the same rules of precedence apply, including the fact that those inside the parentheses are evaluated first. So, in effect the evaluation starts from the innermost parentheses and proceeds outwards.
For ex, I can write:
a = b + c / ((d + e) * f)
wherein the innermost parentheses d + e is evaluated first, this is multiplied by f, c is divided by the whole value and finally it is added to b. (What will be the result if you take the above mentioned values? )
Again remember the golden rule: Whenever in doubt, use parentheses. Use of extra parentheses will not affect the results, but not using them when needed changes the final results. Now, we are in a position to illustrate these with a sample C program. However, before we can write a full program,we introduce you to one more concept of getting the output from the program. There is a function printf() which allows you to do this.
Illustrate the use of various arithmetic operators
# include<stdio.h> main( ) { int a = 100; int b = 2; int c = 25; int d = 4; int result; result = a-b; /*subtraction */ printf(“a – b = %d \n”, result); result = b * c /* multiplication */ printf(“b * c = %d \n”, result); result = a / c; /* division */ printf(“a / c = %d \n”, result); result = a + b * c; /* predence */ printf(“a + b * c = %d \n”, result); printf(“a * b + c * d = %d\n”,a* b+c*d); }
output:
a – b = 98 b* c = 50 a / c = 4 a + b + c = 150 a* b + c * d = 300
Now a description of what we did in the program.
Whatever we write in between /* and */ is a comment. i.e. the C compiler will not process it. You can write your comments and explanations so that it will be easier for you to understand the program, when you go through it at a later date.
#include <stdio.h> is used to include certain input / output functions. We discuss about them later. As of now we simply presume that it should be there.
Main() indicates that it is a main program, we study more about it later. Notice that the entire program is enclosed between the brackets { and }. Later, we see that there can be many more such segments enclosing portions of the program. The declaration int a = 100; declares a as an integer variable and stores 100 in it. Similarly stores 2 in b, 25 in c and 4 in d. The variable result is also declared as an integer, but no value is stored in it as of now. As and when the calculations are done, the result of the calculation are stored in result.
Now look at the statement:
printf("a – b = %d \n",result);
Printf, as we have already described is used to print the output. Now whatever is between the inverted commas “ and ” is printed as it is, except %d and \n. %d indicates that an integer value is to be printed at that place and \n indicates that after printing, the cursor should go to the next line. Now, outside the inverted comma, we have the result, which is an integer. So the value of integer stored in variable result is printed where %d is appearing.
In effect the output looks like this: a – b = is printed as it is. In place of %d, the value of result is printed (What ever is its value). Because \n is there, the control goes to the next line i.e the next printf comes in the next line.
Now analyse the entire program and the output of the same given above. To make things more familiar, we write one more very similar program. This will evaluate the expressions we encountered during the discussion on precedence of operators.
Illustrate the use of precedence of operators
#include <stdio.h> main() { int a; int b = 4; int c = 8; int d = 2; int e = 4; int f = 2; a = b + c / d + e * f /* result without parentheses */ printf(“The value of a is = %d \n”, a); a = (b + c) / d + e * f /* result with parentheses */ printf(“The value of a is = %d \n”, a); a = b + c / ((d + e) * f) /* another result with parentheses */ printf(“The value of a is = %d \n”, a); }
output:
The value of a is = 16 The value of a is = 14 The value of a is = 1
More arithmetic expressions
#include<stdio.h> main( ) { int a = 25; int b = 2; int result; float c = 25.0; float d = 2.0; printf(“6 + a / 5 * b = %d \n”, 6 + a / 5 * b); printf(“a / b * b = %d\n”, a / b * b); printf(“c / d * d = %f\n”, c / d * d); printf(“-a = %d\n”,-a); }
output:
6 + a / 5 * b = 16 a / b * b = 24 c / d * d = 25.00000 -a = -25
Note the difference between this and the previous two programs. When evaluate 6 + a / 5 * b, we have not stored it’s value in any result, but it is evaluated in the printf statement itself and printed straight away.
Program to multiply two numbers
# include <stdio.h> main( ) { float num1,num2,product; num1=300.0; num2=0.6; product = num1 * num2; printf(“ \n %f times %f is %f \n”,num1,num2,product); }
output:
300.000000 times 0.600000 is 180.000000
Program to computer average of three numbers
#include<stdio.h> main( ) { int a = 8; int b = 10; int c = 4; int sum,remainder; float average; /* Calculate the average and display the result */ sum = a + b + c; average = sum / 3; remainder = sum % 3; printf(The average of %d, %d, %d is %d and %d/3 \n”,a,b,c,average,remainder); }
Output:
The average of 8,10,4 is is 7.000000 and 1/3
There are some special types of arithmetic statements in C. Consider the statement i = i + 1; it states add one to i and store the new value as i. Such statements are very frequently used in what are called “increment” operation. Suppose you want to perform an operation 10 times. Then all that you do is to perform the operation once, count i as one, perform it again, add 1 to i. Perform again. Add one more to i and so on.
C provides a special method of writing such counting operation. Instead of i = i + 1, you can write i++. Both mean the same. In this example, you perform the operation and then increment i. In some cases, you may want to first increment and then perform the operation. For such situations, we use ++i. Whereas i++ is called post increment(increment after the operation) ++i is called preincrement. Of course, initially if you feel a bit uncomfortable about these statements, you can as well use i=i+1 type of statements to begin with.
Similarly there are decrement statements, for situations when you want to count backwards – instead for say 1 to 10 suppose you want to count from 10 to 1. Then initially you put i=10 then keep subtractive i=i-1. For such situation we have i– and –i post decrement where subtraction is done after the operation and subtraction is done before the operation respectively.
C also provides a list of arithmetic and logical operator. These will be useful,basically for the control structures operation (see next block). We give you the table of such operators, which can be used to compare two variables or statements.
Scanf() function
One thing you might have noticed in all the above programs is that we are not giving any inputs at all. The values needed by the program are being included in the program itself -only the output is being made available. Obviously, their cannot happen always. We may not know the input before hand always nor can we go on changing the programs, whenever the input data changes. So, there should an input function, which asks for input during the execution time and accepts the values from the keyboard. That function, obviously, is similar to printf( ) – it is called scanf( );
Whenever a scanf( ) is encountered, the computer waits for the user to give the value for that particular input from the keyboard and takes that as the value for the variable.
For ex: it in a program we have
scanf("%d",&a);
When this statement is executed on the computer, the program waits. If you type in,say 10, the value of a is taken as 10. There is a difference though. Instead of simple ‘a’, we write &a, which is a pointer to the location where a is stored. Any way, we come back to this topic again, For now, we can say all scanf( ) parameter come with the ampersand &.
Library functions
The C compiler wants to make the life of the user easier. It provides small program modules called library functions which are programs that perform functions that are needed often by programmers. The user will have to simply call them by their name & use it – he need not write then again and again. Some of the more frequently used library functions are listed below:
Cosine of the value : cos( ) Sine of the value : sin( ) Tangent of value : tan( ) Absolute value : abs( ) ( -a is taken as a) Logarithm to base e : log( ) Square root : sqrt( ) Raising to a power : pow( )
For that matter even scanf() & printf() with which you are familiar are library functions. These functions are available in special files – called header files. For ex: scanf, printf etc are available in a file called stdio.h, whereas cos, sine etc – are in a file called math.h. If you want to use these functions, you should include these files using the #include directive at the beginning of the program.
We have so far used only data type %d, a decimal value. Atleast three more type are frequently used % f for indicating the floating point(real) numbers, %e to indicate double length numbers and %c to store characters.
With these fundamentals we now write a large number of fairly simple programs.
Write a program to convert days to months and days
Algorithm:
- Start
- Enter days
- Calculate months ← Days/30
- Output months, Days
- Stop
PROGRAM TO CONVERT DAYS TO MONTHS AND DAYS
#include<stdio.h> main () { int m,d; printf(“Enter days”); scanf(“%d”,&d); m = d/30; d = d/%30; printf(“Months = %d Days = %d”,m,d); }
Typical Output:
Enter days: 305 Months = 10 Days = 5.
PROGRAM TO EVALUATE EXPRESSION
#include<stdio.h> main () { float a,b,c,x,y; a=2; b=10; c=3; x=a*c+b; y=a*x*x*+b*x+c; printf(“x = %f\n”,x); printf(“y = %f\n”,y); } /* END OF PROGRAM */
Output:
X=16.000000 Y=675.000000
PROGRAM TO READ A NAME AND DISPLAY THE SAME
#include <stdio.h> main () { char str[20]; printf(“\n Enter your name\n”); scanf(“%s”,str); printf(“\nYour Name is ...... %s”,str); } /* END OF PROGRAM */
Output:
Enter your name SUDARSHAN Your name is ...... SUDARSHAN
PROGRAM TO READ A STRING
#include<stdio.h> main () { char str[20]; printf (“\n HI, WHAT IS YOUR NAME ? ”); scanf(“%s”,str); printf(“\n\n WELCOME %s, \n LET’S BE FRIENDS.”,str); } /* END OF PROGRAM */
output:
HI WHAT IS YOUR NAME ? DINESH WELCOME DINESH LET’S BE FRIENDS
TO ROUNDOFF A REAL NUMBER TO NEAREST INTEGER VALUE
#include<stdio.h> main () { int d; float r,t; printf(“\nEnter a Real no.:”); scanf(“%f”,&r); t = r + 0.5; d = ((int)t); printf(“The value rounded off to the nearest integer is: %d”,d); } /* END OF PROGRAM */
output:
Enter a Real no : 62.768 The value rounded off to the nearest integer is : 63.
Write a program to find the area and perimeter of a circle given its radius
Algorithm:
- Start
- Assign Pi ← 3.1415
- Input radium
- Calculate area ← pi*r2, peri ← 2*pi*r
- Output Area, Perimeter
- Stop
CALCULATION OF AREA AND PERIMETER OF A CIRCLE
#include<stdio.h> main () { float r,pi=3.1415, area,peri; printf(“\n Enter radius of circle:”); scanf(“%f”, &r); area = pi*r*r; peri = 2 * pi * r; printf(“\n Area = %5.2f”,area); printf(“\n Perimeter = %5.2f”,peri); } /* END OF PROGRAM */
output:
Enter radius of circle: 2.56 Area = 20.59 Perimeter = 16.08.
Write a program to find the area and perimeter of a rectangle having length,l and breadth b.
Algorithm:
- Start
- Input length & breadth
- Calculate area← length * breadth, peri←2*(length + breadth)
- Output area,peri
- Stop.
CALCULATION OF PERIMETER AND AREA OF A RECTANGLE
#include<stdio.h> main () { float l,b,area,peri; printf(“\nEnter length of rectangle:”); scanf(“%f”,&l); printf(“\nEnter breadth of rectangle:”); scanf(“%f”,&b); area=l*b; peri= 2*(l+b); printf(“\n Area=%10.2f”,area); printf(“\n Perimeter=%10.2f”,peri); } /*END OF PROGRAM*/
Output:
Enter length of rectangle: 2.5 Enter breadth of rectangle: 3.4 Area = 8.50 Perimeter = 11.80
Wrtite a program to accept temperature in Fahrenheit and convert it to degree celsius and viceversa
[ Hint: C=5/9*(F-32]
Algorithm:
- Start
- Input temperature in Fahrenheit(F)
- Calculate Celsius >- 5.0/9.0*(F-32.0)
- Output temperature in Celsius (C)
- Input temperature in Celsius(C)
- Calculate Fahrenheit >- (C*9.0/5.0) +32.0
- Output temperature in Fahrenheit
- Stop
CONVERSION OF TEMPERATURE IN DEGREE TO FAHRENHEIT AND VICEVERSA
#include<stdio.h> main() { float f,c,faren, cel; printf("\n Enter temperature in Fahrenheit:"); scanf(%f",&f); cel=5.0/9.0*(f-32.0); printf("\nTemperature in Celsius =%10.2f",cel); printf("\n Enter temperature in Celsius:"); scanf("%f",&c); faren=(c*9.0/5.0)+32.0; printf("\n Temperature in fahrenheit=%10.2f",faren); } /* END OF PROGRAM */
Output:
Enter temperature in Fahrenheit : 68 Temperature in Celsius = 20.00 Enter temperature in Celsius:20 Temperature in Fahrenheit = 68.00
WRITE A C PROGRAM TO INTERCHANGE THE VALUES OF TWO VARIABLES WITH AND WITHOUT USING TEMPORARY VARIABLE
#include<stdio.h> main() { int a,b temp; printf("input the values for a & b\n"); scanf("A=%d B=%d",&a,&b); printf("Interchanging with using the temporary variable\n"); temp=a; a=b; b=temp; printf("A=%d B=%d\n",a,b); printf("Interchanging without using the temporary variable\n"); b=a + b; a=b - a; b= b -a; printf("A =%d B=%d\n",a,b); } /* END OF PROGRAM*/
Output:
Input values for a & b: A=6 B = 4