Saturday, October 23, 2010

DataTypes in C Part-III

Data and C  

How much is 2563* 455 + 5067 – 3245 /2352? You will certainly need a lot of time to solve this problem! Your computer, on the other hand, can give you the result instantaneously. However, it cannot perform this kind of calculation unless you instruct or program it to do so. Read on if you wish to learn how to write these instructions.  
Writing programs to process data 
In previous articles, you learnt different ways of representing and storing data in a computer’s memory. You also learnt that a computer performs various operations to processes data and produce meaningful information. C offers a rich operator collection for performing various data processing operations. For example, you can perform arithmetic calculations, compare values, and modify variables. In this article, you will learn about arithmetic and other operators used in C programming. 

Arithmetic operators 

In C, arithmetic operations (addition, subtraction, multiplication, division, and modulo division) are performed using five arithmetic operators:. 
1.      +   - Addition
2.      -   - Subtraction
3.      *   - Multiplication
4.      /    - Division
            5.  % - Modulo Division (remainder after integer division)
 The following program uses all the five operators listed above.


  /* arithmetic operators */
#include<stdio.h>
main()
{
1.      int a=5,b=2; float c;
2.      printf(“Addition\n”);
3.      c=a+b;
4.      printf(“Result=%f\n”,c);
5.      printf(“Subtraction\n”);
6.      c=a-b;
7.      printf(“Result=%f\n”,c);
8.      printf(“Multiplication”);
9.      c=a*b;
10.  printf(“Result=%f\n”,c);
11.  printf(“Division\n”);
12.  c=a/b;
13.  printf(“Result=%f\n”,c);
}
 
 
 



 
 
 
 
 
 
 
 
 
 When you run this program, you will see this:
 
Addition
Result=7.000000
Subtraction
Result=3.000000
Multiplication
Result=10.000000
Division

Result=2.000000 

Observe the last output. The result of division is displayed as 2.000000 instead of 2.500000! What is the reason for this? Let us find out. 
Division works differently for ints and floats. Floating-point division results in a float, and integer division results in an int. In this example, the two variables involved in the division calculation are of integer type, and hence the result is an integer. In C, any fraction resulting from an integer division is ignored. This process is called truncation. This can be avoided using a mechanism called typecasting.  
Typecasting 
Typecasting allows you to convert the value of an expression to a particular data type. If you want the result of 5/2 in the above example as 2.5, you must type the code in line 12 as follows: 
c=(float) a/b; 
A pair of parentheses with a data type written inside is known as C’s cast operator. To print the output correctly, remember to change the format string in the printf() statement on line 13 from %d to %f.  

Expressions and operator precedence 

What is an expression? 
If you have done some basic math, you would have heard of expressions. An expression consists of a combination of operators and operands (values on which an operator operates on). For example 
c=a+b; 
or 
x=a*(b/c+d*3)+5; 
As you can see from the above expressions, operands can be constants, variables, or combinations of the two. 
In C, arithmetic expressions are evaluated according to a strict hierarchy of operators. Given below is the hierarchy of arithmetic operators in C: 
Priority
Operators
Description
 
 
 
1st
* / %
multiplication, division, modulo division
 
 
 
2nd
+ -
addition, subtraction
 
 
 
3rd
=
Assignment
If there are two operators of the same level in an expression, the operator that comes first is considered first — ‘first come, first served’. 

/*operator precedence */
#include<stdio.h>
main()
{
1.                  int a=10,b=20,c=15,d=5,result;
2.                  result=a+b%5-c*d/2;
3.                  printf(“Result=%d”,result);
}
 
 
 
 
 
 
 
 
 
 
 
 

When you run this program you will see this: 
Result=-27 
Let us see how you got this result. 
The expression result= a+b%5-c*d/2 is evaluated as follows: 
result=10+20%5-15*5/2
 
1. result=10+0-15*5/2    % is evaluated first. The remainder is 0 when 5 divides 20. 
2. result=10+0-75/2      Multiplication is performed. 15*5=75.
3. result=10+0-37         Division is performed. (75/2 results in 37 instead of 37.5 because both 75 and 2 are integers. 
4. result=10-37         Addition is performed because it comes before minus.
5. result=-27            Finally subtraction is performed and –27 is    stored in the variable result.
 Try these out: 
  1. Write a program to accept the marks of a student in three subjects, and display the total marks and the average.
  1. Write a program to accept basic salary, HRA, DA and PF and display the net salary. (Hint: Net salary is computed as: Basic+HRA+DA–PF).
  1. Write a program to accept the radius of a circle and display its radius and perimeter. (Hint: area=Õ*r*r; perimeter= 2*Õ*r)

Friday, October 22, 2010

Data Types in C Part-II

Data and C  

Suppose you develop a piece of software to be used for computerizing a bank’s operations. In the code for this software, you would write a program to store details of the bank’s customers. In this program let us assume that you have used the assignment operator (refer to the previous article) for storing customer details such as name, age and telephone number in the respective variables. How would you enter the details of a new customer?
You would do this by opening the program, assigning the values to variables, and compiling the program again. However, this is a cumbersome process, as you have to recompile the program each time that you make a change. Moreover, when using an assignment operator, you may not know in advance the values that you want to assign to the variables.
Data and input functions 
For the reasons mentioned above, almost every program should include statements used to request input from users while the program is running. Such statements are called input statements. The C compiler has built-in input functions for storing data (entered through a keyboard) in variables while the program is running. These input functions facilitate interactive programming, i.e., you can interact with a running program. One such widely used function in C is scanf(). 

The scanf() function 

The syntax of scanf() and that of printf() look alike except that an ‘&’ symbol precedes every variable in the case of scanf(). This function is used to input different kinds of values — int, float, and char. 
Read the following code. It demonstrates the use of the scanf() function:
/* Author: Globarena
    Purpose: demonstration of scanf() function
*/
main()
{
1.      int a;
2.      float b;
3.      char c;
4.      printf(“Enter an integer:”);
5.     scanf(“%d”,&a);
6.      printf(“Enter a float:”);
7.     scanf(“%f”,&b);
8.      printf(“Enter a character:”);
9.     scanf(“%c”,&c);
10.  printf(“You entered %d   %f   %c”, a, b, c);
}
 
When you run this program, it prompts you to enter first an integer, then a float, and finally a character. After you enter these values, the last printf() function displays all the three values entered. 
Other input functions 
Apart from the scanf() function, there are also other functions such as getchar() and gets() to store characters and strings (set of characters). The following program demonstrates the use of these functions.

/* Author: Globarena
    Purpose: This program accepts a character
    from the keyboard and displays it on the
    screen.  */
 
#include<stdio.h>
main ()
{
1.      char a;
2.      printf (“Enter any character:”);
3.      a=getchar();
4.      printf(“The character you entered is:%c”,a);
}
Observe how the function getchar() is used in this program. This function receives a character entered by the user and stores it in the variable a. The printf() function written  below the getchar() statement displays on the screen the character that you entered from the keyboard. C, however, also provides a function called putchar() to display the character on the screen. You can use this function in the above program instead of printf(). The following statement is written to use putchar() in the above program.
putchar(a);
 
 
Accepting strings using gets() function
In the previous articles, you saw a program that displayed a string (Hello, World) on the screen using the printf() function. Now you will see how to accept a string from keyboard and display it. 
Observe the following program.
/*Author: Globarena
   Purpose: This program accepts a string 
   from the keyboard and display’s it on the
   screen. */
 
#include <stdio.h>                      
main()                                       
{
1. char a[25];         
2. printf (“Enter a string:”);
3. gets(a);     
4. printf (“%s”,a);    
}
 
 
 
 
 
 
 
 
 In this program: 
  • The first statement — char a[25]; — informs the compiler to set aside 25 locations to store 25 characters.
  • The second statement prompts the user by displaying the message “Enter a string” on the screen.
  • The third statement accepts the string from the keyboard.
  • The fourth statement displays the string that you entered on the screen.
  • %s stands for ‘format string’ to print strings.
You can also get the same result for the above program by using another kind of output function, puts(). This function is used exclusively for handling strings. It can’t be used for printing numeric data. The following statement would be written to use puts() in the above program. 
puts(a);
 
 
 
 Try it out: 
1.   Write a program to accept and store the values 15, 30.5 and ‘A’ in the variables i, f, and c using the function scanf(), and to display them using the printf() function. 
2.  Write a program to accept and store a character (say, ‘$’) in the variable ch using the function getchar() and t display it on the screen using the function putchar(). 
3.  Write a program to accept and store a string (say, “Hi-Tech City”) in the variable city and to display it on the screen using the function puts().
 

Thursday, October 21, 2010

Data Types in C Part-I

Data and C  

Programming is all about processing data to get the desired results. Programs accept data and perform some kind of task. The task could be as simple as calculating percentage of marks or as complex as DNA fingerprint analysis. 
In this article, you will learn how C programs work with data and perform tasks. 
Data is generally defined as the raw facts input into the computer. However, in reference to C, data has a more specific meaning. It refers to two kinds of values — those associated with constants and those represented by variables. 
Variables and constants 
Constants refer to data that remains unchanged throughout the program execution. For example, in a program to find the area of a circle, the value of ∏ (3.1412) is constant. Some more examples of constants include numbers such as 10, 100, 22.34 and characters such as ’A’,’ ’Z’, ’*’ and ’$’.
Variables, on the other hand, store data that may vary during program execution. In the example of finding the area of a circle, the area will change from circle to circle.  
In programming, each variable actually refers to a memory location where a constant is stored. Every variable has a name. You should note the following rules before naming a variable: 
  1. Only alphabets, numerals, and underscores (_) are permitted (spaces and special symbols are not allowed).
  2. The name cannot start with a digit.
  3. Upper case and lower case letters are treated as different.
  4. A variable cannot be a C language keyword.
Note: Always choose meaningful names for variables.  
Examples of variable names: marks1, student_no, sum, product, etc.
Data types
The C compiler must be informed about the type of data (numbers, alphabets, or special characters) you intend to store in a variable. For this, you can use C’s built-in data types.  
There are three primary data types in C — int, float, and char. Other data types such as long and double are derived from these. 
The int data type 
The int data type can be used to store both positive and negative integers, and thus stands for ‘signed integer’. This data type also offers variations such as long and short to accommodate larger and smaller values. See Table 1 for information on the amount of memory this data type occupies and the range of values you can store). 
The float data type 
The float data type is used to store fractional numbers (real numbers). So, if you wish to write a program to compute something, you should use the float data type. A float value consists of an exponential and a fractional portion. Consider these values: 
2.3456e-1      =2.3456 x 10-1           = 0.23456
2.3456e+2     =2.3456 x 10+2         = 234.56
Here, the values to the left of the character ‘e’ denote the fraction while those to the right denote the exponent. The complier uses the ‘e’ to separate and identify these two components. The exponent must have a positive or negative value (positive by default). To accommodate larger fractions, C provides another data type called double. See Table 1 for the memory this data type occupies and the range of values you can store using float and double). 
The char data type 
The char data type is used for storing characters such as alphabets and special symbols (e.g. ‘*’, ‘$’, and ‘#’). Computers use a numerical code called ASCII (American Standard Code for Information Interchange) to represent these characters. There are 256 characters in the ASCII set, all of which can be stored using the char data type.   
Note: All the data types discussed above can be prefixed with the keywords signed or unsigned. The keyword signed represents both positive and negative values, whereas unsigned refers only to positive values.
            Table 1
Data type
Memory size (in bytes)
Range
int
2 or 4 (depends on whether you are using 16-bit processor or 32-bit processor)
-32,768 to +32767 (2-bytes)
-2,147,483,648 to +2,147,483,648 (4-bytes)
short
2
-32768 to +32767
long
4
-2,147,483,648 to +2,147,483,648
float
4
±10 e-37 to ±10e+37
double
8
±10 e-307 to ±10e+307
char
1
-128 to +127
 

Declaring variables in a C program 

As mentioned earlier, you have to inform the compiler about each variables name and the kind of data it is meant to store. This is called variable declaration. For example, you can create a variable called ‘num’ to store an integer value in memory by writing the statement: 
          int num;
Here, int is the data type and num is the name of the variable. 
Note: Before it is used in a program, a variable must be declared. Also, remember that variables should always be declared at the beginning of a function. 

Storing data in variables 

The easiest way to store a value in a variable named ‘num’ is by writing the statement num=value. 
Here, ‘=’ is called an assignment operator because it assigns a value to the variable. Writing 
num=10; 
indicates to the complier that the value ‘10’ should be stored in the ‘num’ variable. 
Note: You can use the assignment operator to store a value in a variable you are declaring. For example: 
          int number=10; 
Writing a program to print values in variables 
Now that you know how to store values in variables, let us write a program to print stored values on the screen. Consider this program:
/* Author: Globarena
    Date: 15/10/2003
    Purpose: To print values stored in variables
*/
#include<stdio.h>
main()
{
          int a=10;
          float b=3.1412;
          char ch=’A’;
          printf(“%d\n%f\n%c”,a,b,ch);
}
 
 
 
 
 
 
 
 
 
 


When you run this program, the following output will be displayed on screen: 
10
3.1412
A 
Observe how the printf() function is used in the program. Doesn’t it look different from the printf() used to print messages ? (See article 2.) You might also be wondering what those strange characters (%d, %f, \n, etc.) are.  
The characters %d, %f, and %c are called format specifiers or simply format strings. The ‘%’ symbol alerts the compiler that a variable is to be printed at that location and the letter that follows tells it to print the value as an int, float, char, and so on.  
The character ‘\n’ is called a newline character. It is used to insert a new line so that the values in variables mentioned after it are printed on a new line (as shown above). If this character is not used, the output will look as shown below: 
103.1412A 
This would be difficult to comprehend.  
Note: Characters like the ‘\n’ character that start with ‘\’ are called escape sequences.  
The following tables gives you a partial list of format strings and escape sequences that you will frequently come across in C programs.  
                   Table 2                                                                       Table 3
 
Sl. No
Data type
Format Specifier
 1.
int
d
2.
float
f
3.
char
c
4.
unsigned int
u
5.
string
s
6.
long int
ld
7.
double
lf
Sl. No
Escape sequence
Purpose
1.
\n
Newline
2.
\t
Tab
3.
\a
Beep
4.
\b
Backspace
5.
\r
Return

Try it out:
 
  1. Write a program to store 10, 12.5, and a character ‘Z’ in integer, float, and character variables respectively and display the values on the screen.
  1. Write a program to store 15, 3,14, and ’X’ in integer, float, and character variables respectively and display the values on separate lines on the screen.