U1
U1
U1
INTRODUCTION TO COMPUTERS
1.1 COMPUTER SYSTEMS
A computer is a system made of two major components: hardware and software. The computer
hardware is the physical equipment. The software is the collection of programs (instructions) that
allow the hardware to do its job.
Computer
System
Hardware
Software
1.1.1Computer Hardware:
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU), primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the computers.
Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio
input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations, comparisons among data, and movement of data inside the system. Todays
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory, is
a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on the
monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy.
Auxiliary storage, also known as secondary storage, is used for both input and output. It is the
place where the programs and data are stored permanently. When we turn off the computer, or
programs and data remain in the secondary storage, ready for the next time we need them.
1.1.2 Computer Software:
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between the
hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
System Software:
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access to
the system.
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.
The last system software category, system development software, includes the language
translators that convert programs into machine language for execution ,debugging tools to ensure
that the programs are error free and computer assisted software engineering(CASE) systems.
Application software:
Application software is broken in to two classes: general-purpose software and application
specific software. General purpose software is purchased from a software developer and can be
used for more than one application. Examples of general purpose software include word
processors, database management systems,and computer aided design systems. They are labeled
general purpose because they can solve a variety of user computing problems.
Application specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system used
by a manufacturing organization are examples of application-specific software. They can be used
only for the task for which they were designed they cannot be used for other generalized tasks.
The relation ship between system and application software is shown in fig-2.In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the
out layer. To work with the system, the typical user uses some form of application software. The
application software in turn interacts with the operating system, which is apart of the system
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the operating system when necessary.
In the time-sharing environment, all computing must be done by the central computer. The
central computer has many duties: It must control the shared resources; it must manage the
shared data and printing and it must do the computing.
1.2.3 Client/Server Environment
A client/server computing environment splits the computing function between a central
computer and users computers. The users are given personal computers or work stations so that
some of the computation responsibility can be moved from the central computer and assigned to
the workstations. In the client-server environment, the users micro computers or workstations
are called the client. The central computer, which may be a powerful microcomputer,
minicomputer, or central mainframe system, is known as the server. Because the work is now
shared between the users computers and the central computer, response time and monitor
display are faster and the users are more productive.
A computer language is also known as Programming Language. There are various types of
programming languages. These languages are used to write programs to tell the computer what
to do.
Each computer language has its own set of rules and grammar. These are called the syntax rules
of the language.
Computer Languages have progressed over the years just like hardware. Starting from the
language made up to just two symbols 0 and 1, today, you can make the computer programs
using common English and Mathematical terms. On the whole these languages are classified
under three categories:
1940s
1950s
Symbolic Languages
1960s
High-Level Languages
The code in a source file stored on the disk must be translated into machine language .This is the
job of the compiler. The c compiler is two separate programs, the preprocessor and the
translator.
The preprocessor reads the source code and prepares it for the translator. While preparing the
code, it scans for special instructions known as preprocessor commands. These commands tell
the preprocessor to look for special code libraries, make substitutions in the code, and in other
ways prepare the code for translation into machine language. The result of preprocessing is
called the translation unit.
After the preprocessor has prepared the code for compilation, the translator does the actual work
of converting the program into machine language. The translator reads the translation unit and
writes the resulting object module to a file that can then be combined with other precompiled
units to form the final program. An object module is the code in machine language. The output
of the compiler is machine language code, but it is not ready to run; that is, it is not executable
because it does not have the required C and other functions included.
1.4.3 Linking:
A C program is made up of many functions. We write some of these functions, and they are a
part of our source program. There are other functions, such as input/output processes and,
mathematical library functions that exist elsewhere and must be attached to our program. The
linker assembles all of these functions, ours and systems into our final executable program.
1.4.4 Executing:
Once program has been linked, it is ready for execution. To execute a program we use an
operating system command, such as run, to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating system program known as
the loader. It locates the executable program and reads it into memory. When everything is
loaded, the program takes control and it begins execution.
In a typical program execution, the reads data for processing, either from the user or from a file.
After the program processes the data, it prepares the output and output can be to the users
monitor or to a file. When the program has finished its job, it tells the operating system, which
then removes the program from memory.
1.5
PROGRAM DEVELOPMENT:
ALGORITHM /PSEUDOCODE
1.5.1 Pseudocode:
Pseudo code is an artificial and informal language that helps programmers to develop
algorithms. Pseudo code is similar to everyday English, it is convenient and user friendly
although it is not an actual computer programming language. Pseudo code programs are not
actually executed on computer rather they merely help the programmer think out a program
before attempting to write it in a programming language such as C.
1.5.2 Algorithm:
Step 1: Start
Step 2: Read the two numbers in to a, b
Step 3: c= a + b
Step 4: write/print c
Step 5: Stop.
The following are the most common symbols used in Drawing flowcharts:
Oval
Terminal
start/stop/begin/end.
Parallelogram
Input/output
Document
Print Out
Rectangle
Process
Any processing to be
Decision
Decision or switching
type of operations.
Circle
Connector
Used to connect
Different parts of flowchart.
Arrow
Flow
Once we fully understand the problem we need to develop our solution. Three tools will help in
this task. 1. Structure chart, 2.Psuedocode &3.Flowcharts. Generally we will use structure chart
and either flowchart or Pseudo code
The structure chart is used to design the whole program .Pseudo code and flowcharts are used to
design the individual parts of the program.
Structure chart: A structure chart, also known as hierarchy chart, shows the functional flow
through our program. The structure chart shows how we are going to break our program into
logical steps each step will be a separate module. The structure chart shows the interaction
between all the parts (modules) of our program.
We can use flowchart or pseudo code to complete the design of your program will depend on
experience and difficulty of the program which you are designing.
1.6.4.2.White box testing: This is the responsibility of the programmer. White box testing
assumes that the tester knows everything about the program.
Except for the simplest program, one set of test data will not completely validate a program.
C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The
language evolved from Martin Richard's BCPL, and one of its earlier forms was the B language,
which was written by Ken Thompson for the DEC PDP-7. The first book on C was The C
Programming Language by Brian Kernighan and Dennis Ritchie, published in 1978.
In 1983, the American National Standards Institute (ANSI) established a committee to
standardize the definition of C. The resulting standard is known as ANSI C, and it is the
recognized standard for the language, grammar, and a core set of libraries. The syntax is slightly
different from the original C language, which is frequently called K&R for Kernighan and
Ritchie. There is also an ISO (International Standards Organization) standard that is very similar
to the ANSI standard.
It appears that there will be yet another ANSI C standard officially dated 1999 or in the early
2000 years; it is currently known as "C9X."
1.7.1 Basic Structure of C Language :
Every C program is made of one or more preprocessor commands, a global declaration
section, and one or more functions.
The program written in C language follows this basic structure. The sequence of sections
should be as they are in the basic structure. A C program should have one or more sections but
the sequence of sections is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section
1.7.1.1
Documentation Section : comes first and is used to document the use of logic or
reasons in your program. It can be used to write the program's objective, developer and logic
details. The documentation is done in C language with /* and */ . Whatever is written between
these two are called comments. The comments are called Block comments. The second format,
the Line comment uses two slashes (/ /) to identify a comment. Programmers generally use this
format for short comments.
1.7.1.2 Linking Section : This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section.
e.g. #include <stdio.h>
1.7.1.3 Definition Section : It is used to declare some constants and assign them some value.
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program replace it with 25.
1.7.1.4. Global declaration Section: Here the variables which are used through out the program
(including main and other functions) are declared so as to make them global(i.e accessible to all
parts of program)
e.g. int i; (before main())
1.7.1.5 main function section: It tells the compiler where to start the execution from
main()
{
point from execution starts
}
main function has two sections
1. declaration section : In this the variables and their data types are declared.
2. Executable section : This has the part of program which actually performs the task we
need.
1.7.1.6 Sub program or function section: This has all the sub programs or the functions which
our program needs.
1.9
C- TOKENS :
Tokens are individual words and punctuations marks in English language sentence. The smallest
individual units are known as C tokens.
OPERATORS
E.g. +, -, *
SPECIAL SYMBOLS
E.g. [ ], { }
STRINGS
E.g. asifia
C TOKENS
CONSTANTS
E.g. rate,no_of_hours
KEY
A C program can be divided into these tokens. A C program contains minimum 3 c tokens no
matter what the size of the program is.
Identifiers :
Names of the variables and other program elements
known as
identifiers. In C, there are few rules that govern the way variable are named (identifiers).
1. Identifiers can be named from the combination of A-Z, a-z, 0-9, _(Underscore).
2. The first alphabet of the identifier should be either an alphabet or an underscore , digit are not
allowed.
3. It should not be a keyword.
Eg: name, ptr, sum
After naming a variable we need to declare it to compiler of what data type it is .
The format of declaring a variable is
Data-type id1, id2,.....idn;
where data type could be float, int, char or any of the data types.
id1, id2, id3 are the names of variable we use. In case of single variable no commas are
required.
eg :
float a, b, c;
Assigning values :
When we name and declare variables we need to assign value to the variable. In some
cases we assign value to the variable directly like
a=10;
in our program.
In some cases we need to assign values to variable after the user has given input for that.
Example we ask user to enter any no and input it .
/* write a program to show assigning of values to variables */
#include<stdio.h>
main()
{
int a;
float b;
printf("Enter any number\n");
b=190.5;
scanf("%d",&a);
printf("user entered %d", a);
printf("B's values is %f", b);
}
LENGTH
RANGE
Unsigned char
8 bits
0 to 255
Char
8 bits
-128 to 127
Short int
16 bits
-32768 to 32767
Unsigned int
32 bits
0 to 4,294,967,295
Int
32 bits
-2,147,483,648 to 2,147,483,648
Unsigned long
32 bits
0 to 4,294,967,295
Enum
16 bits
-2,147,483,648 to 2,147,483,648
Long
32 bits
-2,147,483,648 to 2,147,483,648
Float
32 bits
3.4*10E-38 to 3.4*10E38
Double
64 bits
1.7*10E-308 to 1.7*10E308
Long double
80 bits
3.4*10E-4932 to 1.1*10E4932
1.11 VARIABLES
A quantity that can vary during the execution of a program is known as a variable. To
identify a quantity we name the variable for example if we are calculating a sum of two numbers
we will name the variable that will hold the value of sum of two numbers as 'sum'.
Variable Declaration in C
All variables must be declared before we use them in C program, although certain declarations
can be made implicitly by content. A declaration specifies a type, and contains a list of one or
more variables of that type as follows:
type variable_list;
Here, type must be a valid C data type including char, int, float, double, or any user defined data
type etc., and variable_list may consist of one or more identifier names separated by commas.
Some valid variable declarations along with their definition are shown here:
int
i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a variable at the time of declaration as follows:
int i = 100;
An extern declaration is not a definition and does not allocate storage. In effect, it claims that a
definition of the variable exists some where else in the program. A variable can be declared
multiple times in a program, but it must be defined only once. Following is the declaration of a
variable with extern keyword:
extern int
i;
Though you can declare a variable multiple times in C program but it can be declared only once
in a file, a function or a block of code.
Variable Initialization in C
Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is:
variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
int d = 3, f = 5;
/* initializing d and f. */
byte z = 22;
/* initializes z. */
#include <stdio.h>
int main ()
{
/* variable declaration: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of c : 30
value of f : 23.333334
1.12 CONSTANTS :
A quantity that does not vary during the execution of a program is known as a constant
supports two types of constants namely Numeric constants, character constants, Boolean
constants, String constants.
1.12.1 Numeric constants:
1. Example for an integer constant is 786,-127
2. Long constant is written with a terminal lor L for example 1234567899L is a Long
constant.
3. Unsigned constants are written with a terminal u or U, and the suffix ul and UL
Indicates unsigned long. For example 123456789u is a Unsigned constant and
1234567891ul is an unsigned long constant.
4. The advantage of declaring an unsigned constant is to increase the range of storage.
5. Floating point constants contain a decimal point or an exponent or both.
For E.g :
123.4,1e-2, 1.4E-4,etc. The suffixes f or F indicate a float constant while the absence of
f or F indicate the double, l or L indicate long double.
1.12.2 Character constants:
A character constant is written as one character with in single quotes such as a. The
value of a character constant is the numerical value of the character in the machines character set
certain character constants can be represented by escape sequences like \n. These sequences
look like two characters but represent only one.
The following are the some of the examples of escape sequences:
Escape sequence
Description
\a
Alert
\b
Backspace
\f
Form feed
\n
New Line
\r
Carriage return
\t
Horizontal Tab
\v
Vertical Tab
hello world
It is important to understand the difference between the null character and an empty string. The
null character represents no value. Null character is represented as \0.
1.13 OPERATORS
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.
C operators can be classified as
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
8. Special operator
1.13.1. Arithmetic operators :
All basic arithmetic operators are present in C.
Operator
Meaning
add
subtract
multiplication
division
modulo division(remainder)
An arithmetic operation involving only real operands(or integer operands) is called real
arithmetic(or integer arithmetic). If a combination of arithmetic and real is called mixed mode
arithmetic.
1.13.2. Relational operators :
We often compare two quantities and depending on their relation take certain decisions for that
comparison we use relational operators.
Operator
Meaning
<
is less than
>
is greater than
<=
>=
==
is equal to
!=
is not equal to
It is the form of
ae-1
relational operator
ae-2
1.13.3. Logical operators: An expression of this kind which combines two or more relational
expressions is termed as a logical expressions or a compound relational expression. The
operators and truth values are
op-1
op-2
non-zero
non-zero
non-zero
non-zero
op-1
!op-1
non-zero
zero
zero
non-zero
a+=1
a=a-1
a-=1
a=a%b
a%=b
meaning
&
Bitwise AND
Bitwise OR
Bitwise exclusive OR
<<
left shift
>>
right shift
one's complement
Bitwise OR |
Bitwise OR operator | takes 2 bit patterns, and perform OR operations on each pair of
corresponding bits. The following example will explain it.
1010
1100
-------OR 1110
-------The Bitwise OR, will take pair of bits from each position, and if any one of the bit is 1, the result
on that position will be 1. Bitwise OR is used to Turn-On bits as we will see in later sections.
Bitwise AND &
Bitwise AND operator &, takes 2 bit patterns, and perform AND operations with it.
1010
1100
------AND
1000
------The Bitwise AND will take pair of bits from each position, and if only both the bit is 1, the result
on that position will be 1. Bitwise AND is used to Turn-Off bits.
Ones Complement operator ~
Ones complement operator (Bitwise NOT) is used to convert each 1-bit to 0-bit and 0-bit to
1-bit, in the given binary pattern. It is a unary operator i.e. it takes only one operand.
1001
NOT
------0110
------Bitwise XOR ^
Bitwise XOR ^, takes 2 bit patterns and perform XOR operation with it.
0101
0110
-----XOR 0011
-----The Bitwise XOR will take pair of bits from each position, and if both the bits are different, the
result on that position will be 1. If both bits are same, then the result on that position is 0.
Left shift Operator <<
The left shift operator will shift the bits towards left for the given number of times.
int a=2<<1;
Lets take the binary representation of 2 assuming int is 1 byte for simplicity.
Position 7
Bits
Now shifting the bits towards left for 1 time, will give the following result
Position 7
Bits
Now the result in decimal is 4. You can also note that, 0 is added as padding the in the position 0.
If you left shift like 2<<2, then it will give the result as 8. Therefore left shifting 1 time, is equal
to multiplying the value by 2.
Right shift Operator >>
The right shift operator will shift the bits towards right for the given number of times.
int a=8>>1;
Lets take the binary representation of 8 assuming int is 1 byte for simplicity.
Position 7
Bits
1 0
Now shifting the bits towards right for 1 time, will give the following result
Position 7
Bits
0 1
Now the result in decimal is 4. Right shifting 1 time, is equivalent to dividing the value by 2.
Note on shifting signed and unsigned numbers
While performing shifting, if the operand is a signed value, then arithmetic shift will be used. If
the type is unsigned, then logical shift will be used.
In case of arithmetic shift, the sign-bit ( MSB ) is preserved. Logical shift will not preserve the
signed bit. Lets see this via an example.
#include<stdio.h>
int main() {
signed char a=-8;
signed char b= a >> 1;
printf("%d\n",b);
}
In the above code, we are right shifting -8 by 1. The result will be -4. Here arithmetic shift is
applied since the operand is a signed value.
#include<stdio.h>
int main() {
unsigned char a=-8;
unsigned char b= a >> 1;
printf("%d\n",b);
}
Note: Negative numbers are represented using 2s complement of its positive equivalent.
2's compliment of +8 is
1111 1000
(. and ->). The comma operator is used to link related expressions together.
sizeof operator is used to know the sizeof operand. The sizeof operator tells us the size, in
bytes, of a type or a primary expression.
Eg: sizeof(int)
/* programs to exhibit the use of operators */
#include<stdio.h>
main()
{
int sum, mul, modu;
float sub, divi;
int i, j;
float l, m;
printf("Enter two integers ");
scanf("%d%d",&i,&j);
printf("Enter two real numbers");
scanf("%f%f",&l,&m);
sum=i+ j;
mul=i*j;
modu=i%j;
sub=l-m;
divi=l/m;
}
}
/* program to implement increment and decrement operators */
#include<stdio.h>
main()
{
int i;
printf("Enter a number");
scanf("%d", &i);
i++;
printf("after incrementing %d ", i);
i--;
printf("after decrement %d", i);
}
/* program using ternary operator and assignment */
#include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers ");
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
printf("largest of two is %d",large);
}
1.14 EXPRESSIONS :
An expression is a sequence of operands and operators that reduces to a single value.
Expression can be simple or complex. An operator is a syntactical token that requires an action
be taken. An operand is an object on which an operation is performed.
A simple expression contains only one operator. E.g: 2 + 3 is a simple expression whose
value is 5.A complex expression contains more that one operator. E.g: 2 + 3 * 2.
To evaluate a complex expression we reduce it to a series of simple expressions. In this first we
will evaluate the simple expression 3 * 2 (6) and then the expression 2 + 6,giving a result of 8.
The order in which the operators in a complex expression are evaluated is determined by
a set of priorities known as precedence, the higher the precedence ,the earlier the expression
containing the operator is evaluated. If two operators with the same precedence occur in a
complex expression, another attribute of an operator, its associativity takes control. Associativity
is the parsing direction used to evaluate the expression.
It can be either left-to-right or right-to-left .When two operators with the same precedence occur
in an expression and their associativity is left-to-right , the left operator is evaluated first.
For example, in the expression 3*4/6, there are two operators multiplication and division, with
the same precedence and left-to-right associativity .Therefore the multiplication is evaluated
before the division.
1.14.1 The following table shows the precedence and associativity of operators:
*/%
Low
+-
An expression is evaluated in left to right and value is assigned to variable in left side of
assignment operator.
/* program to demonstrate evaluation of expressions */
#include<stdio.h>
main()
{
float a, b, c, x, y, z;
a=9;b=23;c=3;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf("values of x, y, z are %d%d%d", x, y, z);
}
1.Text
2. Binary
A test stream consists of sequence of characters divided into lines with each line terminated by a
new line (\n).
A binary stream consists of a sequence of data values such as integer, real, complex using their
memory representation.
In C keyboard is known as Standard input and monitor is known as Standard output.
1.16.1 Formatting Input / Output:
The C language provides two formatting functions: printf for output formatting and
scanf for input formatting. The printf function converts data stored in the program into text
stream for output to the monitor, the scanf function converts the text stream coming from
keyboard to data values and stores them in program variables.
1.16.2 Input and Output statements :
The simplest of input operator is getchar to read a single character from the input device.
varname=getchar();
You need to declare varname.
The simplest of output operator is putchar to output a single character on the output
device.
putchar(varname)
The getchar() is used only for one input and is not formatted. Formatted input refers to an input
data that has been arranged in a particular format, for that we have scanf.
scanf("control string", arg1, arg2,...argn);
Control string specifies field format in which data is to be entered.
arg1, arg2... argn specifies address of location or variable where data is stored.
Eg: scanf("%d%d",&a,&b);
%d
%f
floats
%l
long
%c
character
}
1.16.3 Statements and blocks :
A statement causes an action to be performed by the program. It translates directly in to
one or more executable computer instructions.
Statement types:
C defines different types of statements.
1.16. 3.1 Null statement :
The null statement is just a semicolon (the terminator).
Eg:
//null statement
Although they do not arise often, there are syntactical situations where we must have a statement
but no action is required .In these situations we use the null statement.
1.16.3.2 Expression statement:
An expression is turned in to a statement by placing a semicolon(;)after it.
expression;
//expression statement.
Eg: a=2;
When C sees the semicolon, it completes any pending side effects and discards the expression
values before continuing with the next statement.
Let us look at some expression statements:a=b=3;
a=(b=3);
A return statement terminates a function. All functions, including main, must have a
return statement. Where there is no return statement at the end of the function, the system inserts
one with a void return value.
return expression;
//return statement
The return statement can return a value to the calling function. In case of main, it returns a value
to the operating system rather than to another function. A return value of zero tells the operating
system that the program executed successfully.
1.16.3.4 compound statements:
A compound statement is a unit of code consisting of zero or more statements .It is also
known as a block. The compound statement allows a group of statements to become one single
entity.
A compound statement consists of an opening brace, an optional declaration and
definition section, and an optional statement section, followed by a closing brace.
Eg:
//Local Declarations
int x;
int y;
int z;
//Statements
x=1;
y=2;
//End Block
Branching:Branching is so called because the program chooses to follow one branch or another.
1.16.4.1 If and switch statements :
If statement:
We have a number of situations where we may have to change the order of execution of
statements based on certain conditions or repeat a group of statements until certain specified
conditions are met.
The if statement is a two way decision statement and is used in conjunction with an
expression. It takes the following form:
if (test expression)
If the test expression is true then the statement block after if is executed otherwise it is not
executed
if (test expression)
{
statement block;
}
statementx ;
only statementx is executed.
/* program for if */
#include<stdio.h>
main()
{
int a,b;
printf(Enter two numbers);
scanf (%d%d, &a, &b):
if a>b
printf( a is greater);
if b>a
printf( b is greater);
}
If your have another set of statement to be executed if condition is false then if-else is
used
if (test expression)
{
statement block1;
}
else
{
statement block2;
}
statement x ;
#include<stdio.h>
main()
{
int a,b;
printf(Enter two numbers);
scanf(%d%d,&a,&b):
if a>b
printf( a is greater)
else
printf(b is greater);
}
if num < 0
result=abs(num)
output result
else
if num == 0
print "the number is zero"
else
result=num*num
output result
If more than one if else statement
if(text cond1)
{
if (test expression2
{
statement block1;
}
else
{
statement block 2;
}
}
else
{
statement block2;
}
statement-x ;
if else ladder
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
The nesting of if-else depends upon the conditions with which we have to deal.
1.16.4.2 The switch statement :
If for suppose we have more than one valid choices to choose from then we can use
switch statement in place of if statements.
switch(expression)
{
case value-1
block-1
break;
case value-2
block-2
break;
---------------
default:
default block;
break;
}
statementx
In case of
if(cond1)
{
statement-1
}
if (cond2)
{
statement 2
}
/* program to implement switch */
#include<stdio.h>
main()
{
int marks, index;
char grade[10];
}
The most basic loop in C is the while loop. A while statement is like a repeating if
statement. Like an If statement, if the test condition is true: the statments get executed. The
difference is that after the statements have been executed, the test condition is checked again. If
it is still true the statements get executed again. This cycle repeats until the test condition
evaluates to false.
#include <stdio.h>
int main()
{
int number, factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0)
{
/*
while
loop
continues
util
test
condition
number>0
is
true
*/
factorial=factorial*number;
--number;
}
printf("Factorial=%d", factorial);
return 0;
}
do while statement :
The while loop does not allow body to be executed if test condition is false. The do while
is an exit controlled loop and its body is executed at least once.
do {
some code/s;
}
while (test expression);
For loops are typically used when the amount of iterations is known before entering the loop.
Syntax:
for(initialization; test control; increment)
{
body of loop
}
.
The syntax for a break statement in C is as follows:
break;
/* Sample program using break statement */
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
/* Program */
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
for(i = -10; i < 10; i++){
if(i == 0)
continue;
printf("%f\n", 15.0/i);
// Lots of other statements .....
}
exit(EXIT_SUCCESS);
}
The Continue can be used in other parts of a loop, too, where it may occasionally help to
simplify the logic of the code and improve readability. Continue has no special meaning to a
switch statement, where break does have. Inside a switch, continue is only valid if there is a
loop that encloses the switch, in which case the next iteration of the loop will be started.
There is an important difference between loops written with while and for. In a while, a
continue will go immediately to the test of the controlling expression. The same thing in a for
will do two things: first the update expression is evaluated, then the controlling expression is
evaluated.
goto and labels:
A goto statement in C programming language provides an unconditional jump from the
goto to a labeled statement in the same function.
The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;
#include <stdio.h>
int main ()
{
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example1-Helloworldprogram
/* A very simple c program printing a string on screen*/
#include <stdio.h>
main()
{
printf("Hello World\n");
return 0;
}
Output of
above program:
"Hello World"
Example 2 - c program to take input from user using scanf
#include <stdio.h>
main()
{
int number;
printf("Enter an integer\n");
scanf("%d",&number);
printf("Integer entered by you is %d\n", number);
return 0;
}
Output:
Enter a
number
5
Number entered by you is 5
Example 3 - using if else control instructions
#include <stdio.h>
main()
{
int x = 1;
if ( x == 1 )
printf("x is equal to one.\n");
else
printf("For comparison use == as = is the assignment operator.\n");
return 0;
}
Output:
x is equal to one.
Example 4 - loop example
#include <stdio.h>
main()
{
int value = 1;
while(value<=3)
{
printf("Value is %d\n", value);
value++;
}
return 0;
}
Output:
Value is 1
Value is 2
Value is 3
Example 5: /* Program to find out greatest among two numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
a=10;
b=5;
if(a>b)
{
printf("a is greater");
}
getch();
}
Example 6: /* simple if else program */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter a value for a:");
scanf("%d",&a);
printf("\nEnter a value for b:");
scanf("%d",&b);
if(a>b)
{
printf("\n a got greater value");
}
else
{
break;
default :
printf("Wrong Choice. Enter a no between 1 and 5");
break;
}
getch();
}
Example 8: /* Simple goto Program */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter 2 nos A and B one by one : ");
scanf("%d%d",&a,&b);
if(a>b)
{
goto first;
}
else
{
goto second;
}
first:
printf("\n A is greater..");
goto g;
second:
printf("\n B is greater..");
g:
getch();
}