Tuesday, September 29, 2009
Using Char along with Integer and Float
Example 1 : The error program
void main()
{
char grade;
int marks;
printf("\nEnter Grade : ");
scanf("%c",&grade);
printf("\nEnter Marks : ");
scanf("%d",&marks);
}
When you compile the above program, you will notice that the program terminates unexpectdly when the grade is entered without giving you the time to enter marks. The same problem arises when you try to use %c with %f. The solution of the problem is a function named "fflush()". Just put this function between
scanf("%c",&grade);
and
printf("\nEnter Marks : ");
The code should now look like this
Example 1 : The correct code rewrittrn using fflush(stdin)
void main()
{
char grade;
int marks;
printf("\nEnter Grade : ");
scanf("%c",&grade);
fflush(stdin);// stdin stands for Standard Input
printf("\nEnter Marks : ");
scanf("%d",&marks);
}
Run the program again and you will that the program is working perfectly and will allow you to enter the value of marks.
Whenever we want to enter a char after integer/float or vice versa, we'll to use fflush(stdin). It may be needed more than once in a program if there are multiple values to be entered of different types.
Accepting integer and float - Simple Interest Program
Example 1 : Simple Interest Program
void main()
{
int p;
float rate,time,si;
printf("\nEnter Principle Amount : ");
scanf("%d",&p); // %d for integer
printf("\nEnter Rate of Interest : ");
scanf("%f",&rate); // %f for float
printf("\nEnter Term : ");
scanf("%f",&time);
si=(p*rate*time)/100;
printf("\nSimple Interest %f",si);
}
Note :
- // denotes comments. The statements following // will not be processed by the compiler and will be treated as notes or comments.
- The ":" symbol used in printf() is not compulsory. It has been used just to provide a proper space to the user to enter values.
- Use clrscr() to make the previous output disappear.
So, as you can see there isn't any problem accepting both integers and floats in a program. Just make sure that you use proper specifiers.
Example 2 : The Salary Calculator
void main()
{
int salary;
float hra,pf,deduction,gross_income,net_income;
printf("\nEnter your basic salary : ");
scanf("%d",&salary);
hra=salary*3/100;
pf=hra+(salary*2/100); // calculated as hra + 2% of salary
gross_income=salary+hra+pf;
deduction=gross*3/100; // 3% of salary
net_income=gross_income-deduction;
printf("\nPRINTING DETAILS OF YOUR SALARY ");
printf("\============================");
printf("\nBasic Salary %d",salary);
printf("\nHouse Rent Allowance : %f",hra);
printf("\nProvident Fund : %f",pf):
printf("\nGross Salary %f",gross_salary);
printf("\deduction %f",deduction);
printf("\nNet Salary %f",net_income);
}
Note :
- All the formula's are imaginative.
- The first printf() and is used to print a heading of the program which is optional and so is the second printf() which is used a separator by typing the equal to ("=") sign.
Friday, September 25, 2009
Getting input from the user
#include
#include
void main()
{
float price,qty,total;
price=24.5;
qty=2;
total=price*qty;
printf("\nThe total bill is %d",total);
}
Whenever this program is compiled the result will always be 49. Why ? simple because the price has been set to 24.5 and qty to 2. This poses a big problem. What if the user wants to change the value of price or qty so that he/she can have different answer. The answer lies in the function "scanf()" which is used to accept input any value from the user so that we can different answer everytime.
Let the user input the value - The scanf function
The scanf() function expects the user to specify two thing a) The type of data b) The memory location where the value will be saved. Consider its syntax
scanf("%format",&varname);
The format part will be replaced by the specifiers like %d,%f,or %c as per the condition while varname will be replaced by the name of a variable. The "&" pronounced(ampersand) is called the "address of" operator will remain there only (more about it later).
Let's try to use scanf() and rewrite the above program
#include
#include
void main()
{
float price,qty,total;
printf("\nEnter price ");
scanf("%f",&price);
printf("\nEnter quantity ");
scanf("%f",&qty);
total=price*qty;
printf("\nThe total bill is %f",total);
}
Type the code and run it. You will will the following output
Enter price (Here the program will wait for you enter a value. Enter a valid value and press enter)
Enter quantity (the program will again wait for your input. Type a value and again hit the enter key)
Once you have entered the values the program will return to the code window (editor window). Press Alt + F5 to see that the output is the multiplication of the values entered by you and not 49 as it was previously. This is the advantage of scanf(). Whenever the program is compiled it will ask for the value of price and quantity from you and will display different results as per the values entered by you.
Basic Examples
Basic Examples using different datatypes
- To calculate area of a square when side is given
#include
#include
void main()
{
clrscr();
int side,area;
side=4;
area=side*side;
printf("Area of the square is %d",area);
} - To calculate area of a circle when radius is given
#include
#include
void main()
{
clrscr();
float radius,area;
radius=5.6;
area=3.14*radius*radius;
printf("\nArea of the circle is %f",area);
} - To calculate income tax of a person as 2% of his/her salary.
#include
#include
void main()
{
clrscr();
int salary;
float tax,netsalary;
salary=4000;
tax=salary*2/100;
netsalary=salary-tax;
printf("\nTotal Salary %d",salary);
printf("\nIncome Tax %f",tax);
printf("\nNet Salary %f",netsalary);
} - To print a char value
#include
#include
void main()
{
clrscr();
char c;
c='G';
printf("The alphabet is %c",c);
}
Points to remember
- The header file
is added for the clrscr() which clears the previous outputs from the screen. It can be omitted if we don't want to use clrscr(). - You can change the order of header files.
- "\n" is used to print the outputs on different lines. Removing \n will print all the messages in one line.
- %d is used whenever we want to print an integer value,%f is used to print a float(decimal) value while %c denotes a char variable.
- If we want to restrict the number of decimal positions to two we can add ".2" after the "%" sign in %f. For example, the statement
printf("\nNet Salary %.2f",netsalary);
will print only 2 decimal digits. Similarly we can %.3f or %.4f
Character Variables
Rules for creating character variables
- A character variable can not contain more than one character at a time. For example - 'E' is a valid character while 'Error' is not since it contains more than one character.
- Each character constant should be written inside a pair of single quoatations (' ')
Example
void main()
{
char alpha,beta,gamma;
alpha='G';
beta='4';
gamma='=';
printf("%c",alpha);
printf("%c",beta);
printf("%c",gamma);
}
Compile the above program using Ctrl+F9 and check the result using Alt+F5, you will see the following output
G4=
If you want to print all these character on seperate line put a '\n' inside all the printf() statements like, printf("\n%c",alpha);
Character and ASCII values
Observe the following code carefully.
void main()
{
char a='A';
printf("The character is %c",a);
printf("\nAscii value is %d",a);
}
The above program will print the following output
The character is A
Ascii value is 65
Why 'A' is printed is quite evident, because this is the value of the variable. If this same variable is printed using %d specifier it will print the ASCII(American Standard Code For Information Interchange) code of 'A' which is 65. This also proves that C treats all the characters as integers internally.
Thursday, September 24, 2009
Datatypes
Datatype | Range | Byte | Format Specifier | |
---|---|---|---|---|
signed char | -128 to + 127 | 1 | %c | |
unsigned char | 0 to 255 | 1 | %c | |
short signed int | -32768 to +32767 | 2 | %d | |
short unsigned int | 0 to 65535 | 2 | %u | |
signed int | -32768 to +32767 | 2 | %d | |
unsigned int | 0 to 65535 | 2 | %u | |
long signed int | -2147483648 to +2147483647 | 4 | %ld | |
long unsigned int | 0 to 4294967295 | 4 | %lu | |
float | -3.4e38 to +3.4e38 | 4 | %f | |
double | -1.7e308 to +1.7e308 | 8 | %lf | |
long double | -1.7e4932 to +1.7e4932 | 10 | %Lf |
The difference between signed and unsigned
If we know that a value will always be positive then we declare it using the keyword "unsigned". This will increase the the range of the integer from to 0 to 65535. This is quite useful when the value is sure to be positive.
Float or Int
Some freshers argue that if can use float to use integer values also then why do we use int. The answer lies in third column of the above table. An integer variable takes 2 bytes from the memory while a float variables uses 4 bytes. This means that an integer variable takes half the amount of memory if compared to a float variable.
Wednesday, September 23, 2009
How to name a variable
- The name of the variable shouldn't increase 31 characters in length. For example if you create a variable like
int abcdefghijklmnopqrstuvwxyz123456;
the compiler will flash an error since the length is exceeding 31 characters. - The first character of any variable must be an alphabet or underscore(Shift + Hyphenation). The following declaration therefore is invalid
int 1abc;
int #incorrect;
while the following is correct
int marks,int data,int _message; - Variable names must not contain a space or any other symbol except underscore.
- Variable names are case sensitive. Variable name,Name,NAME,nAme are treated as different.
- Names must be unique. Once you have used a variable name you can not use it again.
- You can not use a keyword as a variable name, for example keywords like void,int,main have a special meaning in C therefore the names must be userdefined.
Invalid variable names
1. auto
2. enum
3. int
4. return
5. switch etc.
Monday, September 21, 2009
Declaring and using variables.
datatype variablename
datatype can be either int(for real numbers), float (for decimal values),char (for single characters)
for example, the statement
int rollno
will declare a variables named "rollno" which can store an integer value, like 1,100,2493,-492 etc. Make sure that the value should not be more than 32767.
void main()
{
int a,b,c;
a=10;
b=20;
c=a+b;
printf("%d",c);
}
Type the whole code in the C editor window. Don't forget to add the includes (#include
Step By Step
- The first sentence #include
tells the compiler to add or load the header file standard input output(stdio) from the disc to RAM. Whatever you see on the screen is loaded into RAM and then shown, so it neccessary that this file must be brought from the secondary memory to the primary memory. If you fail to add the include statement the compiler will not be able to process the printf(). The "#" sign is called the "Preprocessor Directive" and it tells the compiler to process this statement before anything else. - The line "void main()" denotes the beginning of the program. You can also view it as the entry point of the program. The () denotes that main is a function(more about functions later) while void denotes that it a kind of function which doesn't return a value.
- int a,b,c --> are called declarations. Once a variable is declared it is ready to be used. You can define a variable as a temperory location or storage area in RAM which holds the value till a program is running. The name of the variables can be anything provided that you follow the rules of the language.
- a=10,b=20,c=a+b --> is called initialization or assignment. Here we are assigning the values to the variables declared in step 3. A is assigned a value of 10 , B is 20 while C will be storing the result of the addition of the two numbers.
- As the last step , the value of C is printed on the screen using the printf() statement. The symbol "%d" will not be printed on the screen it is just an identifier which tells the compiler that the value to be printed is an integer value. Instead of %d the value of the variable after the "," which is C, will be printed.
- Save the program by clicking on "File--> Save".
Things to remember
- Don't put a semicolon(';') after void main(). This will result in a compilation error.
- Pay extra care not to use capital letters except for the message written inside the printf() statement.
- The use of correct brackets is very important. The () - circular, [] sqaure, and {} curly brackets all have different meanings.
How to compile :
- Once you are done typing the program, now it is your turn to check the errors and see the output. For this , press Ctrl + F9 (for compiling) and Alt+F5 for seeing the output.
- Any change in the program must be followed by pressing Ctrl+F9 and Alt+F5 so that the changes can be seen.