AD4BP

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();
}

The First C Program

Armed with the knowledge about the types of variables, constants & keywords the next logical step is to combine them to form instructions. However, instead of this, we would write our first C program now. Once we have done that we would see in detail the instructions that it made use of.
Before we begin with our first C program do remember the following rules that are applicable to all C programs:

Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements.

The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.

Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.

All statements are entered in small case letters.
C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.

Every C statement must end with a ;. Thus ; acts as a statement terminator.
Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest.


/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n = 3 ;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}
Now a few useful tips about the program...

− Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments.

− Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written.

− Any number of comments can be written at any place in the program. For example, a comment can be written before the statement, after the statement or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;

− Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example:
/* formula for simple interest */
si = p * n * r / 100 ;

− Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential for other team members to understand it.

− Although a lot of comments are probably not necessary in this program, it is usually the case that programmers tend to use too few comments rather than too many. An adequate number of comments can save hours of misery and suffering when you later try to figure out what the program does.

− The normal language rules do not apply to text written within /* .. */. Thus we can type this text in small case, capital or a combination. This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler.

− Comments cannot be nested. For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid.

− A comment can be split over more than one line, as in,
/* This is
a jazzy
comment */
Such a comment is often called a multi-line comment.

− main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below.
main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}

− Technically speaking main( ) is a function. Every function has a pair of parentheses ( ) associated with it. We would discuss functions and their working in great detail in Chapter 5.

− Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;

− Any C statement always ends with a ;
For example,
float r, si ;
r = 8.5 ;

− In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is very rich in operators. There are about 45 operators available in C. Surprisingly there is no operator for exponentiation... a slip, which can be forgiven considering the fact that C has been developed by an individual, not by a committee.

− Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages, C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such
function is printf( ). We have used it display on the screen the value contained in si.
The general form of printf( ) function is,
printf ( "", ) ;
can contain,
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any other characters. These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Prin = 1000
Rate = 8.5
What is ‘\n’ doing in this statement? It is called newline and it takes the cursor to the next line. Therefore, you get the output split over two lines. ‘\n’ is one of the several Escape Sequences available in C.

printf( ) can not only print values of variables, it can also print the result of an expression. An expression is nothing but a valid combination of constants, variables and operators. Thus, 3, 3 + 2, c and a + b * c – d all are valid expressions. The results of these expressions can be printed as shown below:
printf ( "%d %d %d %d", 3, 3 + 2, c, a + b * c – d ) ;
Note that 3 and c also represent valid expressions.

C Keywords

Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called ‘Reserved words’.
There are only 32 keywords available in C. Figure 1.5 gives a list of these keywords for your ready reference. A detailed discussion of each of these keywords would be taken up in later chapters wherever their use is relevant.

Types of C Variables

As we saw earlier, an entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. These locations can contain integer, real or character constants. In any language, the types of variables that it can support depend on the types of constants that it can handle. This is because a particular type of variable can hold only the same type of constant. For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant.
The rules for constructing different types of constants are different. However, for constructing variable names of all types the same set of rules apply. These rules are given below.

Rules for Constructing Character Constants

A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, ’A’ is a valid character constant whereas ‘A’ is not.

The maximum length of a character constant can be 1 character.
Ex.: 'A'
'I'
'5'
'='

Rules for Constructing Real Constants

Real constants are often called Floating Point constants. The real constants could be written in two forms—Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional form:

1>A real constant must have at least one digit.

2>It must have a decimal point.

3>It could be either positive or negative.

4>Default sign is positive.

5>No commas or blanks are allowed within a real constant.
Ex.: +325.34
426.0
-32.76
-48.5792
The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. It however doesn’t restrict us in any way from using exponential form of representation for other real constants.

In exponential form of representation, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.
Following rules must be observed while constructing real constants expressed in exponential form:
1>The mantissa part and the exponential part should be separated by a letter e.

2>The mantissa part may have a positive or negative sign.

3>Default sign of mantissa part is positive.

4>The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive.

5>Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Ex.: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5

Rules for Constructing Integer Constants

1>An integer constant must have at least one digit.

2>It must not have a decimal point.

3>It can be either positive or negative.

4>If no sign precedes an integer constant it is assumed to be positive.

5>No commas or blanks are allowed within an integer constant.

6>The allowable range for integer constants is -32768 to 32767.
Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767. For a 32-bit compiler the range would be even greater. Question like what exactly do you mean by a 16-bit or a 32-bit compiler, what range of an Integer constant has to do with the type of compiler and such questions are discussed in detail in Chapter 16. Till that time it would be assumed that we are working with a 16-bit compiler.
Ex.: 426
+782
-8000
-7605

Types of C Constants

C constants can be divided into two major categories:

(a)Primary Constants
(b)Secondary Constants

C Constants

[1]Primary Constants
-Integer Constant
-Real Constant
-Character Constant
[2]Secondary Constants
-Array
-Pointer
-Structure
-Union
-Enum,etc.

Constants, Variables and Keywords

The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. Let us see what are ‘constants’ and ‘variables’ in C. A constant is an entity that doesn’t change whereas a variable is an entity that may change.
In any program we typically do lots of calculations. The results of these calculations are stored in computers memory. Like human memory the computer memory also consists of millions of cells. The calculated values are stored in these memory cells. To make the retrieval and usage of these values easy these memory cells (also called memory locations) are given names. Since the value stored in each location may change the names given to these locations are called variable names.

Write a programe for Calculation of simple interest

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

void main( )
{
int p, n ;
float r, si ;
clrscr();
p = 1000 ;
n = 3 ;
r = 8.5 ;

/* formula for simple interest */
si = p * n * r / 100 ;

printf ( "%f" , si ) ;
getch();
}

What is C

C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasn’t made the ‘official’ Bell Labs language. Thus, without any advertisement C’s reputation spread and its pool of users grew. Ritchie seems to have been rather surprised that so many programmers preferred C to older languages like FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that's what happened.
Possibly why C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than 3 decades has to be really good.
An opinion that is often heard today is – “C has been already superceded by languages like C++, C# and Java, so why bother to learn C today”. I seriously beg to differ with this opinion. There are several reasons for this:
I believe that nobody can learn C++ or Java directly. This is because while learning these languages you have things like classes, objects, inheritance, polymorphism, templates, exception handling, references, etc. do deal with apart from knowing the actual language elements. Learning these complicated concepts when you are not even comfortable with the basic language elements is like putting the cart before the horse. Hence one should first learn all the language elements very thoroughly using C language before migrating to C++, C# or Java. Though this two step learning process may take more time, but at the end of it you will definitely find it worth the trouble.
C++, C# or Java make use of a principle called Object Oriented Programming (OOP) to organize the program. This organizing principle has lots of advantages to offer. But even while using this organizing principle you would still need a good hold over the language elements of C and the basic programming skills.
Though many C++ and Java based programming tools and frameworks have evolved over the years the importance of C is still unchallenged because knowingly or unknowingly while using these frameworks and tools you would be still required to use the core C language elements—another good reason why one should learn C before C++, C# or Java.
Major parts of popular operating systems like Windows, UNIX, Linux is still written in C. This is because even today when it comes to performance (speed of execution) nothing beats C. Moreover, if one is to extend the operating system to work with new devices one needs to write device driver programs. These programs are exclusively written in C.
Mobile devices like cellular phones and palmtops are becoming increasingly popular. Also, common consumer devices like microwave oven, washing machines and digital cameras are getting smarter by the day. This smartness comes from a microprocessor, an operating system and a program embedded in this devices. These programs not only have to run fast but also have to work in limited amount of memory. No wonder that such programs are written in C. With these constraints on time and space, C is the language of choice while building such operating systems and programs.
You must have seen several professional 3D computer games where the user navigates some object, like say a spaceship and fires bullets at the invaders. The essence of all such games is speed. Needless to say, such games won't become popular if they takes a long time to move the spaceship or to fire a bullet. To match the expectations of the player the game has to react fast to the user inputs. This is where C language scores over other languages. Many popular gaming frameworks have been built using C language.
At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance it is the preferred choice of the programmer.
I hope that these are very convincing reasons why one should adopt C as the first and the very important step in your quest for learning programming languages.

Know about Comment

A comment is a piece of descriptive text which explains some aspect of a program. Program comments are totally ignored by the compiler and are only intended for human readers. C++ provides two types of comment delimiters:
* Anything after // (until the end of the line on which it appears) is considered a comment.
* Anything enclosed by the pair /* and */ is considered a comment.
Listing 1.6 illustrates the use of both forms.

Listing 1.6

#include < iostream.h >

/* This program calculates the weekly gross pay for a worker,
based on the total number of hours worked and the hourly pay
rate. */

int main (void)
{
int workDays = 5; // Number of work days per week
float workHours = 7.5; // Number of work hours per day
float payRate = 33.50; // Hourly pay rate
float weeklyPay; // Gross weekly pay

weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = " << weeklyPay << '\n'; }

Comments should be used to enhance (not to hinder) the readability of a program. The following two points, in particular, should be noted:
* A comment should be easier to read and understand than the code which it tries to explain. A confusing or unnecessarily-complex comment is worse than no comment at all.
* Over-use of comments can lead to even less readability. A program which contains so much comment that you can hardly see the code can by no means be considered readable.
* Use of descriptive names for variables and other entities in a program, and proper indentation of the code can reduce the need for using comments.
The best guideline for how to use comments is to simply apply common sense.

Write a programe for see the Effects of prefix and postfix notation

#include < iostream >
using namespace std;
int main()
{
int i(2), j(8);
cout << i++ << endl; // Output: 2
cout << i << endl; // Output: 3
cout << j-- << endl; // Output: 8
cout << --j << endl; // Output: 6
return 0;
}

Expressions

In its simplest form an expression consists of only one constant, one variable, or one
function call. Expressions can be used as the operands of operators to form more complex
expressions. An expression will generally tend to be a combination of operators and
operands.
Each expression that is not a void type returns a value. In the case of arithmetic
expressions, the operands define the type of the expression.
Examples: int a(4); double x(7.9);
a * 512 // Type int
1.0 + sin(x) // Type double
x – 3 // Type double, since one
// operand is of type double
An expression can be used as an operand in another expression.
Example: 2 + 7 * 3 // Adds 2 and 21
Normal mathematical rules (multiplication before addition) apply when evaluating an
expression, i.e. the *, /, % operators have higher precedence than + and -. In our example,
7*3 is first calculated before adding 2. However, you can use parentheses to apply a
different precedence order.
Example: (2 + 7) * 3 // Multiplies 9 by 3.

Binary Arithmetic Operators

Arithmetic operators are used to perform calculations. The opposite page shows an
overview. You should be aware of the following:
■ Divisions performed with integral operands will produce integral results; for example,
7/2 computes to 3. If at least one of the operands is a floating-point number,
the result will also be a floating-point number; e.g., the division 7.0/2 produces
an exact result of 3.5.
■ Remainder division is only applicable to integral operands and returns the remainder
of an integral division. For example, 7%2 computes to 1.

I/O Stream Classes

During the development of C++ a new class-based input/output system was implemented.
This gave rise to the I/O stream classes, which are now available in a library of
their own, the so-called iostream library.
The diagram on the opposite page shows how a so-called class hierarchy develops due
to inheritance. The class ios is the base class of all other stream classes. It contains the
attributes and abilities common to all streams. Effectively, the ios class
■ manages the connection to the physical data stream that writes your program’s
data to a file or outputs the data on screen
■ contains the basic functions needed for formatting data. A number of flags that
determine how character input is interpreted have been defined for this purpose.
The istream and ostream classes derived from ios form a user-friendly interface
for stream manipulation. The istream class is used for reading streams and the
ostream class is used for writing to streams. The operator >> is defined in istream
and << is defined in ostream, for example.
The iostream class is derived by multiple inheritance from istream and ostream
and thus offers the functionality of both classes.
Further stream classes, a file management class, for example, are derived from the
classes mentioned above. This allows the developer to use the techniques described for
file manipulation. These classes, which also contain methods for opening and closing
files, will be discussed in a later chapter.