Unit - Ii: Problem Solving
Unit - Ii: Problem Solving
Unit - Ii: Problem Solving
Problem solving:
Problem solving is a mental process that involves discovering, analyzing, and solving problems.
The ultimate goal of problem solving is to overcome obstacles and finding the solution that best
resolves the issue. That is process of finding solutions for difficult and complex problems.
Success in solving any problem is only possible after we fully understand the problem what we
are trying to solve.
Specifying the problem requirements forces you to state the problem clearly and unambiguously
and to give a clear understanding of what is required for its solution.
The main objective of identifying the problem is to eliminate unimportant aspects and to focus on
the root problem.
This primary investigation of problem understanding is also called as problem definition phase.
During problem definition phase, we have to think about what must be done rather than how to
do it.
The main objective of this phase is to understand the processing part of the problem.
Try to think of all possible solutions for the given problem.
To find the solution, consider similar problems which are related to our problem and analyze how
you have solved them.
Formulate the fundamental conservation laws to mathematically describe what is physically
occurring. Also define the necessary constitutive relationships (relate variables based on
observations) and boundary conditions and/or compatibility constraints.
Use the laws of physics to develop the governing equations like Algebraic equations, and Integral
equations (mathematical equations).
Now, solve the resulting mathematical equations using Analytical solutions, Numerical or discrete
solutions.
Finally verify how well you have solved the problem by comparing to measurements. (Finding
the best mathematical solution).
3. Develop an Algorithm:
Algorithm is basically a set of instructions that (if correct and followed carefully) produce some
desired result.
An algorithm is a step by step procedure for solving the problem.
If the procedure is formally defined, then it must be implemented using some formal language,
and such a language is often known as a programming language(C, C++, JAVA.).
It is common to have a multiple algorithms(procedures) to tackle the same problem, but the
choice of a particular algorithm must depend on the time complexity and space complexity.
IF A < B
then PRINT B
ELSE
PRINT "The numbers are equal"
Step 4: END
Repetition:
Repetition which involves executing one or more steps for a number of times can be implemented using
constructs like the while, do-while and for loops. These loops execute one or more steps until some
condition is true.
Example: An algorithm that prints the first 10 natural numbers.
Step 1: [INITIALIZE] SET I = 0, N = 10
Step 2: Repeat Step while I<=N
Step 3: PRINT I
Step 4: END
4.
Representation of an algorithm:
The two most common representations of an algorithm are pseudo code and flowcharts.
FLOWCHARTING
In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
The usual direction of the flow of a procedure or system is from left to right or top to bottom.
Only one flow line should come out from a process symbol.
Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, should leave the decision symbol.
Only one flow line is used in conjunction with terminal symbol.
Write within standard symbols briefly. As necessary, you can use the annotation symbol to
describe data or computational steps more clearly.
If the flowchart becomes complex, it is better to use connector symbols to reduce the number of
flow lines. Avoid the intersection of flow lines if you want to make it more effective and better
way of communication.
Ensure that the flowchart has a logical start and finish.
It is useful to test the validity of the flowchart by passing through it with a simple test data.
Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part
LIMITATIONS OF USING FLOWCHARTS
Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
The essentials of what is done can easily be lost in the technical details of how it is done.
EXAMPLE: ON FLOWCHARTING
1. Draw a flowchart to find the sum of first 50 natural numbers.
5.
Program development(coding):
In order for a computer to carry out some task, it has to be supplied with a program, which is an
implementation of an algorithm.
This is expressed in a computer programming language; however it is possible (and desirable) to
talk and reason about algorithms in higher-level terms.
Developing a correct algorithm can be a significant intellectual challenge by contrast, coding it
should be straightforward.
Coding is implementing the solution of given problem statement which is suitable and selected
best problem solution using programming language instructions.
It is an effective, systematic approach to problem solving. By following each step consciously,
you can ensure that generating solutions is a fact-driven, objective, and reliable process.
It encourages you to dig deeper to the root cause, allows you to get input from others, to be
creative when finding solutions, and to monitor your solutions to make sure theyre working.
The source code consists of the programming statements that are created by a programmer with a
text editor or a visual programming tool and then saved in a file.
Example:
Second, testing is about managing risk for both the acquiring agency and the systems
vendor/developer/integrator.
The testing program is used to identify when the work has been completed so that the contract
can be closed, the vendor paid, and the system shifted by the agency into the warranty and
maintenance phase of the project.
Test case for finding Factorial of a number:
Factorial (n) = 1*2*3 * n
Example:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
Stmt 2;
.
.
.
Stmt n;
}
1. Documentation Section:
It consists of set of comment lines which include name of a program, author name, creation date
and other information. Comments are not necessary in program. These are useful for
documentation. Comments are placed in between the delimiters /* and */. The compiler does not
execute comments.
a. Single line comments
// this is a single line comment
/* This is a single line comment*/
b. Multiline comments
/* This is first line
Second line
Third line
*/
Global Declarations
The variables are declared before the main ( ) function as well as user defined functions is called
global variables. These global variables can be accessed by all the user defined functions including main (
) function. This section must be declared outside of all functions.
Main function:
Each and Every C program should contain only one main ( ). The C program execution starts with
main ( ) function. No C program is executed without the main function. The main ( ) function should be
written in small (lowercase) letters and it should not be terminated by semicolon. Main ( ) executes user
defined program statements, library functions and user defined functions and all these statements should
be enclosed within left and right braces.
Declaration Part:
It is used to declare local variables. The declaration part declares all variables that are used in the
execution part. Initialization of variables is also done in the section. Variables are declared by using data
types. Not only variables, we can also declare arrays, functions, pointers etc. These variables can also be
initialized with basic data types.
Executable Part (Program statements):
These statements are building blocks of a program. They represent instructions to the computer to
perform a specific task (operations). An instruction may contain input-output statements, arithmetic
statements, control statements, simple assignment statements and any other statements. Each executable
statement should be terminated with semicolon.
User-Defined Functions:
These are subprograms, generally, a subprogram is a function and these functions are written by
the user are called user; defined functions. These functions are performed by user specific tasks and this
also contains set of program statements. They may be written before or after a main () function and called
within main () function. This is an optional to the programmer.
C Character Set:
A character refers to the digit, alphabet or special symbol used to data representation.
1. Alphabets: A.Z, az
2. Digits: 0.9
3. Special Characters: ~! @ # $ % ^ & * ( ) _ + { } [ ] < > , . / ? \ | : ; " '
4. White Spaces: Horizontal tab, Carriage return, new line, form feed
Tokens:
The smallest individual units in a program are known as tokens.
C has the following tokens
Keywords
Identifiers
Constants
Operators
Punctuations
Keywords:
Definition: Keywords are the system defined identifiers (reserved identifiers) and cannot be as the names
of the program variables or other user defined program elements (user defined function names).
1. All keywords have fixed meanings that do not change.
2.
3.
4.
5.
Identifiers:
Identifiers refer to the names of variables, functions, labels, arrays, structures and various other
user-defined elements created by the programmer.
Identifier is the name of a variable that is made up from combination of alphabets, digits and
underscore.
The length of these identifiers can vary from one to several characters.
The first character must be a letter (alphabet) or an underscore, and subsequent characters must be
letters, digits, or underscores.
Here are some correct and incorrect identifier names:
Correct
count
test23
gross_sal
Incorrect
1count
test!2
gross-sal
In C, identifiers may be of any length. However, not all characters will necessarily be significant.
C defines two kinds of identifiers: external and internal.
An external identifier will be involved in an external link process. These identifiers, called
external names, include function names and global variable names that are shared between source
files.
If the identifier is not used in an external link process, then it is internal. This type of identifier is
called an internal name and includes the names of local variables.
In C89, at least the first 6 characters of an external identifier and at least the first 31 characters of
an internal identifier will be significant.
In an identifier, upper- and lowercase are treated as distinct. Hence, count , Count, and COUNT
are three separate identifiers.
An identifier cannot be the same as a C keyword and should not have the same name as functions
that are in the C library.
Constants:
Integer Constants:
1.
2.
3.
4.
5.
426
+782
-8000
-7605
Real Constants:
Real constants are often called Floating Point constants. The real constants could be written in two forms
Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional form:
Ex.:
The exponential form of representation of real constants is usually used if the value of the constant is
either too small or too large.
In exponential form of representation, the real constant is represented in two parts. The part appearing
before e is called mantissa, whereas the part following e is called exponent.
Following rules must be observed while constructing real constants expressed in exponential form:
1.
2.
3.
4.
The mantissa part and the exponential part should be separated by a letter e.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative integer. Default
sign is positive.
5. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Ex.:
+3.2e-5
4.1e8
-0.2e+3
-3.2e-5
Character Constants:
A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single inverted commas. Both the inverted commas should point to the left.
Ex.:
Operators:
Operator is a symbol that is used to perform mathematical operations.
The Assignment Operator:
It is used to assign a value to variable.
The general form of the assignment operator is
variable_name = expression;
where an expression may be as simple as a single constant or as complex as you require. C uses a
single equal sign to indicate assignment. The target, or left part, of the assignment must be an object, such
as a variable, that can receive a value.
Arithmetic Operators:
It is used to perform arithmetical operations. These operators operate on two operands.
It is also called as 'Binary operators'.
Unary minus:
The unary minus multiplies its operand by 1. That is, any number preceded by a minus sign
switches its sign.
The Increment and Decrement Operators
The increment operator, ++ adds 1 to its operand and decrement operator, - subtracts 1to its operand.
These are unary operators. (An operator which operates on a single operand is called unary operator)
In other words:
x = x+1; is the same as ++x; and x = X1; is the same as x;
Relational operators:
In the term relational operator, relational refers to the relationships that values can have with one
another.
The relational operators allow us to compare two values to see whether they are equal to each
other, unequal, or whether one is greater than the other.
It is also used to check conditions. These operators return 1 if condition is true otherwise 0.
Logical operators:
In the term logical operator, logical refers to the ways these relationships can be connected.
Sometimes, we have to check more than one condition at a time. In such case logical operators
allow to check more than one condition at a time.
C allows usage of three logical operators, namely, &&, || and !. These are to be read as AND
OR and NOT respectively.
In C, true is any value other than zero. False is zero. Expressions that use relational or logical operators
return 0 for false and 1 for true.
The truth table for the logical operators is shown here using 1's and 0's.
Bitwise Operators:
Bitwise operators are used for manipulation of data at a bit level. These operations are applied to
the individual bits of the operands.
They can be directly applied to char, short int and long. Bitwise operations are not used on float ,
double, long double, void , or other more complex types.
Bitwise Operators
Bitwise operators are used for manipulation of data at a bit level. These operations are applied to the
individual bits of the operands.
They can be directly applied to char, short int and long. Bitwise operations are not used on float , double,
long double, void , or other more complex types.
) { } * , : = ; ..... #
These characters have special meanings in C. The pound sign (#) can occur only in pre-processing
directives.
Data Types:
The type of a variable determines how much space it occupies in storage and how the bit pattern
stored is interpreted
A data type defines a set of values that a variable can store along with a set of operations that can
be performed on that variable.
Types
Data Types
int, char, float, double, void
Enum, structure, union
array, pointer,function
C89 defines five foundational data types: character, integer, floating-point, double floating-point, and
valueless. These are declared using char, int, float, double, and void, respectively.
These types form the basis for several other types. The size and range of these data types may vary among
processor types and compilers.
Basic data types in C:
1. Integer data type:
It varies depend upon the processor in the CPU that we use. If we are using 16 bit
processor, 2 byte (16 bit) of memory will be allocated for int data type.
Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of
memory for 64 bit processor is allocated for int datatype.
If you want to use the integer value that crosses the above limit, you can go for long
int and long long int for which the limits are very high.
Note:
In this case, float data type can be used to store decimal values in a variable.
For example, A can be stored using char data type. You cant store more than one
character using char data type.
Following table gives you details about standard integer types with its storage sizes and value ranges:
Type
char
unsigned char
signed char
int
unsigned int
short
unsigned short
long
unsigned long
void
Storage size
1 byte
1 byte
1 byte
2 or 4 bytes
2 or 4 bytes
2 bytes
2 bytes
4 bytes
4 bytes
0 bytes
Value range
-128 to 127
0 to 255
-128 to 127
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
0 to 65,535 or 0 to 4,294,967,295
-32,768 to 32,767
0 to 65,535
-2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
Value less
float
double
1. float:
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.
2. double:
1. Double data type is also same as float data type which allows up-to 10 digits after
decimal.
2.
Following table gives you details about standard floating-point types with storage sizes and value ranges
and their precision:
Type
Storage size
float
4 bytes
double
8 bytes
long double 10 bytes
Value range
1.2E-38 to 3.4E+38
2.3E-308 to 1.7E+308
3.4E-4932 to 1.1E+4932
Precision
6 decimal places
15 decimal places
19 decimal places
Type Modifiers:
Except type void, the basic data types may have various modifiers preceding them.
A type modifier alters the meaning of the base type so that it more precisely fit a specific need.
The list of data type modifiers is shown here:
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed
and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example,
unsigned long int.
Signed and unsigned integers differ in the way that the high-order bit of the integer is interpreted. If you
specify a signed integer, the compiler generates code that assumes the high-order bit of an integer is to be
used as a sign flag. If the sign flag is 0, the number is positive; if it is 1, the number is negative.
In general, negative numbers are represented using the two's complement approach, which reverses all bits
in the number (except the sign flag), adds 1 to this number, and sets the sign flag to 1.
The following sets of type specifiers are equivalent:
Variable:
Variable is used to store data and the value of a variable may change during program execution. It
is opposite to constant.
Variable name is a name given to memory location of a computer where data is stored.
All variables must be declared before they can be used.
The general form of a declaration is
type variable_list;
Here, type must be a valid data type plus any modifiers, and variable_list may consist of one or more
identifier names separated by commas.
Examples:
int i, j, l;
short int si;
unsigned int ui;
double balance, profit, loss;
Rules for variables:
1.
2.
3.
4.
5.
6.
7.
C Scopes:
A scope (in any programming) is a region of the program where a variable can have its existence and
outside the region that variable cannot be accessed. Therefore scopes are used to determine the visibility
of an identifier.
C scopes are divided into 4 types:
Block scope:
In C, block is represented as an area between opening curly brace i.e., { and closing curly brace
i.e.,}. However, block scope also extends to function parameters in a function definition. That is, function
parameters are included in a function's block scope. Variables with block scope are local to their block.
In the above code there are three blocks block1,block2 and block3. In the above code one more block
which is main function block. If a variable or function has scope only within the block where it has
declared then scope of variable or function is called as block scope.
Function prototype scope:
Identifiers declared in a function prototype are visible within the prototype.
Function scope:
Function scope begins with the opening curly brace { of a function and ends with its closing
curly brace }. Function scope applies only to labels. A label is used as the target of a goto statement, and
that label must be within the same function as the goto.
Example:
#include<stdio.h>
void display();
int main()
{
printf("In MAIN");
goto xyz;
return 0;
}
void display()
{
xyx:;
printf("In DISPLay");
}
Output: Compilation error
File scope:
Starts at the beginning of the file and ends with the end of the file. It refers only to those
identifiers that are declared outside of all functions. File scope identifiers are visible throughout the entire
file. Variables that have file scope are global.
printf(a=%d,a);
}
Output: a=10
#include<stdio.h>
void main()
{
const int a=10;
printf(a=%d,a);
a=20; //compile error , here a is constant so it does not change its value.
}
Output: compile error.
Volatile:
The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly
specified by the program.
For example, a global variable's address may be passed to the operating system's clock routine and used to
hold the system time. In this situation, the contents of the variable are altered without any explicit
assignment statements in the program.
This is important because most C compilers automatically optimize certain expressions by assuming that
a variable's content is unchanging if it does not occur on the left side of an assignment statement; thus, it
might not be reexamined each time it is referenced. Also, some compilers change the order of evaluation
of an expression during the compilation process. The volatile modifier prevents these changes.
You can use const and volatile together. For example, if 0x30 is assumed to be the value of a port that is
changed by external conditions only, the following declaration would prevent any possibility of accidental
side effects:
const volatile char *port = (const volatile char *) 0x30;
Storage Classes in C:
A storage class defines the scope (visibility) and life time of variables and/or functions within a C
Program.
Scope: The Scope of a variable is the part of a program in which the variable may be visible or available.
Visibility: The program ability to access a variable from the memory.
Life time: The Lifetime of a variable is the duration of time in which a variable exists in the memory
during execution.
C supports four storage class specifiers:
1. auto
2. register
3. static
4. extern
These specifiers tell the compiler how to store the subsequent variable.
The general form of a variable declaration that uses storage class is shown here:
storage_specifier type var_name;
Note that the storage specifier precedes the rest of the variable declaration
Storage class is type modifier or qualifier of data types which decides:
1. Where the variable would be stored.
2. What will be the initial value of the variable, if initial value is not specifically assigned.(i.e. the
default initial value).
3. What is the scope (visibility) of the variable; i.e. in which functions the value of the variable
would be available.
4. What is the life of the variable; i.e. how long would the variable exist.
Storage : Memory.
Default initial value: An unpredictable value, which is often called a 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.
Following program shows how an automatic storage class variable is declared, and the fact that if the
variable is not initialized it contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be...
1211 221
where, 1211 and 221 are garbage values of i and j. Garbage values are unpredictable. Note that the
keyword for this storage class is auto, and not automatic.
main( )
{
auto int i = 1 ;
{
{
{
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
}
The output of the above program is:
111
This is because, all printf( ) statements occur within the outermost block (a block is all statements
enclosed within a pair of braces) in which i has been defined. It means the scope of i is local to the block
in which it is defined. The moment the control comes out of the block in which the variable is defined, the
variable and its value is permanently lost.
To catch my point, go through the following program.
main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
The output of the above program would be:
321
Note that the Compiler treats the three is as totally different variables, since they are defined in different
blocks. Once the control comes out of the innermost block the variable i with value 3 is lost, and hence
the i in the second printf( ) refers to i with value 2. Similarly, when the control comes out of the next
innermost block, the third printf( ) refers to the i with value 1.
Example:
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Here, even though we have declared the storage class of i as register, we cannot say for sure that the
value of i would be stored in a CPU register. Because the number of CPU registers are limited, and they
may be busy doing some other task. In that case variable works as an auto storage class.
As the name suggests, the value of static variables persists until the end of the program. A variable can be
declared static using the keyword static like.
static datatype variable_name;
Static variables may be either an internal type or an external type depending on the place of declaration.
Internal static variables (Local) are those which are declared inside a function. The scope of internal
static variables extends up to the end of the function in which they are defined.
Internal static variables are similar to auto variables, except that they remain in existence throughout the
remainder of the program.
External static variables (Global) are declared outside of all functions and are available to all the
functions in that program. The difference between a static external variable and a simple external variable
is the static external variable is available only within the file where it is defined while the simple external
variable can be accessed by other files.
The features of a variable defined to have a static storage class are as under:
Storage :Memory
Default initial value: Zero
Scope: Local to the block in which the variable is defined.
Life: Value of the variable persists between different function calls.
Compare the two programs and their output given below to understand the difference between the
automatic and static storage classes.
The programs above consist of two functions main( ) and increment( ). The function increment( ) gets
called from main( ) thrice. Each time it increments the value of i and prints it. The only difference in the
two programs is that one uses an auto storage class for variable i, whereas the other uses static storage
class.
Like auto variables, static variables are also local to the block in which they are declared.
The difference between them is that static variables dont disappear when the function is no longer
active. Their values persist. If the control comes back to the same function again the static variables have
the same values they had last time around.
In the above example, when variable i is auto, each time increment( ) is called it is re-initialized to one.
When the function terminates, i vanishes and its new value of 2 is lost. The result: no matter how many
times we call increment( ), i is initialized to 1 every time.
On the other hand, if i is static, it is initialized to 1 only once. It is never initialized again. During the first
call to increment( ), i is incremented to 2. Because i is static, this value persists.
The next time increment( ) is called, i is not re-initialized to 1; on the contrary its old value 2 is still
available. This current value of i (i.e. 2) gets printed and then i = i + 1 adds 1 to i to get a value of 3.
When increment( ) is called the third time, the current value of i (i.e. 3) gets printed and once again i is
incremented. In short, if the storage class is static then the statement static int i = 1 is executed only
once, irrespective of how many times the same function is called.
If declared a static variable or function globally then its visibility will only the
file in which it has declared not in the other files.
For example:
(a)
#include<stdio.h>
static float a=144.0f; //global to all function
int main()
{
{
printf("%d",a); //variable a is visible here.
//printf("%d",b); variable b is not visible here.
}
printf("%d",a); //variable a is visible here.
//printf("%d",b); variable b is not visible here.
return 0;
}
static int b=5; //Global to only calculation function
void calculation(){
printf("%d",a); //variable a is visible here.
printf("%d",b); //variable b is visible here.
}
(b) Consider a c program which has written in two files named as one.c and two.c:
//one.c
#include<conio.h>
static int i=25;
static int j=5;
void main()
{
sum();
}
//two.c
#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/**
Above two lines will search the initialization statement of variable i and j either in two.c (if initialized
variable is static or extern) or one.c (if initialized variable is extern)
*/
extern void sum(){
int s;
s=i+j;
printf("%d",s);
}
Compile and execute above two file one.c and two.c at the same time:
Output: Compilation error: Unknown symbol i and j.
Hence we can say variable i and j which has initialized into two.c is not visible in file one.c. This example
proves visibility (scope) of globally declared static variable is file.
Note: In the above example function sum which was declared and defined in two.c has also storage class
extern. So we can call from other file (one.c).If it will static then we cannot call function sum since static
storage class is only visible to the file where it has declared.
Memory
Zero
Global.
As long as the programs execution doesnt come to an end.
1. Default initial value of extern integral type variable is zero otherwise null.
For example:
#include <stdio.h>
char c;
int i;
float f;
char *str;
int main()
{
printf("%d %d %f %s",c,i,f,str);
return 0;
}
Output: 0 0 0.000000 (null)
2. When we use extern modifier with any variables it is only declaration i.e. memory is not allocated
for these variable. Hence the following program shows compilation error unknown symbols i.
#include <stdio.h>
extern int i; //extern variable
int main()
{
printf("%d",i);
return 0;
}
Output: Compilation error, undefined symbol i.
3. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the
variables.
#include <stdio.h>
extern int i=10; //extern variable
int main()
{
printf("%d",i);
return 0;
}
Output: 10
4. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or
separately. We can only initialize extern variable globally.
#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
//locally.
printf("%d",i);
return 0;
}
Output: Compilation error: Cannot initialize extern variable.
5. If we declare any variable as extern variable then it searches that variable either it has been
initialized or not. If it has been initialized which may be either extern or static* then it is ok
otherwise compiler will show an error.
(a)
#include <stdio.h>
int main(){
extern int i; //It will search the initialization of
//variable i.
printf("%d",i);
return 0;
}
int i=20; //Initialization of variable i.
Output: 20
(b)
#include <stdio.h>
int main(){
extern int i; //It will search the any initialized
//variable i which may be static or
//extern.
printf("%d",i);
return 0;
}
extern int i=20; //Initialization of extern variable i.
Output: 20
(c)
#include <stdio.h>
int main(){
#include <stdio.h>
extern int i;
int i=10; //Initialization statement
i=25;
//Assignment statement
int main(){
printf("%d",i);
return 0;
}
Output: Compilation error
8. If declared an extern variables or function globally then its visibility will whole the program which
may contain one file or many files.
For example consider a c program which has written in two files named as one.c and two.c:
//one.c
int i=25; //By default extern variable
int j=5; //By default extern variable
//Above two line is initialization of variable i and j.
void main()
{
sum();
}
//two.c
#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/* Above two lines will search the initialization
statement of variable i and j either in two.c (if initialized
variable is static or extern) or one.c (if initialized variable
is extern) */
void sum()
{
int s;
s=i+j;
printf("%d",s);
}
Compile and execute above two file one.c and two.c at the same time:
Output: 30
Hence we can say variable i and j which has initialized into two.c is also visible in file one.c. This
example proves visibility (scope) of globally declared extern variable is program.
Note: In the above example function sum which was declared and defined in two.c has also storage class
extern. So we can call from other file (one.c).If it will static then we cannot call function sum since static
storage class is only visible to the file where it has declared.
9. An extern variables or functions have external linkage. An external linkage variables or functions
are visible to all files.
Scope
Block
Block
Life time
Block
Block
Globally
Locally
Globally
Locally
Globally
static
extern
Block
File
Block
Program
Program
Program
Program
Program
int getchar(void);
getchar() function waits until a key is pressed and then returns its value. The key pressed also echoed
(displayed) on to the screen.
The getchar() echos the character on to the screen, but unfortunately enter key to be typed following the
input character.
Example:
void main()
{
char ch;
printf(enter the character );
ch=getchar(); //will echo character on the screen ,must be followed by enter key
printf(%c,ch);
}
Problem with getchar()
1. The getchar() is implemented in such a way that , it buffers input until ENTER key is pressed. This is
called line-buffered input. (you have to press ENTER before any character is returned).
2. getchar() inputs only one character each time it is called, line buffering may leave one or more
characters waiting in the input queue.
getch () :
getch() accepts only single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
syntax :
int getch(void);
the getch() function waits for a key press, after which it returns character immediatey.
Example:
void main()
{
char ch;
printf(enter the character );
ch=getch(); //will not echo character on the screen and no need of enter key
printf(%c,ch);
}
getche() :
Like getch(), getche() also accepts only single character from the keyboard, but unlike getch(), getche()
displays the entered character in the screen.
Syntax :
int getche(void);
Example:
void main()
{
char ch;
printf(enter the character );
ch=getch(); //will not echo character on the screen and no need of enter key
printf(%c,ch);
}
gets() :
gets() accepts (reads) string of characters including spaces from the standard Input device (keyboard).
gets() stops reading character from keyboard only when the enter key is pressed.
Syntax : char* gets(char *str);
Where str is a pointer to a character array that receives the characters entered by the user.
Example:
void main()
{
char str[50];
printf(enter the string);
gets(str);
printf(%s,str);
}
Putchar():
Putchar() writes a character to the screen at the current cursor position. That is putchar() displays
one character at a time to the Monitor.
putchar(char ch);
Example:
void main()
{
char ch;
printf(enter the character );
ch=getchar();
putchar(ch); //display the character on to the screen.
}
puts() :
puts displays a single / paragraph of text to the standard output device.
int puts(const char *s);
Example:
void main()
{
char str[50];
printf(enter the string);
gets(str);
puts(str);
}
Global Variable
Global Variables are declared before the main
function (outside the function).
Global Variables can be accessed in any function.
Global Variables are alive till the end of the
program.
They do not get recreated if the function is recalled.
They are implemented by associating memory
locations with variable names
Examples:
In the above example, first we divide 'a' by 'b' without typecasting. While in the second attempt we
typecast both 'a' and 'b' to float and then divide them.
So, what happens is, in the first attempt, the compiler knows both 'a' and 'b' are integers so it ignores the
floating part of the result and stores the result of a/b in a temporary integer variable and then assign the
value of this temporary integer variable to 'c'. So despite of 'c' being a float, the final value that 'c' gets is
an integer ie '0' in this case.
While in the second attempt, as both 'a' and 'b' are individually typecasted as 'float', so this typecasting
makes compiler think as if both 'a' and 'b' are floats, so the compiler retains the floating part of the result
and assigns the float value to 'c'.
Debugging
Testing can and should be planned, designed Procedure and duration of debugging cannot be so
and scheduled.
constrained.
Testing is a demonstration of error or
apparent correctness.
INTERPRETER
Example : C Compiler
Character represented
Double quotation mark
Escape
sequence
Character represented
\'
\?
Question mark
\\
Backslash
\a
Alarm(beep,bell)
\b
Backspace
\f
Formfeed
\n
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\n is called newline and it takes the cursor to the next line. The new line character '\n' moves to
the start of the next line. This character is often mapped to 012 (LF) on ASCII systems.
The horizontal tab character '\t' moves to the next horizontal tabulation on the current line. If
currently at or past the last tab, it results in unspecified behavior (Often, this can include moving
to the end of the current line, or the start of the next, or to the first tab on the next line.). This
character is often mapped to 011 on ASCII.
The vertical tab character '\v' moves to the beginning of the line at the next vertical tabulation. If
currently at or past the last vertical tab, it results in unspecified behaviour. This character is often
mapped to 013 on ASCII.
\b moves the cursor one position to the left of its current position. The backspace character \b
moves to the previous position within the line. This character is often mapped to 010 on ASCII
systems.
\r takes the cursor to the beginning of the line in which it is currently placed. The carriage
return character '\r' moves to the start of the current line. This character is often mapped to 015
on ASCII.
\a alerts the user by sounding the speaker inside the computer. The alert character '\a' produces
an audible or visible alert when output. This character is often mapped to 007 on ASCII systems.
Form feed advances the computer stationery attached to the printer to the top of the next page.
The form feed character '\f' starts a new page. This character is often mapped to 014 on ASCII.
Characters that are ordinarily used as delimiters... the single quote, double quote, and the
backslash can be printed by preceding them with the backslash.