Skip to main content

The Basics Of C Programming - Part 2.

A variable is just a named area of storage that can hold a single value (numeric or character). C is very fussy about how you create variables and what you store in them. It demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

There are five basic data types associated with variables:
int - integer: a whole number.
float - floating point value: i.e. a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type.

One of the confusing things about the C language is that the range of values and the amount of storage that each of these types takes is not defined. This is because in each case the 'natural' choice is made for each type of machine. You can call variables what you like, although it helps if you give them sensible names that give you a hint of what they're being used for - names like sum, total, average and so on.

Integer Number Variables
The first type of variable we need to know about is of class type int - short for integer. An int variable can store a value in the range -32768 to +32767. You can think of it as a largish positive or negative whole number: no fractional part is allowed. To declare an int, you can use the instruction:
int variable_name;


For example:
int a;
declares that you want to create an int variable called a.

To assign a value to our integer variable we use the following statement:
a=10;

The C programming language uses the "=" character for assignment. A statement of the form a=10; should be interpreted as take the numerical value 10 and store it in a memory location associated with the integer variable a. The "=" character should not be seen as an equality otherwise writing statements of the form:
a=a+10;

This statement should be interpreted as take the current value stored in a memory location associated with the integer variable a; add the numerical value 10 to it and then replace this value in the memory location associated with a.

Decimal Number Variables
C uses two keywords to declare a variable that is to be associated with a decimal number: float and double. They each offer a different level of precision as outlined below:

float: A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes four bytes to store.

double: A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double takes eight bytes to store.

For example:
float total;
double sum;

To assign a numerical value to our floating point and double precision variables we would use the following C statement:

total=0.0;
sum=12.50;

Character Variables
To declare a variable of type character we use the keyword char - a single character stored in one byte. For example:
char c;

If c is a char variable you can store the letter A in it using the C statement:
c='A'
Notice that you can only store a single character in a char variable.

Assignment Statement
Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see how C uses these operations on two float variables a and b.

add: a+b
subtract: a-b
multiply: a*b
divide: a/b

Be careful with the arithmetic! What is the answer to this simple calculation?
a=10/3

The answer depends upon how a was declared. If it was declared as type int the answer will be 3; if a is of type float then the answer will be 3.333.

Two points to note from the above calculation:
1)   C ignores fractions when doing integer division!
2)   When doing float calculations, integers will be converted into float.

Arithmetic Ordering
Consider the following calculation:
a=10.0 + 2.0 * 5.0 - 6.0 / 2.0

A computer has its own set of rules when performing an arithmetic calculation. In the above calculation the multiplication and division parts will be evaluated first and then the addition and subtraction parts. This gives an answer of 17.

You can freely mix int, float and double variables in expressions. In nearly all cases the lower precision values are converted to the highest precision values used in the expression. For example, the expression f*i, where f is a float and i is an int, is evaluated by converting the int to a float and then multiplying. The final result is, of course, a float but this may be assigned to another data type and the conversion will be made automatically. If you assign to a lower precision type then the value is truncated and not rounded. In other words, in nearly all cases you can ignore the problems of converting between types.

This is very reasonable but more surprising is the fact that the data type char can also be freely mixed with ints, floats and doubles. A character is represented as an ASCII or some other code in the range 0 to 255 and if you want you can use this integer code value in arithmetic. Another way of thinking about this is that a char variable is just a single-byte integer variable that can hold a number in the range 0 to 255, which can optionally be interpreted as a character. Consider the following instruction:

int x=10;
int y=25;
char z=x+y;
printf("Sum of x+y = %c", z);

produces the following output:
Sum of x+y= #
because the ASCII code of # is 35.

Something To Declare
You must declare the variable name before using it anywhere in the program, otherwise it will produce compilation error. You can declare any number of variables of the same type with a single statement. 
For example:
int a, b, c;

declares three integers: a, b and c. Exactly where you declare a variable makes a difference but for now you should put variable declarations after the opening curly bracket of the main program.

Here is an example program that includes some of the concepts outlined above. 

#include <stdio.h>
main()
{
int a,b,average;
a=10;
b=6;
average = ( a+b ) / 2 ;
printf("Here ");
printf("is ");
printf("the ");
printf("answer... ");
printf("\n");
printf("%d.",average);
}

You can assign an initial value to a variable when you declare it. 
For example:
int i=1;
sets the int variable to one as soon as it's created. 

This is just the same as:
int i;
i=1;  
but the compiler may be able to speed up the operation if you initialize the variable as part of its declaration.

Variable names:
a)    should be lowercase for local variables.
b)   should be uppercase for symbolic constants.
c)    only the first 31 characters of a variables name are significant.
d) must begin with a letter or _ (under score) character.

Popular posts from this blog

Introduction To Algorithms, 3rd Edition

Before there were computers, there were algorithms. But now that there are computers, there are even more algorithms, and algorithms lie at the heart of computing. This book provides a comprehensive introduction to the modern study of computer algorithms. It presents many algorithms and covers them in considerable depth, yet makes their design and analysis accessible to all levels of readers. In this book, the authors tried to keep explanations elementary without sacrificing depth of coverage or mathematical rigor. Each chapter presents an algorithm, a design technique, an application area, or a related topic. Algorithms are described in English and in a pseudocode designed to be readable by anyone who has done a little programming. The book contains 244 figures — many with multiple parts — illustrating how the algorithms work. It also includes careful analysis of the running times of all algorithms. In this third edition, the entire book once again updated including changes cove...

C Program To Check Whether A Number Is Palindrome Or Not.

This program takes an integer from user and the integer is reversed. If the reversed integer is equal to the integer entered by user then that number is a palindrome. If not that number is not a palindrome.   #include <stdio.h> int main()  { int num, temp, remainder, reverse = 0; printf("Enter an integer: "); scanf("%d", &num); /*  original number is stored at temp */ temp = num; while (num > 0)  { remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10;   }

The Basics Of C Programming - Part 3.

There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you can use: scanf("%d",&a); When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press Enter or Return, to signal that he, or she, has finished entering the value. Then the program continues with the new value stored in a. In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result! The final missing piece in the jigsaw is using the printf function, the one we use to print the value currently being stored in a variable. To display the value stored in the variable a you can use: printf("The value stored in a is %d",a); Note: the scanf function does not prompt for an input. You should ge...

C++ Program To Implement Bank Management System.

#include<iostream> #include<fstream> #include<cctype> #include<iomanip> #include <cstdlib> using namespace std; class account { int acno; char name[50]; int deposit; char type; public: void create_account(); //function to get data from user void show_account() const; //function to show data on screen void modify(); //function to add new data void dep(int); //function to accept amount and add to balance amount void draw(int); //function to accept amount and subtract from balance amount void report() const; //function to show data in tabular format int retacno() const; //function to return account number int retdeposit() const; //function to return balance amount char rettype() const;  //function to return type of account }; void account::create_account() { cout<<"\nEnter The Account No. : "; cin>>acno; cout<<"\n\nEnter The Name Of The Account Holder : "; cin.ig...