Introduction To Problem Solving Using C Unit-2
Introduction To Problem Solving Using C Unit-2
Character Set, Structure of a ‘C’ Program, Data Types, Operators, Expressions, Assignment Statement, Conditional
Statements, Looping Statements, Nested Looping Statements, Multi Branching Statement (Switch), Break and Continue,
Differences between Break and Continue, Unconditional Branching (Go to Statement)
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program.
A C program basically consists of the following parts:
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
return 0;
}
1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler
to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additionalcomments
in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.
Another Example:
/* This program accepts a number & displays it to the user*/
#include <stdio.h> void main(void)
{ int number;
printf( "Please enter a number: " );
scanf( "%d", &number );
printf( "You entered %d", number );
return 0;
}
Stepwise explanation:
#include
The part of the compiler which actually gets your program from the source file is called the
preprocessor.
#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is an instruction
to the compiler to make it do something. It tells the C compiler to include the contents of a file (in
this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special place, by the fact
that the filename is enclosed in <> characters
<stdio.h>
stdio.h is the name of the standard library definition file for all Standard Input and Output functions.
Your program will almost certainly want to send information to the screen and read things from the
keyboard, and stdio.h is the name of the file in which the functions that we want to use are defined.
The function we want to use is called printf. The actual code of printf will be tied in later by the linker.
The ".h" portion of the filename is the language extension, which denotes an include file.
void
This literally means that this means nothing. In this case, it is referring to the function whose name
follows.Void tells to C compiler that a given entity has no meaning, and produces no error.
Main In this particular example, the only function in the program is called main. A C program is
typically made up of large number of functions. Each of these is given a name by the programmer
and they refer to each other as the program runs.C regards the name main as a special case and will
run this function first i.e. the program execution starts from main. A parameter to a function gives
the function something to work on.
{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open
brace there must be a matching close one. Braces allow us to group pieces of program together,
often called a block. A block can contain the declaration of variable used within it, followed by a
sequence of program statements. In this case the braces enclose the working parts of the function
main.
;( semicolon)
The semicolon marks the end of the list of variable names, and also the end of that declaration
statement.
All statements in C programs are separated by ";" (semicolon) characters. The ";" character is actually
very important. It tells the compiler where a given statement ends. If the compiler does not find one
of these characters where it expects to see one, then it will produce an error.
scanf
In other programming languages, the printing and reading functions are a part of the language. In C this
is not the case; instead they are defined as standard functions which are part of the language
specification, but are not a part of the language itself. The standard input/output library contains a
number of functions for formatted data transfer; the two we are going to use are scanf (scan
formatted) and printf (print formatted).
printf
The printf function is the opposite of scanf. It takes text and values from within the program and sends
it out onto the screen. Just like scanf, it is common to all versions of C and just like scanf, it is
described in the system file stdio.h.The first parameter to a printf is the format string, which
contains text, value descriptions and formatting instructions.
Types of error
a) Syntax Errors: Errors in syntax (grammar) of the program.
b) Semantic Errors: Errors in the meaning of the program.
c) Logical Errors: Errors in logic of the program. Compiler cannot diagnose these kinds of
errors.
d) Runtime Errors: i) Insufficient memory ii)Floating exception
e) Compile Errors: i) parse error ii)implicit declaration iii) no matching function iv)Unsatisfied
symbols v)incomplete type vi)cannot call member function vii)bad argument viii)cannot
allocate an object
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In
C, various characters have been given to communicate. Character set in C consists of;
Digits 0-9
Identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline.
Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the
same as using "index" and neither of them is the same as using "InDeX" for a variable. All
three refer to different variables.
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler.
Data Type
In the C programming language, data types refer to a domain of allowed values & the
operations that can be performed on those values. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted. There are 4
fundamental data types in C, which are- char, int, float &, double. Char is used to store any
single character; int is used to store any integer value, float is used to store any single
precision floating point number & double is used to store any double precision floating
point number.
We can use 2 qualifiers with these basic types to get more types.
Constants
A constant is an entity that doesn‘t
change whereas a variable is an entity that
may change constantscan be divided into two
major categories: Primary Constants,
Secondary Constants
VARIABLES
Variables are names that are used to store values. It can take different values but one at a
time. A data type is associated with each variable & it decides what values the variable can
take. Variable declaration requires that you inform C of the variable's name and data type.
Syntax – data type variable name;
Eg:int page_no;
char grade;
float salary;
long y;
Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various examples:
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If
we want we can assign some initial value to the variables during the declaration itself. This
is called initialization of the variable.
Eg-int pageno=10;
Expressions
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation
a>b- relational operation a
== b - logical operation
func (a,b) – function call
Statements
Statements are the primary building blocks of a program. A program is a series of statements
with some necessary punctuation. A statement is a complete instruction to the computer. In
C, statements are indicated by a semicolon at the end. a semicolon is needed to identify
instructions that truly are statements.
INPUT-OUTPUT IN C
When we are saying Input that means we feed some data into program. This can be given in
the form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file.
C programming language provides a set of built-in functions to output the data on the
computer screen.
Functions printf() and scanf() are the most commonly used to display out and take input
respectively. Let us consider an example:
FORMATTED INPUT-OUTPUT
Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.
Generally there are two kinds of locations in a computer where such a value can be present, these
are Memory and CPU registers. The storage class of a particular variable determines in which of
the above two locations the variable‘s value is stored.
There are four properties by which storage class of a variable can be recognized. These are scope,
default initial value, scope and life.
A variable‘s storage class reveals the following things about a variable
(i) Where the variable is stored.
(ii) What is the initial value of the variable if the value of the variable is not specified?
(iii) What is the scope of the variable (To which function or block the variable is available).
(iv) What is the life of particular variable (Up to what extent the variable exists in a program).
In c there are four types of storage class. They are: 1. Auto 2. Register 3.
Static 4. Extern
Storage class is modifier or qualifier of data types which decides: In which area of memory
a particular variable will be stored? What is scope of variable? What is visibility of
variable?
Scope of a variable in c: Meaning of scope is to check either variable is alive or dead. Alive
means data of a variable has not destroyed from memory. Up to which part or area of the
program a variable is alive, that area or part is known as scope of a variable. There are
four type of scope in c:
1. Block scope.
2. Function scope.
3. File scope.
3. Program scope.
Automatic Storage Class
Syntax to declare automatic variable is:
auto datatype variablename;
Example:
auto int i;
Features of Automatic Storage Class are as follows
Storage: Memory
Default Initial Value: Garbage Value
Scope: Local to the block in which the variable is defined
Life: Till the control remains within the block in which the variable is defined
by default every variable is automatic variable
The following program illustrates the work of automatic variables.
void test();
void main()
{
test();
test();
test();
}
void test()
{
auto int k=10;
printf(―%d\n‖,k);
k++;
}
Output:
10
10
10
In the above program when the function test() is called for the first time ,variable k is created and
initialized to 10. When the control returns to main(), k is destroyed. When function test() is called
for the second time again k is created , initialized and destroyed after execution of the function.
Hence automatic variables came into existence each time the function is executed and destroyed
when execution of the function completes.
In the above program, variable a was used frequently as a loop counter so the variable a is defined as a
register variable. Register is a not a command but just a request to the compiler to allocate the
memory for the variable into the register. If free registers are available than memory will be
allocated in to the registers. And if there are no free registers then memory will be allocated in the
RAM only (Storage is in memory i.e. it will act as automatic variable).
Every type of variables can be stored in CPU registers. Suppose the microprocessor has 16 bit registers
then they can‘t hold a float or a double value which requires 4 and 8 bytes respectively.
But if you use register storage class for a float or double variable then you will not get any error
message rather the compiler will treat the float and double variable as be of automatic storage
class(i.e. Will treat them like automatic variables).
Output:10 11 12
Here in the above program the output is 10, 11, 12, because if a variable is declared as static then it is
initialized only once and that variable will never be initialized again. Here variable k is declared as
static, so when test() is called for the first time k value is initialized to 10 and its value is
incremented by 1 and becomes 11. Because k is static its value persists. When test() is called for the
second time k is not reinitialized to 10 instead its old value 11 is available. So now 11 is get printed
and it value is incremented by 1 to become 12. Similarly for the third time when test() is called
12(Old value) is printed and its value becomes 13 when executes the statement ‗k++;‘
So the main difference between automatic and static variables is that static variables are initialized to
zero if not initialized but automatic variables contain an unpredictable value(Garbage Value) if not
initialized and static variables does not disappear when the function is no longer active , their value
persists, i.e. if the control comes back to the same function again the static variables have the same
values they had last time.
General advice is avoid using static variables in a program unless you need them, because their values
are kept in memory when the variables are not active which means they occupies space in memory
that could otherwise be used by other variables.
So if a variable is to be used by many functions and in different files can be declared as external
variables. The value of an uninitialized external variable is zero. The declaration of an external
variable declares the type and name of the variable, while the definition reserves storage for the
variable as well as behaves as a declaration. The keyword extern is specified in declaration but not
in definition. Now look at the following four statements
1. auto int a;
2. register int b;
3. static int c;
4. extern int d;
Out of the above statements first three are definitions where as the last one is a declaration. Suppose
there are two files and their names are File1.c and File2.c respectively. Their contents are as
follows:
File1.c
int n=10;
void hello()
{
printf(―Hello‖);
}
File2.c
extern int n;
extern void hello();
void main()
{printf(―%d‖, n);
hello();}
In the above program File1.obj+ File2.obj=File2.exe and in File2.c value of n will be 10.
OPERATORS-An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C language is rich in built-in operators and provides the following
types of operators: Arithmetic Operators, Relational Operators, Logical Operators, Bitwise
Operators, Assignment Operators, Increment and decrement operators, Conditional
operators, Misc Operators
% B % A will give 0
Division
== Checks if the values of two operands are equal or not, if yes (A == B) is not
then condition becomes true. true.
> Checks if the value of left operand is greater than the value (A > B) is not
of right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not
the value of right operand, if yes then condition becomes true.
true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.
Logical Operators:
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&&
nonzero, then condition becomes true. false.
|| (A || B) is true.
non-zero, then condition becomes true.
!(A && B) is
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it (A & B) will give 12,
exists in both operands. which is 0000 1100
^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49,
one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary and has (~A ) will give -61, which
the effect of ‗flipping‘ bits. is 1100 0011 in 2‘s
complement form.
<< Binary Left Shift Operator. The left operands value A << 2 will give 240
is moved left by the number of bits specified by the which is 1111 0000
right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15
value is moved right by the number of bits specified which is 0000 1111
by the right operand.
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
Operator Description Example
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different statements
according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false
expression2 is returned.
y = ( x> 5 ? 3 : 4 ) ;this statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
Misc Operators:
There are few other operators supported by c language.
Operator Description Example
& Returns the address of a variable. &a; will give actual address of
the variable.
Type casting /type conversion is a way to convert a variable from one data type to
another data type. For example, if you want to store a long value into a simple integer
then you can typecast long to int.
You can convert values from one type to another explicitly using the cast operator. There
are two types of type casting in c languages that are implicit conversions and Explicit
Conversions.
New data type should be mentioned before the variable name or value in brackets which
to be typecast.
C TYPE CASTING EXAMPLE PROGRAM:
In the below C program, 7/5 alone will produce integer value as 1.So, type cast is done
before division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf(―%f‖,x);
}
Output:
1.400000
WHAT IS TYPE CASTING IN C LANGUAGE?
Converting an expression of a given type into another type is known as type casting. It is best
practice to convert lower data type to higher data type to avoid data loss.Data will be
truncated when the higher data type is converted to lower. For example, if a float is
converted to int, data which is present after the decimal point will be lost.
There are two types of type casting in c language.
TYPES OF TYPECASTING IN C
Types of type casting in C Programming
Implicit Conversion
Explicit Conversion
1. IMPLICIT CONVERSION
Implicit conversions do not require any operator for converted. They are automatically
performed when a value is copied to a compatible type in the program.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(―implicit value is %d‖,p);
getch();}
Output:-
implicit value is 20.
2. EXPLICIT CONVERSION
In C language, Many conversions, especially those that imply a different interpretation of the
value, require an explicit conversion.
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
short p;
clrscr();
p = (short) i; // Explicit conversion
printf(―Explicit value is %d‖,p);
getch();
}
Output:-
Explicit value is 20.
a) If statement
Syntax:
if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If boolean expression evaluates to false then the first set of code after the end of the if
statement (after the closing curly brace) will be executed. C programming language assumes any
non-zero and non-null values as true and if it is either zero or null then it is assumed as false
value.
Flow Diagram:
Example:
#include <stdio.h>
int main ()
{ int a = 10;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
Printf("value of a is : %d\n", a);
}
When the above code is compiled and executed, it produces following result:
a is less than 20;
value of a is : 10
Example:
#include <stdio.h>
main ()
{ int a = 100;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
else
{ Printf("a is not less than 20\n" );
} Printf("value of a is : %d\n", a);}
When the above code is compiled and executed, it produces following result:
a is not less than 20;
value of a is : 100
Example:
main ()
{ char grade = 'B';
switch(grade)
{ case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
} printf("Your grade is %c\n", grade );
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is B
Program Loops and Iteration A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the programming
languages:
Example:
#include <stdio.h> main ()
{ int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
}
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: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
#include <stdio.h>
main ()
{ int a = 10;
do
{ printf("value of a: %d\n", a);
a = a + 1;
} while ( a < 20 );
}
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: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
#include <stdio.h>
main ()
{ for( int a = 10; a < 20; a = a + 1 )
{ printf("value of a: %d\n", a);
}
}
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: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Jump statements
Syntax:
Break;
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 10;
while( a < 20 )
{ printf("value of a: %d\n", a);
a++;
if( a > 15)
{ break;
}
}
}
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: 15
(ii) Continue statement: Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating. The continue statement in C programming
language works somewhat like the break statement. Instead of forcing termination,
however, continue forces the next iteration of the loop to take place, skipping any code in
between. Syntax: continue;
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 10;
do
{ if( a == 15)
{ a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
}
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
(iii) Goto Statement: Transfers control to the labeled statement. Though it is not advised to
use goto statement in your program A goto statement in C programming language
provides an unconditional jump from the goto to a labeled statement in the same function.
Syntax:
goto label;
label: statement;
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 10;
LOOP: do
{ if( a == 15)
{ a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
}
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