AD4BP

The Case Control Structure

In real life we are often faced with situations where we are required to make a choice between a number of alternatives rather than only one or two. For example, which school to join or which hotel to visit or still harder which girl to marry (you almost always end up making a wrong decision is a different matter altogether!). Serious C programming is same; the choice we are asked to make is more complicated than merely selecting between two alternatives. C provides a special control statement that allows us to handle such cases effectively; rather than using a series of if statements. This control instruction is in fact the topic of this chapter. Towards the end of the chapter we would also study a keyword called goto, and understand why we should avoid its usage in C programming.

Decisions Using switch
The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows:

switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}
The integer expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to aninteger. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The “do this” lines in the above form of switch represent any valid C statement.
What happens when we run a program containing a switch? First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following that case, and all subsequent case and default statements as well. If no match is found with any of the case statements, only the statements following the default are executed. A few examples will show how this control structure works.
Consider the following program:

main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case 2
I am in case 3
I am in default


The output is definitely not what we expected! We didn’t expect the second and third line in the above output. The program prints case 2 and 3 and the default case. Well, yes. We said the switch executes the case where a match is found and all the subsequent cases and the default as well.
If you want that only case 2 should get executed, it is upto you to get out of the switch then and there by using a break statement. The following example shows how this is done. Note that there is no need for a break statement after the default, since the control comes out of the switch anyway.
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
break ;
case 2 :
printf ( "I am in case 2 \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case 2

Lesson 3: Variables and Data Types

During programming we need to store data. This data is stored in variables. Variables are locations in memory for storing data. The memory is divided into blocks. It can be viewed as pigeon-holes. You can also think of it as PO Boxes. In post offices there are different boxes and each has an address. Similarly in memory, there is a numerical address for each location of memory (block). It is difficult for us to handle these numerical addresses in our programs. So we give a name to these locations. These names are variables. We call them variables because they can contain different values at different times.
The variable names in C may be started with a character or an underscore ( _ ). But avoid starting a name with underscore ( _ ). C has many libraries which contain variables and function names normally starting with underscore ( _ ). So your variable name starting with underscore ( _ ) may conflict with these variables or function names.

In a program every variable has
o Name
o Type
o Size
o Value

The variables having a name, type and size (type and size will be discussed later) are just empty boxes. They are useless until we put some value in them. To put some value in these boxes is known as assigning values to variables. In C language, we use assignment operator for this purpose.
In C language equal-to-sign (=) is used as assignment operator. Do not confuse the algebraic equal-to with the assignment operator. In Algebra X = 2 means the value of X is 2, whereas in C language X = 2 (where X is a variable name) means take the value 2 and put it in the memory location labeled as X, afterwards you can assign some other value to X, for example you can write X = 10, that means now the memory location X contains the value 10 and the previous value 2 is no more there.

Data Types
A variable must have a data type associated with it, for example it can have data types like integer, decimal numbers, characters etc. The variable of type Integer stores integer values and a character type variable stores character value. The primary difference between various data types is their size in memory. Different data types have different sizes in memory depending on the machine and compilers. There are very few data types in C language. These data types are reserved words of C language. The reserve words can not be used as a variable name. Let’s take a look into different data types that the C language provides us to deal with whole numbers, real numbers and character data.

Whole Numbers
The C language provides three data types to handle whole numbers.
o int
o short
o long

The data type int is used to store whole numbers (integers). The integer type has a space of 4 bytes (32 bits for windows operating system) in memory. And it is mentioned as ‘int’ which is a reserved word of C, so we can not use it as a variable name. In programming before using any variable name we have to declare that variable with its data type. If we are using an integer variable named as ‘i’, we have to declare it as

int i ;

The above line is known as declaration statement. The declaration statement int i ; reserves 4 bytes of memory and labels it as ‘i’. This happens at the execution time.

We noted that the integer occupies four bytes in memory. So if we have to store a small integer like 5, 10 or 20, C provides another data type for storing small whole numbers which is called short. The size of short is two bytes and it can store numbers in range of -32768 to 32767. So if we are going to use a variable for which we know that it will not increase from 32767, for example the age of different people, then we use the data type short for age.

short age = 5;

On the other side if we have a very large whole number that cannot be stored in an int then we use the data type long provided by C. So when we are going to deal with very big whole numbers in our program, we use long data type. We use it in program as:

long x = 300500200;

Real Numbers
The C language provides two data types to deal with real numbers (numbers with decimal points e.g. 1.35, 735.251). The real numbers are also known as floating point numbers.
o float
o double

To store real numbers, float data type is used. The float data type uses four bytes to store
a real number. Here is program that uses float data types.

float f = 325.32501

If we need to store a large real number which cannot be store in four bytes, then we use double data type. Normally the size of double is twice the size of float. In program we use it as:
double x = 345624.769123;


char Data Type
So far we have been looking on data types to store numbers, In programming we do need to store characters like a,b,c etc. For storing the character data C language provides char data type. By using char data type we can store characters in variables. While assigning a character value to a char type variable single quotes are used around the character as ‘a’.

/* This program uses short data type to store values */
#include
main()
{
char x;
x = ’a’;
cout << “The character value in x = “;
cout << x;
}

Arithmetic Operators
In C language we have the usual arithmetic operators for addition, subtraction, multiplication and division. C also provides a special arithmetic operator which is called modulus. All these operators are binary operators which means they operate on two operands. So we need two values for addition, subtraction, multiplication, division and modulus.
Addition +
Subtraction -
Multiplication *
Division /
Modulus %

There is one thing to note in division that when we use integer division (i.e. both operands are integers) yields an integer result. This means that if, for example, you are dividing 5 by 2 (5 / 2) it will give integer result as 2 instead of actual result 2.5. Thus in integer division the result is truncated to the whole number, the fractional part (after decimal) is ignored. If we want to get the correct result, then we should use float data type. The modulus operator returns the remainder after division. This operator can only be used with integer operands. The expression x % y returns the remainder after x is divided by y. For example, the result of 5 % 2 will be 1, 23 % 5 will be 3 and 107%10 will be 7.

Precedence of Operators
The arithmetic operators in an expression are evaluated according to their precedence. The precedence means which operator will be evaluated first and which will be evaluated after that and so on. In an expression, the parentheses ( ) are used to force the evaluation order. The operators in the parentheses ( ) are evaluated first. If there are nested parentheses then the inner most is evaluated first. The expressions are always evaluated from left to right. The operators *, / and % have the highest precedence after parentheses. These operators are evaluated before + and –
operators. Thus + and – operators has the lowest precedence. It means that if there are * and + operators in an expression then first the * will be evaluated and then its result will be added to other operand. If there are * and / operators in an expression (both have the same precedence) then the operator which occurs first from left will be evaluated first and then the next, except you force any operator to evaluate by putting parentheses around it.

Lesson 2: First C Program

The best way to learn C is to start coding right away. So here is our very first program in C.
# include
main()
{
cout << "HELLO WORLD!"; } Let's see what the above snippet of code means. # include #include is a pre-processor directive. It is not part of our program; it is an instruction to the compiler. It tells the C compiler to include the contents of a file, in this case the system file iostream.h. The compiler knows that it is a system file, and therefore looks for it in a special place. The features of preprocessor will be discussed later. For the time being take this line on faith. You have to write this line. The sign # is known as HASH and also called SHARP.
is the name of the library definition file for all Input Output Streams. Your program will almost certainly want to send stuff to the screen and read things from the keyboard. iostream.h is the name of the file which has the code to do that work for you.

main()
The name main is special, in that the main is actually the one which is run when your program is used. A C program is made up of a large number of functions. Each of these is given a name by the programmer and they refer to each other as the program runs. C regards the name "main" as a special case and will run this function first. If you forget to have a main function, or mistype the name, the compiler will give you an error.

Notice that there are parentheses (“( )”, normal brackets) with main. Here the parentheses contain nothing. There may be something written inside the parentheses. It will be discussed in later lectures.

{}
Next, there is a curly bracket also called braces("{ }"). For every open brace there must be a matching close. Braces allows to group together pieces of a program. The body of main is enclosed in braces. Braces are very important in C; they enclose the blocks of the program.

cout
cout is known as out put stream in C and C++. Stream is a complicated thing, you will learn about it later. Think of a stream as a door. The data is transferred through stream, cout takes data from computer and sends it to the output. For the moment it is a screen of the monitor. hence we use cout for output.

<<
The sign << indicates the direction of data. Here it is towards cout and the function of cout is to show data on the screen.

“HELLO WORLD!”
The thing between the double quotes (“ ”) is known as character string. In C programming character strings are written in double quotes. Whatever is written after << and within quotation marks will be direct it to cout, cout will display it on the screen.

The semicolon (;) at the end of the above statement is very important. All C statements end with a semicolon (;). Missing of a semicolon (;) at the end of statement is a syntax error and compiler will report an error during compilation. If there is only a semicolon (;) on a line than it will be called a null statement. i.e. it does nothing. The extra semicolons may be put at the end but are useless and aimless

What is Programming?

Formally: "A program is a precise sequence of steps to solve a particular problem."
At its most basic level, programming a computer simply means telling it what to do. Without these instructions or programs computers are merely dumb machines. Computers are incredibly stupid. They do exactly what we tell them to do: no more, no less-- unlike human beings. Computers can't think by themselves. In this sense, they differ from human beings. For example, if someone asks you, “What is the time?”, “Time please?” or just, “Time?” you understand anyway that he is asking the time but computer is different. Instructions to the computer should be explicitly stated. Computer will tell you the time only if you ask it in the way you have programmed it. When you're programming, it helps to be able to "think'' as stupidly as the computer does, so that you are in the right frame of mind for specifying everything in minute detail, and not assuming that the right thing will happen by itself.

The Receipe of a good Program:
In order to design a program effectively and properly we must have a recipe to follow. In the book name ‘How to design programs’ by Matthias Felleisen and the co-worker, the idea of design recipe has been stated very elegenlty as “Learning to design programs is like learning to play soccer. A player must learn to trap a ball, to dribble with a ball, to pass, and to shoot a ball. Once the player knows those basic skills, the next goals are to learn to play a position, to play certain strategies, to choose among feasible strategies, and, on occasion, to create variations of a strategy because none fits.“ The author then continues to say that: “A programmer is also very much like an architect, a composers, or a writer. They are creative people who start with ideas in their heads and blank pieces of paper. They conceive of an idea, form a mental outline, and refine it on paper until their writings reflect their mental image as much as possible. As they bring their ideas to paper, they employ basic drawing, writing, and playing music to express certain style elements of a building, to describe a person's character, or to formulate portions of a melody. They can practice their trade because they have honed their basic skills for a long time and can use them on an instinctive level. Programmers also form outlines, translate them into first designs, and iteratively refine them until they truly match the initial idea. Indeed, the best programmers edit and rewrite their programs many times until they meet certain aesthetic standards. And just like soccer players, architects, composers, or writers, programmers must practice the basic skills of their trade for a long time before they can be truly creative. Design recipes are the equivalent of soccer ball handling techniques, writing techniques, arrangements, and drawing skills. “ Hence to design a program properly, we must:

o Analyze a problem statement, typically expressed as a word problem.
o Express its essence, abstractly and with examples.
o Formulate statements and comments in a precise language.
o Evaluate and revise the activities in light of checks and tests and
o Pay attention to detail.

All of these are activities are very useful for a programmer.

The above details are provided just for the sake of completeness and do not worry if the above sounds greek to you. it is natural. If, after going half of the course, you come back here then you will be in a perfect position to understand all of this. We have kept this boring detail to a limit. There were other topics like types of softwares, system software, application software, device drivers and the dry background of C programming language, which we have not included in this tutorial / guide. Our focus in this tutorial / guide is on programming C / C++.

Forms of if

The if statement can take any of the following forms:
(a) if ( condition )
do this ;
(b) if ( condition )
{
do this ;
and this ;
}
(c) if ( condition )
do this ;
else
do this ;
(d) if ( condition )
{
do this ;
and this ;
}
else
{
do this ;
and this ;
}
(e) if ( condition )
do this ;
else
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}
(f) if ( condition )
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}
else
do this ;

Nested if-elses

It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs. This is shown in the following program.
/* A quick demo of nested if-else */
main( )
{
int i ;
printf ( "Enter either 1 or 2 " ) ;
scanf ( "%d", &i ) ;
if ( i == 1 )
printf ( "You would go to heaven !" ) ;
else
{
if ( i == 2 )
printf ( "Hell was created with you in mind" ) ;
else
printf ( "How about mother earth !" ) ;
}
}

Note that the second if-else construct is nested in the first else statement. If the condition in the first if statement is false, then the condition in the second if statement is checked. If it is false as well, then the final else statement is executed.
You can see in the program how each time a if-else construct is nested within another if-else construct, it is also indented to add clarity to the program. Inculcate this habit of indentation, otherwise you would end up writing programs which nobody (you included) can understand easily at a later date.
In the above program an if-else occurs within the else block of the first if statement. Similarly, in some other program an if-else may occur in the if block as well. There is no limit on how deeply the ifs and the elses can be nested.

The if-else Statement

The if statement by itself will execute a single statement, or a group of statements, when the expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false? Of course! This is what is the purpose of the else statement that is demonstrated in the following example:
Example : In a company an employee is paid as under:
If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary.
/* Calculation of gross salary */
main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;
}

The Real Thing

We mentioned earlier that the general form of the if statement is as follows
if ( condition )
statement ;
Truly speaking the general form is as follows:
if ( expression )
statement ;
Here the expression can be any valid expression including a relational expression. We can even use arithmetic expressions in the if statement. For example all the following if statements are valid
if ( 3 + 2 % 5 )
printf ( "This works" ) ;
if ( a = 10 )
printf ( "Even this works" ) ;
if ( -5 )
printf ( "Surprisingly even this works" ) ;
Note that in C a non-zero value is considered to be true, whereas a 0 is considered to be false. In the first if, the expression evaluates to 5 and since 5 is non-zero it is considered to be true. Hence the printf( ) gets executed.
In the second if, 10 gets assigned to a so the if is now reduced to if ( a ) or if ( 10 ). Since 10 is non-zero, it is true hence again printf( ) goes to work.
In the third if, -5 is a non-zero number, hence true. So again printf( ) goes to work. In place of -5 even if a float like 3.14 were used it would be considered to be true. So the issue is not whether the number is integer or float, or whether it is positive or negative. Issue is whether it is zero or non-zero.

The if Statement

Like most languages, C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this:
if ( this condition is true )
execute this statement ;
The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. But how do we express the condition itself in C? And how do we evaluate its truth or falsity? As a general rule, we express a condition using C’s ‘relational’ operators. The relational operators allow us to compare two values to see whether they are equal to each other, unequal, or whether one is greater than the other. Here’s how they look and how they are evaluated in C.
thisThe relational operators should be familiar to you except for the equality operator == and the inequality operator !=. Note that = is used for assignment, whereas, == is used for comparison of two quantities. Here is a simple program, which demonstrates the use of if and the relational operators.
/* Demonstration of if statement */
main( )
{
int num ;
printf ( "Enter a number less than 10 " ) ;
scanf ( "%d", &num ) ;
if ( num <= 10 )
printf ( "What an obedient servant you are !" ) ;
}
On execution of this program, if you type a number less than or equal to 10, you get a message on the screen through printf( ). If you type some other number the program doesn’t do anything. The following flowchart would help you understand the flow of control in the program.

Write a programe to Calculation of simple interest in c language

#include< stdio.h >
#include< conio.h >

void main( )
{
int p, n ;
float r, si ;
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;

si = p * n * r / 100 ;
printf ( "%f" , si ) ;
getch();
}