C Programming Unit 1
C Programming Unit 1
C Programming Unit 1
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.
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.
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.
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
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.
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.
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; }
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.
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.
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
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;
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.
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
*/%
+-
>> <<
== !=
Binary Operators left-to-right
&
&&
||
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
* Multiplication
/ Division
% Modulus Operator
etc.,
.
#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
x + y = 32
x – y = 22
x * y = 115
x%y=2x
/y=5
x + y = 18.0 x
– y = 10.0 x *
y = 56.0 x / y
= 3.50
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 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.
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.
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 OR
! Logical NOT
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.
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 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
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
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.
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.
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 OR
^ Bitwise
Exclusive
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.
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;
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 .
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);
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.
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.
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.
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;
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.
main()
{ char ch;
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 */
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;
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;
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
do
{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0)
int i;
for (i=0;i<10;i++)
{
if (i==5)
continue;
printf("%d",i);
if (i==8)
break; }
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'.