C Programming Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

lOMoAR cPSD| 12585645

UNIT I BASICS OF C PROGRAMMING

Introduction to programming paradigms - Structure of C program - C programming: Data Types


– Storage classes - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Pre-processor directives Compilation
process

Basic Information’s about programming

Computers are really dumb machines because they do only what they are told to do. The basic
operations of a computer system form the computer’s instruction set.

A computer program is just a collection of the instructions necessary to solve a specific problem.
The approach or method that is used to solve the problem is known as an algorithm.

For example: Develop a program that tests if a number is odd or even.

Normally, to develop a program to solve a particular problem, first express the solution to the
problem in terms of an algorithm and then develop a program that implements that algorithm.

The algorithm for solving the even/odd problem might be expressed as follows:
1. First, divide the number by two.
2. If the remainder of the division is zero, the number is even;
3. Otherwise, the number is odd.

With the algorithm in hand, proceed to write the instructions necessary to implement the
algorithm on a particular computer system. These instructions would be expressed in the
statements of a particular computer language, such as Visual Basic, Java, C++, or C.

Higher-Level Languages
When computers were first developed, the only way they could be programmed was in terms of
binary numbers that corresponded directly to specific machine instructions and locations in the
computer’s memory.
The next technological software advance occurred in the development of assembly languages,
which enabled the programmer to work with the machine on a slightly higher level.
Instead of having to specify sequences of binary numbers to carry out particular tasks, the
assembly language permits the programmer to use symbolic names to perform various operations
and to refer to specific memory locations.

A special program, known as an assembler, translates the assembly language program from its
symbolic format into the specific machine instructions of the computer system.

Different processor types have different instruction sets. Assembly language programs are written
using these instruction sets, the program will not run on a different processor type without being
rewritten. So they are machine dependent.
Assembly languages are regarded as low-level languages because the programmer must still learn
the instruction set of the particular computer system to write a program in assembly language, and
the resulting program is not portable too.
Higher-level languages came to overcome the machine dependent issue of low-level language.
FORTRAN (FORmula TRANslation) was the first higher-level language.

One FORTRAN instruction or statement resulted in many different machine instructions being
executed, unlike the one-to-one correspondence found between assembly language statements and
machine instructions.
Standardization of the syntax of a higher-level language meant that a program could be written
in the language to be machine independent. That is, a program could run on any machine that
supported the language with few or no changes.

To support a higher-level language, a special computer program must be developed that translates
the statements of the program in the higher-level language into particular instructions of the
computer. Such a program is known as a compiler.

An operating system is a program that controls the entire operation of a computer system. All
input and output (that is, I/O) operations that are performed on a computer system are channelled
through the operating system. The operating system must also manage the computer system’s
resources and must handle the execution of programs. Most popular operating systems today is
the Unix, Microsoft Windows XP.

Compiling Programs
A compiler analyzes a program developed in a particular computer language and then translates it
into a form that is suitable for execution on particular computer system.

Following figure shows the steps that are involved in entering, compiling, and executing a
computer program developed in the C programming language and the typical Unix commands that
would be entered from the command line.

The program that is to be compiled is first typed into a file on the computer system. A text editor
is usually used to enter the C program into a file. C programs can typically be given any name
provided the last two characters are “.c”.
For example, vi is a popular text editor used on Unix systems. The program that is entered into the
file is known as the source program because it represents the original form of the program
expressed in the C language. After the source program has been entered into a file, you can then
proceed to have it compiled.

In the first step of the compilation process, the compiler examines each program statement
contained in the source program and checks it to ensure that it conforms to the syntax and
semantics of the language1. If any mistakes are discovered by the compiler during this phase, they
are reported to the user and the compilation process ends right there.

The errors then have to be corrected in the source program (with the use of an editor), and the
compilation process must be restarted. Typical errors reported during this phase of compilation
might be due to an expression that has unbalanced parentheses (syntactic error), or due to the use
of a variable that is not “defined” (semantic error).

When all the syntactic and semantic errors have been removed from the program, the compiler
then proceeds to take each statement of the program and translate it into a “lower” form. On most
systems, this means that each statement is translated into the equivalent statements in assembly
language needed to perform the identical task.

The next step is, the assembler takes each assembly language statement and converts it into a
binary format known as object code, which is then written into another file on the system. This
file typically has the same name as the source file with the last letter an “o” (in unix) or “obj” (in
windows) instead of a “c”.

After the program has been translated into object code, it is ready to be linked. If the program uses
other programs that were previously processed by the compiler, then during this phase the
programs are linked together. Programs that are used from the system’s program library are also
searched and linked together with the object program during this phase.

The process of compiling and linking a program is often called building. The final linked file,
which is in an executable object code format, is stored in another file on the system, ready to be
run or executed. (In Unix, this file is called “a.out”, In Windows, same name as the source file,
with “exe” extension).

To subsequently execute the program, all you do is type in the name of the executable object file.
So, the command a.out has the effect of loading the program called a.out into the computer’s
memory and initiating its execution.

When the program is executed, each of the statements of the program is sequentially executed in
turn. If the program requests any data from the user, known as input, the program temporarily
suspends its execution so that the input can be entered. Or, the program might simply wait for an
event, such as a mouse being clicked, to occur.

Results that are displayed by the program, known as output, appear in a window, sometimes called
the console. Or, the output might be directly written to a file on the system.
If all goes well, the program performs its intended functions. If the program does not produce the
desired results, it is necessary to go back and reanalyze the program’s logic. This is known as the
debugging phase, during which an attempt is made to remove all the known problems or bugs
from the program.
To do this, it will most likely be necessary to make changes to the original source program. In that
case, the entire process of compiling, linking, and executing the program must be repeated until
the desired results are obtained.

Integrated Development Environments


The process of editing, compiling, running, and debugging programs is often managed by a single
integrated application known as an Integrated Development Environment, or IDE for short.

An IDE is a windows-based program that allows you to easily manage large software programs,
edit files in windows, and compile, link, run, and debug your programs.

Most IDEs also support program development in several different programming languages in
addition to C, such as C# and C++.

Example
• In Mac OS X, CodeWarrior and Xcode are two IDEs used.
• In Windows, Microsoft Visual Studio is a popular IDE.
• Kylix is a popular IDE for developing applications under Linux.

Compiler Vs Language Interpreters


There is another method used for analyzing and executing programs developed in a higher-level
language. With this method, programs are not compiled but are interpreted.

An interpreter analyzes and executes the statements of a program at the same time. This method
usually allows programs to be more easily debugged.

On the other hand, interpreted languages are typically slower than their compiled counterparts
because the program statements are not converted into their lowest-level form in advance of their
execution.

Example
• BASIC and Java are two programming languages in which programs are often
interpreted and not compiled.
• Other examples include the Unix system’s shell and Python.
• Some vendors also offer interpreters for the C programming language.

Programming paradigms

Programming paradigms are a way to classify programming languages based on their


features.
Languages can be classified into multiple paradigms.
Some paradigms are concerned mainly with implications for the execution model
of the language, such as allowing side effects, or whether the sequence of
operations is defined by the execution model.
Other paradigms are concerned mainly with the way that code is organized, such as
grouping a code into units along with the state that is modified by the code. Yet
others are concerned mainly with the style of syntax and grammar.
An execution model specifies how work takes place.
Every programming language has an execution model cover things such as What
is an indivisible unit of work?
What are the constraints on the order in which those units of work take place?
This order may be chosen ahead of time, or it can be dynamically determined as the
execution proceeds.
The implementation of an execution model can be via compiler, or interpreter, and
often includes a runtime system.

Example: C programming language has a concept called a statement. Statements are


indivisible units of work and that they proceed in the same order as their syntactic appearance
in the code (except when a control statement such as IF or WHILE modifies the order). The C
language actually has an additional level to its execution model, which is the order of
precedence. It states the rules for the order of operations within a single statement.

Side effects are the most common way that a program interacts with the outside world (people,
filesystems, other computers on networks). But the degree to which side effects are used
depends on the programming paradigm.

Common programming paradigms include:


1. Imperative which allows side effects.
2. Functional which disallows side effects.
3. Declarative which does not state the order in which operations execute.
4. Object-oriented which groups code together with the state the code modifies.
5. Procedural which groups code into functions.
6. Logic which has a particular style of execution model coupled to a particular style
of syntax and grammar.
7. Symbolic programming which has a particular style of syntax and grammar.

Imperative paradigm has two main features: they state the order in which operations occur and
they allow side effects. Most object-oriented languages are also imperative languages.
Declarative paradigm does not state the order in which to execute operations. Instead, they
supply a number of operations that are available in the system, along with the conditions under
which each is allowed to execute. The execution model tracks which operations are free to execute
and chooses the order on its own.

Languages support single/multiple paradigms


Some languages are designed to support one paradigm (Smalltalk supports objectoriented
programming, Haskell supports functional programming).
Multi paradigm supported languages can be purely procedural, purely object-oriented, or
can contain elements of both or other paradigms. Example: Object Pascal, C+
+, Java, C#, Scala, Visual Basic, Common Lisp, Scheme, Perl, PHP, Python, Ruby, Oz,
and F#). Software designers and programmers decide how to use those paradigm elements.
Introduction to C

C is a high-level structured oriented programming language used in general purpose programming,


developed by Dennis Ritchie at AT&T Bell labs, USA between 1969 and 1973.
Some Facts about C Programming Language
In 1988, the American National Standards Institute (ANSI) has formalized the C language.
C was invented to write UNIX operating system.
C is a successor of ‘Basic Combined Programming Language’ (BCPL) called B language.
Linux OS, PHP and MySQL is written in C.
C has been written in assembly language.
Uses of C Programming Language
In the beginning C was used for developing system applications e.g. : Database Systems,
Language Interpreters, Compilers and Assemblers, Operating Systems, Network Drivers, Word
Processors
C has Become Very Popular for Various Reasons
One of the early programming languages.
Still the best programming language to learn quickly.
C language is reliable, simple and easy to use.
C language is a structured language.
Modern programming concepts are based on C.
It can be compiled on a variety of computer platforms.
Universities preferred to add C programming in their courseware. Features of C
Programming Language
C is a robust language with rich set of built-in functions and operators.
Programs written in C are efficient and fast.
C is highly portable, programs once written in C can be run on another machines with
minor or no modification.
C is basically a collection of C library functions; we can also create our own function and
add it to the C library.
C is easily extensible.
Advantages of C
C is the building block for many other programming languages.
Programs written in C are highly portable.
Several standard functions are there (like in-built) that can be used to develop programs.
C programs are basically collections of C library functions, and it’s also easy to add own
functions in to the C library.
The modular structure makes code debugging, maintenance and testing easier.
Disadvantages of C
C does not provide Object Oriented Programming (OOP) concepts.
There is no concept of Namespace in C.
C does not provide binding or wrapping up of data in a single unit.
C does not provide Constructor and Destructor.
1. Documentation Section
- This is a comment block, which is ignored by the compiler. Comment can used
anywhere in program to add info about program or code block, which will be helpful for
developers to easily understand the existing code in the future. e.g. /* */, //
2. Link Section
-This Section is the core part of the programe in which compiler links the
inbuilt function from the system library. e.g. # include < >
3. Definition Section
-In this part, we define a symbolic constant.
e.g. define PI = 3.14
4. Global Declaration
-When programmer wants to use some variables that are used in more than one
function. The global declaration section is used to define those variables that are used
globally within the entire program and is used in more than one function.
5. Main( )
-The main() is the main function where program execution begins. Every C
program must contain only one main function. This section contains two parts.
-These two parts are declared within the opening and closing curly braces of the
main(). The execution of program begins at the opening brace ‘{‘ and ends with the
closing brace ‘}’.
-Also it has to be noted that all the statements of these two parts needs to be
terminated with semi-colon.
Declaration parts in which all variables and user defined functions are declared.
Execution part in which program logic and other process is done.

Two curly brackets “{…}” are used to group all statements together Or shows how much
the main() function has its scope.
6. Subprogram Section
-The sub-program section deals with all user defined functions that are called from the
main(). These user defined functions are declared and defined usually after the main()
function.
Compile & Run the first C program

#include <stdio.h>
int main (void)
{ printf ("Programming is
fun.\n"); return 0; }

Explanation about the First C Program

• In the C programming language, lowercase and uppercase letters are distinct.


• The first line of the program (Preprocessor directive) #include <stdio.h> should be
included at the beginning of just about every program you write. It tells the compiler
information about the printf output routine that is used later in the program.
• The line of the program that reads int main (void) informs the system that the name of the
program is main, and that it returns an integer value, which is abbreviated “int.” main is a
special name that indicates precisely where the program is to begin execution.
• The open and close parentheses immediately following main specify that main is the name
of a function.
• The keyword void that is enclosed in the parentheses specifies that the function main takes
no arguments (that is, it is void of arguments).
• All program statements included between the braces are taken as part of the main routine
by the system.
• The first statement specifies that a routine named printf is to be invoked or called. The
parameter or argument to be passed to the printf routine is the string of characters
"Programming is fun.\n"
• The printf routine is a function in the C library that simply prints or displays its argument
on output screen.
• The last two characters in the string, namely the backslash (\) and the letter n, are known
collectively as the newline character. A newline character tells the system to do precisely
what its name implies—that is, go to a new line.
• Any characters to be printed after the newline character then appear on the next line of the
display. In fact, the newline character is similar in concept to the carriage return key on a
typewriter.
• All program statements in C must be terminated by a semicolon (;).This is the reason for
the semicolon that appears immediately following the closing parenthesis of the printf call.
• The last statement in main that reads return 0;says to finish execution of main, and return
to the system a status value of 0.
• You can use any integer here. Zero is used by convention to indicate that the program
completed successfully—that is, without running into any errors. Different numbers can
be used to indicate different types of error conditions that occurred (such as a file not being
found). This exit status can be tested by other programs to see whether the program ran
successfully.

Displaying Multiple Lines of Output


#include <stdio.h>
int main (void)
{
printf ("Testing...\n..1\n...2\n....3\n");
return 0;
}

Output
Testing...
..1
...2
....3

Displaying Variables
#include <stdio.h>
int main (void)
{ int sum; sum = 50 + 25; printf ("The sum
of 50 and 25 is %i\n", sum); return 0; }

Output
The sum of 50 and 25 is 75

Comments
• A comment statement is used in a program to document a program and to enhance its
readability.
• There are two ways to insert comments into a C program.
• A comment can be initiated by the two characters / and *.This marks the beginning of the
comment. These types of comments have to be terminated. To end the comment, the
characters * and / are used without any embedded spaces. All characters included between
the opening /* and the closing */ are treated as part of the comment statement and are
ignored by the C compiler. This form of comment is often used when comments span
several lines in the program.

• The second way to add a comment to your program is by using two consecutive slash
characters //. Any characters that follow these slashes up to the end of the line are ignored
by the compiler.

Using Comments in a Program


/* This program adds two integer values
and displays the results */ #include
<stdio.h>
int main (void)
{
// Declare variables int
value1, value2, sum;
// Assign values and calculate their
sum value1 = 50; value2 = 25;
sum = value1 + value2; // Display the result printf ("The sum
of %i and %i is %i\n", value1, value2, sum); return 0; }

Output
The sum of 50 and 25 is 75
Exercises
1. Write a program that prints the following text at the terminal.
1. In C, lowercase letters are significant.
2. main is where program execution begins.
3. Opening and closing braces enclose program statements in a routine.
4. All program statements must be terminated by a semicolon.

2. What output would you expect from the following program?#include <stdio.h>
int main (void)
{
printf
("Testing...");
printf ("....1");
printf ("...2");
printf ("..3"); printf
("\n");
return 0;
}

3. Write a program that subtracts the value 15 from 87 and displays the result, together with
anappropriate message, at the terminal.

4. Identify the syntactic errors in the following program. Then type in and run the
correctedprogram to ensure you have correctly identified all the mistakes.
#include <stdio.h>
int main (Void)
(
INT sum;
/* COMPUTE RESULT
sum = 25 + 37 - 19
/* DISPLAY RESULTS //
printf ("The answer is %i\n" sum);
return 0;
}

5. What output might you expect from the following program?#include <stdio.h>
int main (void)
{
int answer, result;
answer = 100; result = answer - 10;
printf ("The result is %i\n", result + 5); return
0;
}
Working with Variables

Today’s programming languages allow you to concentrate more on solving the particular
problem rather than worrying about specific machine codes or memory locations.
Assign symbolic names for storing program computations and results in memory known
as variable names.
A variable name can be chosen by you.
The C language allows storing different types of data into the variables & proper
declaration for the variable is made before it is used in the program.
Variables can be used to store floating-point numbers, characters, and even pointers to
memory locations.

The rules for forming variable names are quite simple:


They must begin with a letter or underscore ( _ ) and can be followed by any combination
of letters (upper- or lowercase), underscores, or the digits 0–9.
Always remember that upper- and lowercase letters are distinct in C. (sum, Sum, SUM
each refer to a different variable)
In general, any name that has special significance to the C compiler cannot be used as a
variable name. (Example: reserved word like “int”)
Variable names can be as long as you want, although only the first 31 characters might be
significant.

Suggestions on choosing variable name


Pick names that reflect the intended use of the variable (i.e. type of value or purpose). The
reasons are obvious.
Just as with the comment statement, meaningful variable names can dramatically increase
the readability of a program and pay off in the debug and documentation phases.
In fact, the documentation task is probably greatly reduced because the program is more
self-explanatory.

List of valid variable names List of not valid variable names with reason
sum sum$value : $ is not a valid character. pieceFlag piece flag :
Embedded spaces are not permitted.
i 3Spencer : Variable names cannot start with a
J5x7 number.
Number_of_moves int : int is a reserved word/name.
_sysflag

Data Types and Constants

The C programming language provides five basic data types: float, double, char, and
_Bool.
A variable declared to be of type int can be used to contain integral values only—that is,
values that do not contain decimal places.
A variable declared to be of type float can be used for storing floating-point numbers
(values containing decimal places).
The double type is the same as type float, only with roughly twice the precision.
The char data type can be used to store a single character, such as the letter a, the digit
character 6, or a semicolon etc.
Finally, the _Bool data type can be used to store just the values 0 or 1. Variables of this
type are used for indicating an on/off, yes/no, or true/false situation.
Constants
Any number, single character, or character string is known as a constant.
For example, the number 58 represents a constant integer value.
The character string "Programming in C" is an example of a constant character string.
Expressions consisting entirely of constant values are called constant expressions. So, the
Expression 128 + 7 – 17 is a constant expression because each of the terms of the
expression is a constant value.

C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can
specify our constants in octal or hexadecimal, or force them to be treated as long integers.
• Octal constants are written with a leading zero - 015.
• Hexadecimal constants are written with a leading 0x - 0x1ae.
• Long constants are written with a trailing L - 890L.
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some
characters can't be represented in this way, so we use a 2 character sequence.

In addition, a required bit pattern can be specified using its octal equivalent.
'\044' produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A string constant
is surrounded by double quotes e.g. "Brian and Dennis". The string is actually stored as an array
of characters. The null character '\0' is automatically placed at the end of such a string to act as a
string terminator.
Constant is a special types of variable which can not be changed at the time of execution.
Syntax:
const int a=20;

Variable Storage Sizes and Ranges


Every value, whether it’s a character, integer, or floating-point number, has a range of
values associated with it. This range has to do with the amount of storage that is allocated
to store a particular type of data.
In general, that amount is not defined in the language. It typically depends on the computer
you’re running, and is machine-dependent. For example, an integer might take up 32 bits
on your computer, or it might be stored in 64.
You should never write programs that make any assumptions about the size of your data
types.
You are guaranteed that a minimum amount of storage will be set aside for each basic data
type. For example, it’s guaranteed that an integer value will be stored in a minimum of 32
bits of storage, which is the size of a “word” on many computers.
The Basic Integer Type int
In C, an integer constant consists of a sequence of one or more digits.
A minus sign preceding the sequence indicates that the value is negative.
The values 158, –10, and 0 are all valid examples of integer constants.
No embedded spaces are permitted between the digits, and values larger than 999 cannot
be expressed using commas. (So, the value 12,000 is not a valid integer constant and must
be written as 12000.)

Octal & Hexadecimal notation


Two special formats in C enable integer constants to be expressed in a base other than
decimal (base 10).
OCTAL:
o If the first digit of the integer value is a 0, the integer is taken as expressed in octal
notation—that is, in base 8. In that case, the remaining digits of the value must be
valid base-8 digits and, therefore, must be 0–7.
o So, to express the value 50 in base 8 in C, which is equivalent to the value 40 in
decimal, the notation 050 is used. Similarly, the octal constant 0177 represents the
decimal value 127 (1 × 64 + 7 × 8 + 7).
o An integer value can be displayed at the terminal in octal notation by using the
format characters %o in the format string of a printf statement. In such a case, the
value is displayed in octal without a leading zero.
o The format characters %#o does cause a leading zero to be displayed before an
octal value.

HEXADECIMAL:
o If an integer constant is preceded by a zero and the letter x (either lowercase or
uppercase), the value is taken as being expressed in hexadecimal (base 16)
notation. o Immediately following the letter x are the digits of the hexadecimal
value, which can be composed of the digits 0–9 and the letters a–f (or A–F). The
letters represent the values 10–15, respectively. So, to assign the hexadecimal value
FFEF0D to an integer variable called rgbColor, the statement rgbColor =
0xFFEF0D; can be used.
o The format characters %x display a value in hexadecimal format without the
leading 0x, and using lowercase letters a–f for hexadecimal digits.
o To display the value with the leading 0x, you use the format characters %#x, as in
the following: printf ("Color is %#x\n", rgbColor);
o An uppercase x, as in %X, or %#X can be used to display the leading x and the
hexadecimal digits that follow using uppercase letters.

The Floating Number Type float


A variable declared to be of type float can be used for storing values containing decimal
places. A floating-point constant is distinguished by the presence of a decimal point.
You can omit digits before the decimal point or digits after the decimal point, but obviously
you can’t omit both. The values 3., 125.8, and –.0001 are all valid examples of floating-
point constants. To display a floating-point value at the terminal, the printf conversion
characters %f is used.
Floating-point constants can also be expressed in scientific notation. The value 1.7e4 is a
floating-point value expressed in this notation and represents the value 1.7 × 10–4.
The value before the letter e is known as the mantissa, whereas the value that follows is
called the exponent. This exponent, which can be preceded by an optional plus or minus
sign, represents the power of 10 by which the mantissa is to be multiplied. So, in the
constant 2.25e–3, the 2.25 is the value of the mantissa and –3 is the value of the exponent.
This constant represents the value 2.25 × 10–3, or 0.00225. Incidentally, the letter e, which
separates the mantissa from the exponent, can be written in either lowercase or uppercase.

To display a value in scientific notation, the format characters %e should be specified in


the printf format string. The printf format characters %g can be used to let printf decide
whether to display the floating-point value in normal floating-point notation or in scientific
notation. This decision is based on the value of the exponent: If it’s less than –4 or greater
than 5, %e (scientific notation) format is used; otherwise, %f format is used.
Use the %g format characters for displaying floating-point numbers—it produces the most
aesthetically pleasing output.
A hexadecimal floating constant consists of a leading 0x or 0X, followed by one or more
decimal or hexadecimal digits, followed by a p or P, and followed by an optionally signed
binary exponent. For example, 0x0.3p10 represents the value 3/16 × 210 = 192.

The Extended Precision Type double


Type double is very similar to type float, but it is used whenever the range provided by a
float variable is not sufficient. Variables declared to be of type double can store roughly
twice as many significant digits as can a variable of type float.
Most computers represent double values using 64 bits.
Unless told otherwise, all floating-point constants are taken as double values by the C
compiler. To explicitly express a float constant, append either an f or F to the end of the
number, as follows: 12.5f
To display a double value, the format characters %f, %e, or %g, which is the same
format characters used to display a float value, can be used.

The Single Character Type char


A char variable can be used to store a single character.
A character constant is formed by enclosing the character within a pair of single quotation
marks. So 'a', ';', '0' are all valid examples of character constants.
The first constant represents the letter a, the second is a semicolon, and the third is the
character zero which is not the same as the number zero.
Do not confuse a character constant (a single character enclosed in single quotes) with a
character string (which is any number of characters enclosed in double quotes).
The character constant '\n' (the newline character) is a valid character constant even though
it seems to contradict the rule cited previously. This is because the backslash character is
a special character in the C system and does not actually count as a character.
There are other special characters that are initiated with the backslash character.
The format characters %c can be used in a printf call to display the value of a char variable
at the terminal.

The Boolean Data Type _Bool


A _Bool variable is defined to store just the values 0 and 1 that need to indicate a Boolean
condition. For example, a variable of this type might be used to indicate whether all data
has been read from a file.
By convention, 0 is used to indicate a false value, and 1 indicates a true value.
When assigning a value to a _Bool variable, a value of 0 is stored as 0 inside the variable,
whereas any nonzero value is stored as 1.
To make it easier to work with _Bool variables in program, the standard header file
<stdbool.h> defines the values bool, true, and false.
Using the Basic Data Types
#include <stdio.h>
int main (void)
{
int integerVar = 100; float
floatingVar = 331.79; double
doubleVar = 8.44e+11;
char charVar = 'W'; _Bool boolVar = 0;
printf ("integerVar = %i\n", integerVar);
printf ("floatingVar = %f\n",
floatingVar); printf ("doubleVar = %e\n",
doubleVar); printf ("doubleVar = %g\n",
doubleVar); printf ("charVar = %c\n",
charVar); printf ("boolVar = %i\n",
boolVar); return 0; }

Output
integerVar = 100
floatingVar = 331.790009
doubleVar =
8.440000e+11 doubleVar
= 8.44e+11 charVar = W
boolVar = 0;

Type Specifiers

Five Type Specifiers in C: long, long long, short, unsigned, and signed
If the specifier long is placed directly before the int declaration, the declared integer
variable is of extended range of memory on some computer systems. For example: long
int factorial; declares the variable factorial to be a long integer variable.
As with floats and doubles, the particular accuracy of a long variable depends on your
particular computer system.
On many systems, an int and a long int both have the same range and either can be used
to store integer values up to 32-bits wide (231 – 1, or 2,147,483,647).
A constant value of type long int is formed by optionally appending the letter L (upper-
or lowercase) onto the end of an integer constant. No spaces are permitted between the
number and the L. So, the declaration long int numberOfPoints = 131071100L; declares
the variable numberOfPoints to be of type long int with an initial value of 131,071,100.
To display the value of a long int using printf, the letter l is used as a modifier before the
integer format characters i, o, and x. This means that the format characters %li can be
used to display the value of a long int in decimal format, the characters %lo can display
the value in octal format, and the characters %lx can display the value in hexadecimal
format.
There is also a long long integer data type, so long long int maxAllowedStorage;
declares the indicated variable to be of the specified extended range, which is guaranteed
to be at least 64 bits wide. Instead of a single letter l, two ls are used in the printf string to
display long long integers, as in %lli.
The long specifier is also allowed in front of a double declaration, as follows: long
double US_deficit_2004; A long double constant is written as a floating constant with
the letter l or L immediately following, such as 1.234e+7L

To display a long double, the L modifier is used. So, %Lf displays a long double value
in floating-point notation, %Le displays the same value in scientific notation, and %Lg
tells printf to choose between %Lf and %Le.

The specifier short, when placed in front of the int declaration, tells the C compiler that
the particular variable being declared is used to store fairly small integer values. The
motivation for using short variables is primarily one of conserving memory space, which
can be an issue in situations in which the program needs a lot of memory and the amount
of available memory is limited.
On some machines, a short int takes up half the amount of storage as a regular int
variable does. In any case, you are guaranteed that the amount of space allocated for a
short int will not be less than 16 bits.
There is no way to explicitly write a constant of type short int in C.
To display a short int variable, place the letter h in front of any of the normal integer
conversion characters: %hi, %ho, or %hx.
Alternatively, you can also use any of the integer conversion characters to display short
ints, due to the way they can be converted into integers when they are passed as
arguments to the printf routine.
The final specifier that can be placed in front of an int variable is used when an integer
variable will be used to store only positive numbers.
The declaration unsigned int counter; declares to the compiler that the variable counter
is used to contain only positive values.
By restricting the use of an integer variable to the exclusive storage of positive integers,
the range of the integer variable is extended.
An unsigned int constant is formed by placing the letter u (or U) after the constant, as
follows: 0x00ffU
You can combine the letters u (or U) and l (or L) when writing an integer constant, so
20000UL tells the compiler to treat the constant 20000 as an unsigned long.
An integer constant that’s not followed by any of the letters u, U, l, or L and that is too
large to fit into a normal-sized int is treated as an unsigned int by the compiler. If it’s too
small to fit into an unsigned int, the compiler treats it as a long int. If it still can’t fit
inside a long int, the compiler makes it an unsigned long int. If it doesn’t fit there, the
compiler treats it as a long long int if it fits, and as an unsigned long long int otherwise.
When declaring variables to be of type long long int, long int, short int, or unsigned int,
you can omit the keyword int. Therefore, the unsigned variable counter could have been
equivalently declared as follows: unsigned counter;
You can also declare char variables to be unsigned. The signed qualifier can be used to
explicitly tell the compiler that a particular variable is a signed quantity. Its use is
primarily in front of the char declaration, and further discussion is deferred until Chapter
14,“More on Data Types.”
Table: Basic Data Types

Storage Classes

The term storage class refers to the manner in which memory is allocated to the variable
by the compiler and to the scope of a particular function definition.
A storage class defines the scope (visibility) and life-time of variables and functions within
a C Program.
Storage classes are auto, static, extern, and register.
A storage class can be omitted in a declaration and a default storage class is assigned
automatically.
An identifier defined outside any function or statement block can be referenced anywhere
subsequent in the file.
Identifiers defined within a BLOCK are local to that BLOCK and can locally redefine an
identifier defined outside it.
Label names are known throughout the BLOCK, as are formal parameter names.
Labels, structure and structure member names, union and union member names, and
enumerated type names do not have to be distinct from each other or from variable or
function names. However, enumeration identifiers do have to be distinct from variable
names and from other enumeration identifiers defined within the same scope.

The auto storage class is the default storage class for all local variables. The example
below defines two variables within the same storage class. 'auto' can only be used within
functions, i.e., local variables.
{
int mount;
auto int month;
}

The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register
size (usually one word) and can't have the unary '&' operator applied to it (as it does not
have a memory location). Eg: register int miles;
The register should only be used for variables that require quick access such as counters.
It should also be noted that defining 'register' does not mean that the variable will be stored
in a register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.

The static storage class instructs the compiler to keep a local variable in existence during
the life-time of the program instead of creating and destroying it each time it comes into
and goes out of scope. Therefore, making local variables static allows them to maintain
their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes
that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that
member to be shared by all the objects of its class.

/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}

/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}

OUTPUT
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
#include <stdio.h>

The extern storage class is used to give a reference of a global variable that is visible to
ALL the program files. When you use 'extern', the variable cannot be initialized however;
it points the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also
be used in other files, then extern will be used in another file to provide the reference of
defined variable or function. Just for understanding, extern is used to declare a global
variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition
in the first file, main.c. Output: count is 5

Storage class applied to Functions


If a storage class is specified when a function is defined, it must be either static or extern.
Functions that are declared as static can only be referenced from within the same file that
contains the function. Functions that are specified as extern (or that have no class specified) can
be called by functions from other files.

Storage class applied to Variables


The following table summarizes the various storage classes that can be used in declaring variables
as well as their scope and methods of initialization.

C Language Operator Precedence Chart


Operator precedence describes the order in which C reads expressions. For example, the
expression a=4+b*2 contains two operations, an addition and a multiplication. Does the C
compiler evaluate 4+b first, then multiply the result by 2, or does it evaluate b*2 first, then add 4
to the result? The operator precedence chart contains the answers. Operators higher in the chart
have a higher precedence, meaning that the C compiler evaluates them first. Operators on the same
line in the chart have the same precedence, and the "Associatively" column on the right gives their
evaluation order.

Operator Precedence Chart


Operator Type Operator Associatively

Primary Expression Operators () [] . -> expr++ expr-- left-to-right


Unary Operators * & + - ! ~ ++expr --expr (typecast) sizeof() right-to-left

*/%

+-

>> <<

< > <= >=

== !=
Binary Operators left-to-right
&

&&

||

Ternary Operator ?: right-to-left

Assignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-left

Comma , left-to-right
Operators Introduction
An operator is a symbol which helps the user to command the computer to do a certain
mathematical or logical manipulations. Operators are used in C language program to operate on
data and variables. C has a rich set of operators which can be classified as
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

1. Arithmetic Operators
All the basic arithmetic operations can be carried out in C. All the operators have almost the same
meaning as in other languages. Both unary and binary operations are available in C language.
Unary operations operate on a singe operand, therefore the number 5 when operated by unary –
will have the value –5.
Arithmetic Operators
Operator Meaning

+ Addition or Unary Plus

– Subtraction or Unary Minus

* Multiplication

/ Division

% Modulus Operator

Examples of arithmetic operators are


x + y x - y -x + y a * b + c
-a * b

etc.,

here a, b, c, x, y are known as operands. The modulus operator is a special operator in C


language which evaluates the remainder of the operands after division. Example

.
#include //include header file stdio.h
void main() //tell the compiler the start of the program
{
int numb1, num2, sum, sub, mul, div, mod; //declaration of variables scanf
(“%d %d”, &num1, &num2); //inputs the operands

sum = num1+num2; //addition of numbers and storing in sum.


printf(“\n Thu sum is = %d”, sum); //display the output

sub = num1-num2; //subtraction of numbers and storing in sub. printf(“\n


Thu difference is = %d”, sub); //display the output

mul = num1*num2; //multiplication of numbers and storing in mul. printf(“\n


Thu product is = %d”, mul); //display the output

div = num1/num2; //division of numbers and storing in div.


printf(“\n Thu division is = %d”, div); //display the output mod
= num1%num2; //modulus of numbers and storing in mod.
printf(“\n Thu modulus is = %d”, mod); //display the output
}
.
Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers than such an
operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y
= 5 be 2 integer numbers. Then the integer operation leads to the following results.

x + y = 32
x – y = 22
x * y = 115
x%y=2x
/y=5

In integer division the fractional part is truncated.

Floating point arithmetic


When an arithmetic operation is preformed on two real numbers or fraction numbers such an
operation is called floating point arithmetic. The floating point results can be truncated according
to the properties requirement. The remainder operator is not applicable for floating point
arithmetic operands. Let x = 14.0 and y = 4.0 then

x + y = 18.0 x
– y = 10.0 x *
y = 56.0 x / y
= 3.50

Mixed mode arithmetic


When one of the operand is real and other is an integer and if the arithmetic operation is carried
out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real
type then the result will always be real thus 15/10.0 = 1.5

2. Relational Operators
Often it is required to compare the relationship between operands and bring out a decision and
program accordingly. This is when the relational operator come into picture. C supports the
following relational operators.

Operato Meaning
r

< is less than

<= is less than or equal to

> is greater than

>= is greater than or equal


to

== is equal to
It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using
relational operators.

A simple relational expression contains only one relational operator and takes the following form.

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination
of them. Given below is a list of examples of relational expressions and evaluated values.

6.5 <= 25 TRUE


-65 > 0 FALSE
10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C language such as if, while and
for statements to decide the course of action of a running program.

3. Logical Operators
C has the following logical operators, they compare or evaluate logical and relational expressions.

Operato Meaning
r

&& Logical AND

|| Logical OR

! Logical NOT

Logical AND (&&)


This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is true
then the whole compound expression is true.

Example
a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is true only
if both expressions are true i.e., if a is greater than b and x is equal to 10.

Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of
the 2 expressions is true.

Example

a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates
to true if a is less than either m or n and when a is less than both m and n.

Logical NOT (!)


The logical not operator takes single expression and evaluates to true if the expression is false
and evaluates to false if the expression is true. In other words it just reverses the value of the
expression.

For example

! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or
equal to y

4. Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes it
to the value or variable on the left of the expression.

Example

x=a+b

Here the value of a + b is evaluated and substituted to the variable x. In

addition, C has a set of shorthand assignment operators of the form.

var oper = exp;

Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator
oper = is known as shorthand assignment operator

Example
x + = 1 is same as x = x + 1

The commonly used shorthand assignment operators are as follows Shorthand

assignment operators .
Statement with Statement with
simple shorthand
assignment operator
operator

a=a+1 a += 1

a=a–1 a -= 1

a = a * (n+1) a *= (n+1)

a = a / (n+1) a /= (n+1)

a=a%b a %= b

Example for using shorthand assignment operator


.
#define N 100 //creates a variable N with constant value 100
#define A 2 //creates a variable A with constant value 2

main() //start of the program


{
int a; //variable a declaration
a = A; //assigns value 2 to a

while (a < N) //while value of a is less than N


{ //evaluate or do the following
printf(“%d \n”,a); //print the current value of a
a *= a; //shorthand form of a = a * a
} //end of the loop
} //end of the program
.

Output

2
4
16
5. Increment and Decrement Operators
The increment and decrement operators are one of the unary operators which are very useful in C
language. They are extensively used in for and while loops. The syntax of the operators is given
below
1. ++ variable name
2. variable name++
3. – –variable name 4. variable name– –

The increment operator ++ adds the value 1 to the current value of operand and the decrement
operator – – subtracts the value 1 from the current value of operand. ++variable name and
variable name++ mean the same thing when they form statements independently, they behave
differently when they are used in expression on the right hand side of an assignment statement.

Consider the following .


m = 5; y = ++m;
(prefix)

In this case the value of y and m would be 6 Suppose

if we rewrite the above statement as

m = 5; y = m++;
(post fix)

Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand
and then the result is assigned to the variable on the left. On the other hand, a postfix operator
first assigns the value to the variable on the left and then increments the operand.

6. Conditional or Ternary Operator


The conditional operator consists of 2 symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows . exp1 ? exp2 : exp3

The ternary operator works as follows

exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the
value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression. Note that only one of the expression is evaluated. For example

a = 10; b = 15; x
= (a > b) ? a : b

Here x will be assigned to the value of b. The condition follows that the expression is false
therefore b is assigned to x.

.
/* Example : to find the maximum value using conditional operator)
#include
void main() //start of the program
{ int i,j,larger; //declaration of variables printf (“Input 2 integers : ”); //ask
the user to input 2 numbers scanf(“%d %d”,&i, &j); //take the number
from standard input and store it
larger = i > j ? i : j; //evaluation using ternary operator printf(“The largest of
two numbers is %d \n”, larger); // print the largest number } // end of the
program
.
Output
Input 2 integers : 34 45
The largest of two numbers is 45

7. Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for manipulation
data at bit level. A bitwise operator operates on each bit of data. Those operators are used for
testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied
to a float or double.

Operato Meaning
r

& Bitwise AND

| Bitwise OR

^ Bitwise
Exclusive

<< Shift left

>> Shift right

8. Special Operators
C supports some special operators of interest such as comma operator, size of operator, pointer
operators (& and *) and member selection operators (. and ->). The size of and the comma
operators are discussed here. The remaining operators are discussed in forth coming chapters.

The Comma Operator


The comma operator can be used to link related expressions together. A comma-linked list of
expressions are evaluated left to right and value of right most expression is the value of the
combined expression.

For example the statement


value = (x = 10, y = 5, x + y);

First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest
precedence in operators the parenthesis is necessary. Some examples of comma operator are

In for loops:
for (n=1, m=10, n <=m; n++,m++)
In while loops
While (c=getchar(), c != ‘10’) Exchanging
values.
t = x, x = y, y = t;

The size of Operator


The operator size of gives the size of the data type or variable in terms of bytes occupied in the
memory. The operand may be a variable, a constant or a data type qualifier.

Example
m = sizeof (sum); n
= sizeof (long int); k
= sizeof (235L);

The size of operator is normally used to determine the lengths of arrays and structures when their
sizes are not known to the programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.

Example program that employs different kinds of operators. The results of their evaluation are also
shown in comparision .

.main() //start of program


{
int a, b, c, d; //declaration of variables
a = 15; b = 10; c = ++a-b; //assign values to variables printf
(“a = %d, b = %d, c = %d\n”, a,b,c); //print the values
d=b++ + a; printf (“a = %d, b = %d, d = %d\n, a,b,d);
printf (“a / b = %d\n, a / b);
printf (“a %% b = %d\n, a % b);
printf (“a *= b = %d\n, a *= b);
printf (“%d\n, (c > d) ? 1 : 0 );
printf (“%d\n, (c < d) ? 1 : 0 ); }
Notice the way the increment operator ++ works when used in an expression. In the statement c
= ++a – b; new value a = 16 is used thus giving value 6 to C. That is a is incremented by 1
before using in expression.
However in the statement d = b++ + a; The old value b = 10 is used in the expression. Here b is
incremented after it is used in the expression.

We can print the character % by placing it immediately after another % character in the
control string. This is illustrated by the statement. printf(“a %% b = %d\n”, a%b);

This program also illustrates that the expression c


>d?1:0
Assumes the value 0 when c is less than d and 1 when c is greater than d.

Type conversions in expressions


Implicit type conversion
C permits mixing of constants and variables of different types in an expression. C automatically
converts any intermediate values to the proper type so that the expression can be evaluated
without loosing any significance. This automatic type conversion is know as implicit type
conversion .

During evaluation it adheres to very strict rules and type conversion. If the operands are of
different types the lower type is automatically converted to the higher type before the operation
proceeds. The result is of higher type.

The following rules apply during evaluating expressions


All short and char are automatically converted to int then
1. If one operand is long double, the other will be converted to long double and result .....will
be long double.
.2. If one operand is double, the other will be converted to double and result will be double.
.3. If one operand is float, the other will be converted to float and result will be float. .4. If
one of the operand is unsigned long int, the other will be converted into unsigned .....long
int and result will be unsigned long int.
.5. If one operand is long int and other is unsigned int then .
.....a. If unsigned int can be converted to long int, then unsigned int operand will be
..........converted as such and the result will be long int.
.....b. Else Both operands will be converted to unsigned long int and the result will be
..........unsigned long int.
.6. If one of the operand is long int, the other will be converted to long int and the result will be
long int. .
7. If one operand is unsigned int the other will be converted to unsigned int and the .....result
will be unsigned int.

Explicit Conversion
Many times there may arise a situation where we want to force a type conversion in a way that is
different from automatic conversion.

Consider for example the calculation of number of female and male students in a class
female_students Ratio = ------------------- male_students

Since if female_students and male_students are declared as integers, the decimal part will be
rounded off and its ratio will represent a wrong figure. This problem can be solved by converting
locally one of the variables to the floating point as shown below.

Ratio = (float) female_students / male_students

The operator float converts the female_students to floating point for the purpose of evaluation of
the expression. Then using the rule of automatic conversion, the division is performed by
floating point mode, thus retaining the fractional part of the result. The process of such a local
conversion is known as explicit conversion or casting a value. The general form is

(type_name) expression
Specifier Meaning
%c – Print a character
%d – Print a Integer
%i – Print a Integer
%e – Print float value in exponential form.
%f – Print float value
%g – Print using %e or %f whichever is smaller
%o – Print actual value
%s – Print a string
%x – Print a hexadecimal integer (Unsigned) using lower case a – F
%X – Print a hexadecimal integer (Unsigned) using upper case A – F
%a – Print a unsigned integer.
%p – Print a pointer value
%hx – hex short
%lo – octal long
%ld – long unsigned integer.

Input and Output


Input and output are covered in some detail. C allows quite precise control of these. This section
discusses input and output from keyboard and screen.
The same mechanisms can be used to read or write data from and to files. It is also possible to
treat character strings in a similar way, constructing or analysing them and storing results in
variables. These variants of the basic input and output commands are discussed in the next
section

• The Standard Input Output File


• Character Input / Output o
getchar o putchar
• Formatted Input / Output
o printf o
scanf
• Whole Lines of Input and Output
o gets o puts
printf
This offers more structured output than putchar. Its arguments are, in order; a control string,
which controls what gets printed, followed by a list of values to be substituted for entries in the
control string Example: int a,b; printf(“ a = %d,b=%d”,a,b);.

It is also possible to insert numbers into the control string to control field widths for values to be
displayed. For example %6d would print a decimal value in a field 6 spaces wide, %8.2f would
print a real value in a field 8 spaces wide with room to show 2 decimal places. Display is left
justified by default, but can be right justified by putting a - before the format information, for
example %-6d, a decimal integer right justified in a 6 space field

scanf scanf allows formatted reading of data from the keyboard. Like printf it has a control string,
followed by the list of items to be read. However scanf wants to know the address of the items to
be read, since it is a function which will change that value. Therefore the names of variables are
preceded by the & sign. Character strings are an exception to this. Since a string is already a
character pointer, we give the names of string variables unmodified by a leading &.
Control string entries which match values to be read are preceeded by the percentage sign in a
similar way to their printf equivalents. Example: int a,b; scan f(“%d%d”,& a,& b);

getchar
getchar returns the next character of keyboard input as an int. If there is an error then EOF (end of
file) is returned instead. It is therefore usual to compare this value against EOF before using it. If
the return value is stored in a char, it will never be equal to EOF, so error conditions will not be
handled correctly.
As an example, here is a program to count the number of characters read until an EOF is
encountered. EOF can be generated by typing Control - d.

#include <stdio.h>

main()
{ int ch, i = 0;

while((ch = getchar()) != EOF)


i ++;
printf("%d\n", i);
}

putchar putchar puts its character argument on the standard output (usually the
screen).
The following example program converts any typed input into capital letters. To do this it applies
the function to upper from the character conversion library c type .h to each character in turn.

#include <ctype.h> /* For definition of toupper */


#include <stdio.h> /* For definition of getchar, putchar, EOF */

main()
{ char ch;

while((ch = getchar()) != EOF)


putchar (toupper(ch));
}
gets gets reads a whole line of input into a string until a new line or EOF is encountered. It is
critical to ensure that the string is large enough to hold any expected input lines. When all input is
finished, NULL as defined in studio is returned.
#include <stdio.h>

main() { char
ch[20];

gets(x);
puts(x);
}
puts puts writes a string to the output, and follows it with a new line
character. Example: Program which uses gets and puts to double space
typed input.

#include <stdio.h>

main()
{ char line[256]; /* Define string sufficiently large to
store a line of input */

while(gets(line) != NULL) /* Read line */


{ puts(line); /* Print line */
printf("\n"); /* Print blank line */
}
}
Note that putchar, printf and puts can be freely used together
Expression Statements
Most of the statements in a C program are expression statements. An expression statement is
simply an expression followed by a semicolon. The lines
i = 0;
i = i + 1;
and printf("Hello, world!\n");
are all expression statements. (In some languages, such as Pascal, the semicolon separates
statements, such that the last statement is not followed by a semicolon. In C, however, the
semicolon is a statement terminator; all simple statements are followed by semicolons. The
semicolon is also used for a few other things in C; we've already seen that it terminates
declarations, too.
Branching and looping

CONTROL FLOW STATEMENT

IF- Statement:
It is the basic form where the if statement evaluate a test condition and direct program execution
depending on the result of that evaluation.

Syntax:

If (Expression)
{
Statement 1;
Statement 2;
}
Where a statement may consist of a single statement, a compound statement or nothing as an empty
statement. The Expression also referred so as test condition must be enclosed in parenthesis, which
cause the expression to be evaluated first, if it evaluate to true (a non zero value), then the statement
associated with it will be executed otherwise ignored and the control will pass to the next
statement.

Example:
if (a>b)
{
printf (“a is larger than b”);
}

IF-ELSE Statement:
An if statement may also optionally contain a second statement, the ``else clause,'' which is to be
executed if the condition is not met. Here is an example:
if(n > 0)
average = sum / n;
else {
printf("can't compute average\n");
average = 0;
}
NESTED - IF- Statement :
It's also possible to nest one if statement inside another. (For that matter, it's in general possible to
nest any kind of statement or control flow construct within another.) For example, here is a little
piece of code which decides roughly which quadrant of the compass you're walking into, based
on an x value which is positive if you're walking east, and a y value which is positive if you're
walking north:
if(x > 0) {
if(y > 0)
printf("Northeast.\n");
else printf("Southeast.\n");
}
else {
if(y > 0)
printf("Northwest.\n");
else printf("Southwest.\n");
}
/* Illustates nested if else and multiple arguments to the scanf function. */
#include <stdio.h>
main()
{ int invalid_operator = 0; char
operator; float number1,
number2, result;

printf("Enter two numbers and an operator in the


format\n"); printf(" number1 operator number2\n");
scanf("%f %c %f", &number1, &operator, &number2);

if(operator == '*')
result = number1 * number2;
else if(operator == '/') result =
number1 / number2;
else if(operator == '+') result =
number1 + number2;
else if(operator == '-') result =
number1 - number2;
else invalid _ operator = 1;

if( invalid _ operator != 1 ) printf("%f %c %f is %f\n", number1,


operator, number2, result ); else printf("Invalid operator.\n");
}

Sample Program Output


Enter two numbers and an operator in the format number1
operator number2
23.2 + 12
23.2 + 12 is 35.2

Switch Case
This is another form of the multi way decision. It is well structured, but can only be used in certain
cases where;
• Only one variable is tested, all branches must depend on the value of that variable. The
variable must be an integral type. (int, long, short or char).
• Each possible value of the variable can control a single branch. A final, catch all, default
branch may optionally be used to trap all unspecified cases.
Hopefully an example will clarify things. This is a function which converts an integer into a vague
description. It is useful where we are only concerned in measuring a quantity when it is quite
small.

estimate(number)
int number;
/* Estimate a number as none, one, two, several, many */
{ switch(number) {
case 0 :
printf("None\n");
break; case
1:
printf("One\n");
break; case
2:
printf("Two\n");
break; case 3 :
case 4 : case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}
Each interesting case is listed with a corresponding action. The break statement prevents any
further statements from being executed by leaving the switch. Since case 3 and case 4 have no
following break, they continue on allowing the same action for several values of number. Both if
and switch constructs allow the programmer to make a selection from a number of possible actions.

Loops
Looping is a way by which we can execute any some set of statements more than one times
continuously .In c there are mainly three types of loops are use :
• while Loop
• do while Loop
For Loop While
Loop
Loops generally consist of two parts: one or more control expressions which (not surprisingly)
control the execution of the loop, and the body, which is the statement or set of statements which
is executed over and over.
The general syntax of a while loop is Initialization
while( expression )
{
Statement1
Statement2
Statement3

The most basic loop in C is the while loop. A while loop has one control expression, and executes
as long as that expression is true. This example repeatedly doubles the number 2 (2, 4, 8, 16, ...)
and prints the resulting numbers as long as they are less than 1000:
int x = 2;
while(x < 1000)
{
printf("%d\n", x);
x = x * 2;
}
(Once again, we've used braces {} to enclose the group of statements which are to be executed
together as the body of the loop.)

For Loop
Our second loop, which we've seen at least one example of already, is the for loop. The general
syntax of a while loop is

for( Initialization;expression;Increments/decrements )
{
Statement1
Statement2
Statement3

The first one we saw was:


for (i = 0; i < 10; i = i + 1) printf
("i is %d\n", i);
(Here we see that the for loop has three control expressions. As always, the statement can be a
brace-enclosed block.)
Do while Loop
This is very similar to the while loop except that the test occurs at the end of the loop body. This
guarantees that the loop is executed at least once before continuing. Such a setup is frequently
used where data is to be read. The test then verifies the data, and loops back to read again if it was
unacceptable.

do
{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0)

The break Statement


We have already met break in the discussion of the switch statement. It is used to exit from a loop
or a switch, control passing to the first statement beyond the loop or a switch.
With loops, break can be used to force an early exit from the loop, or to implement a loop with a
test to exit in the middle of the loop body. A break within a loop should always be protected within
an if statement which provides the test to control the exit condition.
The continue Statement
This is similar to break but is encountered less frequently. It only works within loops where its
effect is to force an immediate jump to the loop control statement.
• In a while loop, jump to the test statement.
• In a do while loop, jump to the test statement.
• In a for loop, jump to the test, and perform the iteration.
Like a break, continue should be protected by an if statement. You are unlikely to use it very
often.
Take the following example:

int i;
for (i=0;i<10;i++)
{

if (i==5)
continue;
printf("%d",i);
if (i==8)
break; }

This code will print 1 to 8 except 5.

Continue means, whatever code that follows the continue statement WITHIN the loop code
block will not be exectued and the program will go to the next iteration, in this case, when the
program reaches i=5 it checks the condition in the if statement and executes 'continue',
everything after continue, which are the printf statement, the next if statement, will not be
executed.

Break statement will just stop execution of the look and go to the next statement after the loop if
any. In this case when i=8 the program will jump out of the loop. Meaning, it wont continue till
i=9, 10.

Comment: o The compiler is "line oriented", and parses your program in a line-by-line
fashion. o There are two kinds of comments: single-line and multi-line comments.
o The single-line comment is indicated by "//"
This means everything after the first occurrence of "//", UP TO THE END OF
CURRENT LINE, is ignored.
o The multi-line comment is indicated by the pair "/*" and "*/".
This means that everything between these two sequences will be ignored. This may
ignore any number of lines.
Here is a variant of our first program:
/* This is a variant of my first program.
* It is not much, I admit.
*/ int main() { printf("Hello
World!\n"); // that is all? return(0); }
C - PREPROCESSOR

Overview
The C preprocessor, often known as cpp, is a macro processor that is used automatically by the C
compiler to transform your program before compilation. It is called a macro processor because it
allows you to define macros, which are brief abbreviations for longer constructs.
The C preprocessor is intended to be used only with C, C++, and Objective-C source code. In the
past, it has been abused as a general text processor. It will choke on input which does not obey C's
lexical rules. For example, apostrophes will be interpreted as the beginning of character constants,
and cause errors. Also, you cannot rely on it preserving characteristics of the input which are not
significant to C-family languages. If a Makefile is preprocessed, all the hard tabs will be removed,
and the Makefile will not work.
Having said that, you can often get away with using cpp on things which are not C. Other Algolish
programming languages are often safe (Pascal, Ada, etc.) So is assembly, with caution. -
traditional-cpp mode preserves more white space, and is otherwise more permissive. Many of the
problems can be avoided by writing C or C++ style comments instead of native language
comments, and keeping macros simple

Include Syntax
Both user and system header files are included using the preprocessing directive `#include'. It has
two variants: #include <file>

This variant is used for system header files. It searches for a file named file in a standard
list of system directories. You can prepend directories to this list with the -I option (see
Invocation).

#include "file"

This variant is used for header files of your own program. It searches for a file named file
first in the directory containing the current file, then in the quote directories and then the
same directories used for <file>. You can prepend directories to the list of quote
directories with the -iquote option.

The argument of `#include', whether delimited with quote marks or angle brackets, behaves like a
string constant in that comments are not recognized, and macro names are not expanded. Thus,
#include <x/*y> specifies inclusion of a system header file named x/*y.
However, if backslashes occur within file, they are considered ordinary text characters, not escape
characters. None of the character escape sequences appropriate to string constants in C are
processed. Thus, #include "x\n\\y" specifies a filename containing three backslashes. (Some
systems interpret `\' as a pathname separator. All of these also interpret `/' the same way. It is most
portable to use only `/'.)
It is an error if there is anything (other than comments) on the line after the file name.

Object-like Macros
An object-like macro is a simple identifier which will be replaced by a code fragment. It is called
object-like because it looks like a data object in code that uses it. They are most commonly used
to give symbolic names to numeric constants.
You create macros with the `#define' directive. `#define' is followed by the name of the macro and
then the token sequence it should be an abbreviation for, which is variously referred to as the
macro's body, expansion or replacement list. For example,
#define BUFFER_SIZE 1024
defines a macro named BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after
this `#define' directive there comes a C statement of the form .
foo = (char *) malloc (BUFFER_SIZE); then the C preprocessor will recognize and expand the
macro BUFFER_SIZE. The C compiler will see the same tokens as it would if you had written .
foo = (char *) malloc (1024);
By convention, macro names are written in uppercase. Programs are easier to read when it is
possible to tell at a glance which names are macros.
The macro's body ends at the end of the `#define' line. You may continue the definition onto
multiple lines, if necessary, using backslash-newline. When the macro is expanded, however, it
will all come out on one line. For example,
#define NUMBERS 1, \
2, \
3
int x[] = { NUMBERS };
==> int x[] = { 1, 2, 3 };
The most common visible consequence of this is surprising line numbers in error messages. There
is no restriction on what can go in a macro body provided it decomposes into valid preprocessing
tokens. Parentheses need not balance, and the body need not resemble valid C code. (If it does not,
you may get error messages from the C compiler when you use the macro.) The C preprocessor
scans your program sequentially. Macro definitions take effect at the place you write them.
Therefore, the following input to the C preprocessor foo = X; #define X 4 bar = X;
produces foo = X; bar = 4;
When the preprocessor expands a macro name, the macro's expansion replaces the macro
invocation, then the expansion is examined for more macros to expand. For example,
#define TABLESIZE BUFSIZE
#define BUFSIZE 1024
TABLESIZE
==> BUFSIZE
==> 1024
TABLESIZE is expanded first to produce BUFSIZE, then that macro is expanded to produce the
final result, 1024.
Notice that BUFSIZE was not defined when TABLESIZE was defined. The `#define' for
TABLESIZE uses exactly the expansion you specify—in this case, BUFSIZE—and does not
check to see whether it too contains macro names. Only when you use TABLESIZE is the result
of its expansion scanned for more macro names.
This makes a difference if you change the definition of BUFSIZE at some point in the source file.
TABLESIZE, defined as shown, will always expand using the definition of BUFSIZE that is
currently in effect:
#define BUFSIZE 1020
#define TABLESIZE BUFSIZE
#undef BUFSIZE
#define BUFSIZE 37

Conditional Syntax
A conditional in the C preprocessor begins with a conditional directive: `#if', `#ifdef' or `#ifndef'.
Ifdef
• If
• Defined
• Else
• Elif

Ifdef
The simplest sort of conditional is
#ifdef MACRO

controlled text

#endif /* MACRO */
This block is called a conditional group. controlled text will be included in the output of the
preprocessor if and only if MACRO is defined. We say that the conditional succeeds if MACRO
is defined, fails if it is not.
The controlled text inside of a conditional can include preprocessing directives. They are executed
only if the conditional succeeds. You can nest conditional groups inside other conditional groups,
but they must be completely nested. In other words, `#endif' always matches the nearest `#ifdef'
(or `#ifndef', or `#if'). Also, you cannot start a conditional group in one file and end it in another.
Even if a conditional fails, the controlled text inside it is still run through initial transformations
and tokenization. Therefore, it must all be lexically valid C. Normally the only way this matters is
that all comments and string literals inside a failing conditional group must still be properly ended.
The comment following the `#endif' is not required, but it is a good practice if there is a lot of
controlled text, because it helps people match the `#endif' to the corresponding `#ifdef'. Older
programs sometimes put MACRO directly after the `#endif' without enclosing it in a comment.
This is invalid code according to the C standard. CPP accepts it with a warning. It never affects
which `#ifndef' the `#endif' matches.
Sometimes you wish to use some code if a macro is not defined. You can do this by writing
`#ifndef' instead of `#ifdef'. One common use of `#ifndef' is to include code only the first time a
header file is included. See Once-Only Headers.

If
The `#if' directive allows you to test the value of an arithmetic expression, rather than the mere
existence of one macro. Its syntax is
#if expression

controlled text

#endif /* expression */
expression is a C expression of integer type, subject to stringent restrictions. It may contain
Integer constants.
• Character constants, which are interpreted as they would be in normal code.
• Arithmetic operators for addition, subtraction, multiplication, division, bitwise operations,
shifts, comparisons, and logical operations (&& and ||). The latter two obey the usual short-
circuiting rules of standard C.
• Macros. All macros in the expression are expanded before actual computation of the
expression's value begins.
• Uses of the defined operator, which lets you check whether macros are defined in the
middle of an `#if'.
• Identifiers that are not macros, which are all considered to be the number zero. This allows
you to write #if MACRO instead of #ifdef MACRO, if you know that MACRO, when
defined, will always have a nonzero value. Function-like macros used without their
function call parentheses are also treated as zero.

Defined
The special operator defined is used in `#if' and `#elif' expressions to test whether a certain name
is defined as a macro. defined name and defined (name) are both expressions whose value is 1 if
name is defined as a macro at the current point in the program, and 0 otherwise. Thus, #if defined
MACRO is precisely equivalent to #ifdef MACRO. defined is useful when you wish to test more
than one macro for existence at once. For example,
#if defined (__vax__) || defined (__ns16000__) would succeed if either of the
names __vax__ or __ns16000__ is defined as a macro.
Conditionals written like this:
#if defined BUFSIZE && BUFSIZE >= 1024 can generally be simplified to just #if
BUFSIZE >= 1024, since if BUFSIZE is not defined, it will be interpreted as having the
value zero.
If the defined operator appears as a result of a macro expansion, the C standard says the behavior
is undefined. GNU cpp treats it as a genuine defined operator and evaluates it normally. It will
warn wherever your code uses this feature if you use the command-line option -pedantic, since
other compilers may handle it differently.

Else
The `#else' directive can be added to a conditional to provide alternative text to be used if the
condition fails. This is what it looks like:
#if expression text-if-
true
#else /* Not expression */ text-if-
false
#endif /* Not expression */
If expression is nonzero, the text-if-true is included and the text-if-false is skipped. If expression
is zero, the opposite happens.
You can use `#else' with `#ifdef' and `#ifndef', too. Elif
One common case of nested conditionals is used to check for more than two possible alternatives.
For example, you might have #if X == 1
...
#else /* X != 1 */
#if X == 2
...
#else /* X != 2 */
...
#endif /* X != 2 */
#endif /* X != 1 */
Another conditional directive, `#elif', allows this to be abbreviated as follows:
#if X == 1
...
#elif X == 2
...
#else /* X != 2 and X != 1*/
...
#endif /* X != 2 and X != 1*/
`#elif' stands for “else if”. Like `#else', it goes in the middle of a conditional group and subdivides
it; it does not require a matching `#endif' of its own. Like `#if', the `#elif' directive includes an
expression to be tested. The text following the `#elif' is processed only if the original `#if'-
condition failed and the `#elif' condition succeeds.
More than one `#elif' can go in the same conditional group. Then the text after each `#elif' is
processed only if the `#elif' condition succeeds after the original `#if' and all previous `#elif'
directives within it have failed.
`#else' is allowed after any number of `#elif' directives, but `#elif' may not follow `#else'.

You might also like