--------------------------------------------------------------------------------------------------------------------------
Prepared By : Uday Shah - HOD (IT)
Contact No : 7600044051
E-Mail : rupareleducation@gmail.com
“C”
What is Language
·
Language is a collection of words and symbols
which can be used to perform certain task or activities and to establish a
communication between person to person.
- In the same manner
computer languages are the collection of predefine key words which can be
used to perform certain task and to communicate between two entities like
between two machines or between human and computers or computers and
others peripherals.
There are three different level of programming languages.
They are
(1) Machine languages (low level)
(2) Assembly languages
(3) Procedure Oriented languages (high level)
(4) Fourth Generation languages (4 GLS)
(1) Machine Languages :-
·
Computers are made of No. of electronic
components and they all are two – state electronic components means they
understand only the 0 and 1.
·
Therefore the instruction given to the computer
must be written using binary numbers.
·
1and 0. Computers do not understand English or
any other language but they only understand or respond to binary numbers (0 and
1). So each computer has its own Machine languages.
(2) Assembly Languages :-
·
As it was very tedious to understand and remember
0’s representing numerous data and instruction. So to resolve this problem
mnemonics codes were developed.
·
For example add is used as symbolic code to
represent addition.
·
SUB is used for subtraction.
- They are the symbolic representation of certain combination of
binary numbers
for example
SUB
·
Which represents certain actions as computer
understand only Machine language instructions a program written in Assembly
Language must be translated into Machine languages.
·
Before it can be executed this translation if
done by another program called assembler.
·
This assembler will translate mnemonic codes into
Machine languages.
(3) Procedure Oriented Languages
·
In earlier assembly languages assembler programs
produced only one Machine languages instruction for every assembly languages
instruction.
·
So to resolve this problem now assembler were
introduced.
·
Which can produce several machine level
instructions for one assembly language instruction.
·
Thus programmer was relieve from the task of
writing and instruction for every machine operation performed. These languages
contains set of words and symbols and one can write program with the
combination of these keywords.
·
These languages are also called high level
languages. Basic, Fortran, Pascal and COBOL.
·
The most important characteristic of high level
languages is that it is machine independent and a program written in high level
languages can be run on any computers with different architecture with no
modification or very little modification.
WHAT IS LANGUAGE TRANSLATORS?
·
As we know that computer understand only the
instruction written in the Machine language.
·
Therefore a program written in any other language
should be translated to Machine language.
·
For this purpose special programs are available
they are called translators or language processors.
·
This special programs accept the user program and
check each statement and produces a corresponding set of Machine language
instructions.
There are two types of Translators.
(1) Compiler :-
·
A Compiler checks the entire program written by
user and if it is free from error and mistakes then produces a complete program
in Machine language known as object program.
·
But if it founds some error in program then it
does not execute the single statement of the program.
·
So compiler translate whole program in Machine
language before it starts execution.
(2) Interpreters :-
·
Interpreters performs the similar job like
compiler but in different way.
·
It translates (Interprets) one statement at a
time and if it is error – free then executes that statement.
·
This continues till the last statement in the
program has been translated and executed.
·
Thus Interpreter translates and executes the
statement before it goes to next statement.
·
When it founds some error in statement it will
immediately stop the execution of the program.
·
Since compiler of Interpreter can translate only
a particular language for which it is designed one has to use different
compiler for different languages.
Difference of
Compiler – Interpreter :
·
Error finding is much easier in Interpreter
because it checks and executes each statement at a time.
·
So wherever it fine some error it will stop the
execution.
·
Where Compiler first check all the statement for
error and provide lists of all the errors in the program.
·
Interpreter take more time for the execution of a
program compared to Compilers because it translates and executes each statement
one by one.
WHY ‘C’ LANGUAGE ?
·
In early of 1960 there were many languages
available but they were used for some specific purpose.
·
For example Cobol was used for commercial
application Fortran was used for some scientific and engineering application.
·
So at this stage people were searching some language
which can fulfill the need of all type of application.
·
So invention of different language taken place. The
‘C’ language becomes very popular due to its robustness rich set of built in function
and operators that can be used to write any complex program.
Sr. No.
|
Year
|
Language
|
Developer
|
Remarks
|
1
|
1960
|
ALGOL
|
International
Committee
|
Too General, Too
Abstract
|
2
|
1963
|
CPL
|
|
|
3
|
1967
|
BPCL
|
Martin Richards
&
|
|
4
|
1970
|
B
|
Kent Thomson at
AT&T
Laboratory
|
|
5
|
1972
|
C
|
Denis Ritchie at
AT&T
Laboratories
|
Modular, General
|
FEATURES OF C LANGUAGE
There are several reasons why many computer professionals
feel that C is at the top of the list :
FLEXIBLILITY:
·
C is a powerful and flexible language.
·
C is used for projects as diverse as operating
system, word processor, graphics, spreadsheets and even compilers for other
language.
·
C is a popular language preferred by professional
programmers.
·
As a result, a wide variety of C compilers and
helpful accessories are available.
PORTABILITY:
·
C is a portable language.
·
Portable means that a C program written for one
computer system can be run on another system with little or no modification.
·
Portability is enhanced by the ANSI standard by
C, the set of rules for C compilers.
COMPACTNESS:
·
C is a language of few words, containing only a
handful terms, called keywords, which serve as the base on which the
language’s functionality is built.
·
You might think that a language with more keyword
would be more powerful.
·
This isn’t true. As you will find that it can be
programmed to do any task.
REUSABILITY:
·
C is modular, C code can and should be written in
routine called functions.
·
These functions can be reused in other
applications or programs.
·
By passing pieces of information to the function,
you can create useful, reusable code.
C AS MIDDLE
LEVEL LANGUAGE
All programming languages can be divided into two categories:
Problem oriented languages or high languages :
·
Examples of languages falling in this category
are FORTRAN, BASIC, Pascal, etc.
·
These languages have been designed to give a
better programming efficiency, faster program development.
·
Generally these languages have better programming
capability but they are less capable to deal with hardware or Hardware related
programming.
Machine oriented languages of Low Level Languages
:
·
Examples of languages falling in this category
are Assembly language and Machine Language.
·
This languages have been designed to give a
better machine efficiency i.e. faster program execution.
·
Generally these languages have better hardware
programming capability but it is very difficult and tedious to do create
complex application like and business application or some commercial
application
C as Middle Level Language :
C stands in
between these two categories. That’s why it is called a Middle Level Language, since
it was designed to have both; a relatively good programming efficiency (as
compared to Machine Oriented Language) and a relatively good machine efficiency
(as compared to Problem Oriented Language).
DATA INPUT AND OUTPUT
·
As we know that any c program is made up of 1 or
more then 1 function. Likewise it use some functions for input output process.
·
The most common function are printf() and
scanf().
Printf() function :
·
Printf() function is use to display something on
the console or to display the value of some
variable on
the console The general syntax for printf() function is as follows
printf(<”format
string”>,<list of variables>);
·
To print some message on the screen
·
Printf(“God is great”);
·
This will print message “God is great” on the
screen or console.
·
To print the value of some variable on the screen
Integer Variable :
int a=10;
printf(“%d”,a);
Here %d is format string
to print some integer value and a is the integer variable whose valuewill be
printed by printf() function. This will print value of a “10” on the screen. You can make
this output interactive
by writing them
Int a=10;
Printf(“a=%d”,a);
This will
print “a=10” on the screen
·
To print multiple variable’s value one can use
printf() function in following way.
Int p=1000,r=10,n=5;
Printf(“amount=%d rate=%d
year=%d”,p,r,n);
This will
print “amount=1000 rate=10 year=5” on the screen
·
Float Variable :
Float per=70.20;
printf(“Percentage=%f”,per);
Here %f is format
string to print some float(real) value and per is the float variable whose value
will be printed by printf() function. This will print value of a
“Percentage=70.20” on the screen.
·
Character Variable :
char ans=’Y’;
printf(“Answer=%c”,ans);
Here %c is format
string to print single character value and ans is the character variable
whose value will be printed by printf() function. This will print value of a
“Answer=Y” on the screen.
·
Suppose we want to print “Amar” on the screen
with character variable
Char
c1=’A’,c2=’m’,c3=’a’,c4=’r’ ;
Printf(“Name = %c %c %c
%c”,c1,c2,c3,c4);
This will
print “Name=A m a r” on the screen. You can use single printf() function to
print different data type variable’s value also.
Example :
Int rno=10;
Char res=’P’;
Float per=75.70;
Printf(“Rollno=%d
Result=%cPercentage=%f”,rno,res,per);
This will print message
“Rollno=10 Result=P Percentage=75.70” on the screen.
Scanf() Function :
·
Scanf() function is use to read data from
keyboard and to store that data in the variables. The general syntax for
scanf() function is as follows.
Scanf(“Format
String”,&variable);
·
Here format string is used to define which
type of data it is taking as input this format string can be %c for
character, %d for integer
variable and %f for float variable.
·
Where as variable the name of memory location or
name of the variable and & sign is an operator that tells the compiler the
address of the variable where we want to store the value.
·
One can take multiple input of variable with
single scanf() function but it is recommended that there should be one variable
input with one scanf() function.
Scanf(“Format
string1,format string2”,&variable1,&variable2);
For Integer Variable :
Int rollno;
Scanf(“%d”,&rollno);
Printf(“Enter rollno=”);
Here in
scanf() function %d is a format string for integer variable and &rollno
will give the address of variable rollno to store the value at variable rollno
location..
For Float Variable :
Float per;
Printf(“Enter
Percentage=”);
Scanf(“%f”,&per);
Here in
scanf() function %f is a format string for float variable and &per
will give the address of variable per to store the value at variable per
location.
For Character Variable :
Char ans;
Printf(“Enter answer=”);
Scanf(“%c”,&ans);
Here in
scanf() function %c is a format string for character variable and &ans
will give the address of variable ans to store the value at variable ans
location.
Single character input – the getchar( ) function
:
·
Single characters can be entered into the
computer using the “C” library function getchar. The getchar function is a part
of the standard “C” language I/O library.
·
It returns a single character from a standard
input device (typically a keyboard).
·
The function does not required any arguments
through a pair of empty parentheses must follow the word getchar.
·
In general terms, a reference to the getchar
function is written as.
Character
variable=getchar();
·
Where character variable refers to some
previously declared character variable.
·
A “C” program contains the following statements.
char c;
c=getchar();
·
The first statement declares that c is a character type variable.
·
The second statement causes a single character to be entered from
the standard input device and then assigned to c.
·
If an end-of file condition is encountered when reading character
with the getchar function, the value of the symbolic constant EOF will
automatically be returned.
·
The detection of EOF in this manner offers a convenient way to
detect an end of file, whenever and wherever it may occur.
·
Appropriate corrective action can be taken. The getchar() function
can also be used to read multicharacter strings, by reading one character at a
time a multiples loop.
Single character output – The putchar( )
function:
·
Single character can be displaye using the C
library function putchar.
·
The putchar function, like getchar is a part of
the standard “C” language I/O library.
·
It transmits a single character to a standard
output device.
·
The character being transmitted will normally be
represented as a character-type variable.
·
It must be expressed as an argument to the function, enclosed in
parentheses following the word putchar.
·
In general a reference to the putchar function is written as
Putchar (character variable)
·
Where character variable refers to some
previously declared character variable. A “C” program contains the following
statements.:
char c=’a’;
putchar(c);
·
The first statement declares that c is character
type variable.
·
The second statement causes the current value of
c to be transmitted to the standard output device where it will be displayed.
·
The putchar function can be used to output a
one-dimensional, character type array.
·
Each character can then be written separately
within a loop
If we want to
perform certain action for no of times or we want to execute same statement or
a group of statement repeatedly then we can use different type of loop
structure available in C. Basically there are 3 types of loop structure
available in C
(1) While loop
(2) Do… while
(3) For loop
While statement :
The while statement is
used to carry out looping operations. The general form of the statements
initialization;
while(exp)
{
statement 1;
statement 2;
increment/
decrement;
}
·
The enclose statements within two braces will be
executed repeatedly as long as the expression evaluated as true.
·
When the expression is evaluate a false or when
condition will be false then it will come out from the loop and stop the
execution of that loop.
·
Initialization statement initialize some memory
variable with some value.
·
Increment or decrement operator increase or
decrease the value of operator is use by expression. This statement can be
simple of compound, though it is typically a compound statement, it must
include some features, which eventually offers the value of expression, thus
provides a stopping condition for the loop.
·
In the practice, the included expression is usually
a logical expression that is either true or false. (remember that true
corresponds to non-zero value and false corresponds to zero value).
·
Thus the statement will continue to execute as long
as the logical expression is true.
·
The part of while statement, which contains the
statement, is called the body of the loop.
·
Body of the loop may have one or more statements.
·
The braces are needed only if the body contains two
or more statements. However, it is a good practice to use braces even if the
body has only one statement.
·
Suppose we want to display the consecutive digits 0,1,2,3,…9 with one
digit on the each line. This can be accomplished with the following program
#include<stdio.h>
main ()
{
int digit
= 0;
while(digit<=9)
{
printf(“%d
\n”,digit);
++digit
;
}
}
·
Initially, digit is assigned a value of 0.
·
The while loop then displays the current value of
digit, increases its value by 1 and then repeats the cycle, until the value of
the loop will be repeatedby 10 times, resulting in 10 consecutive lines of
output.
·
Each line will contain a successive integer value,
beginning with and ending with 9.
·
Thus when the program to run, the following output
will be generated :
0 1 2 3 4 5 6 7 8 9
Do-While statement :
Sometimes, however, it is
desirable to have a loop with the test for continuation at the end or each
pass. This can be accomplished by means of the do-while statement. The general
form of do-while statement is
do
{
statement 1;
statement 2;
increment/
decrement;
} while(exp);
·
The enclosed statement within 2 braces will be
executed repeatedly as the value of expression is not zero.
·
Notice that statement will always be executed at
least once.
·
Since the test for repetition does not occur until
the end of the first pass through the loop.
·
The statement can be either simple or compound,
though most applications will require it to be a compound statement.
·
It must include some feature which eventually
alters the value of expression so that the looping action can terminate.
·
Since the expression is evaluated at the bottom of
the loop, the do…while loop construct provides an exit… controlled loop and
therefore the body of the loop is always executed at least once.
·
In practice, expression is usually a logical
expression, which is either true(with a non zero value) or a false(with a value
of 0).
·
The included statement will be repeated if the
logical expression is true.
·
For most applications it is more natural to test
for continuation of a loop at the beginning rather than at the end of the loop
for this reason, the do…while statement is use less frequently than while
statement.
·
Suppose that we want to display consecutive
0,1,2,3,…9 with one digit on each line. This can be accomplished with the
following program
#include<stdio.h>
main ()
{
int
digit = 0;
do
{
printf(“%d
\n”,digit);
++digit
;
}
while(digit<=9);
}
·
The digit is initially assigned a value of 0.
·
The do while loop displays the current value of
digit.
·
Increases it value by 1, and then tests to see if
the current value of digit exceeds 0.If so loop terminates; otherwise the loop
continues, using the new value of digit.
·
Note that
the last is carried out at the end of each pass through the loop.
·
The net effect is that the loop repeated 10 times,
resulting in 10 successive lines of output.
·
Thus, when the program is run the following output
is generated :
0
1 2 3 4 5 6 7 8 9
FOR
statement :
The for statement is another entry controller
that provides a more concise loop control structure. The general form of the
for loop is
for(initialization; test condition;
increment)
{
statement
1;
statement
2;
}
The execution of the for
statement is as follows :
1. Initialization of the control variables is
done first, using assignments statement such as I=0 and count=0. The variables
I and count are known as loop controls.
2. The value of the control variables is tested
using the test condition. The test condition is relational expression, such as
I>0 or I<10 that determines when the loop is terminated and the execution
continues with statement that immediately follows the loop.
3. When the body of the loop is executed, the
control is transferred back to the for statement either evaluating the last
statement is the loop. Now, the control variable is incremented using and
assignment statement such as I=I+1 and if the new value of the control is
satisfied under test condition, then the body of the loop is executed. This
process continues till the value of the control variable fails to satisfy the
test-condition.
(a) Consider the
following segment of a program
for(i=0; i<9; i++)
{
printf(“%d”,
i);
printf(“\n”);
}
·
This for loop is executed 10 times and prints the
digits 0 to 9 in
one line.
·
The three sections within parentheses must be
separated by a semicolons. Note that there is no semicolon at eh end of the
increment section i++.
·
The for statement allows for negative increments.
For example, the loop discussed above can be written as follows
for(i=9; i>=0; i--)
{
printf(“%d”,i)
printf(“/n”);
}
·
This loop is also executed 10 times. But the output
would be from 9 to 0 instead of 0 to 9. Note that, braces are optional when the
body of the loop contains only one statement
Additional
features of for loop :
The for loop in C
has several capabilities that are not found in the other loop constructs. For
example, more than one variable can be initialized at a time in the for
statement.
for(n=1,m=50; n<m; n++, m--)
{
p=m/n;
printf(“%d%d%d
\n”,n,m,p);
}
This is perfectly
valid. The multiple arguments in the increment section are separated by commas.
The third feature
is that the test condition may have nay compound relation and the testing need
not be limited only to the loop control variable. Consider the example below
sum=0;
for(i=1;i<20 && sum<100; i++)
{
sum=sum+i;
printf((“%d
\n”, sum);
}
The loop uses a
compound test condition with the control variable; and external variable sum.
The loop is executed as long as both the conditions I<20 and sum<100 are
true. The sum is evaluated inside the loop.
It is also
permissible to use expressions in the assignment statements of initialization
and increment sections, For example, a statement of the type :
For(z=(m+n)/2; x<0;x=x/2)
is perfectly
valid.
Another unique
aspect of the for loop is that one or more sections can be omitted, if
necessary.
Consider the following statements
m=0;
for(;m!=100;)
{
printf(“%d
\n”, m);
m=m+5;
}
Both the initialization
and increment sections are omitted in the for statement. The initialization has
been done before the for statement and the control variable is incremented
inside the loop. In such cases the sections are left blank. However, the
semicolons separating the sections must remain. If the test condition is not
present, the for statement sets up an
infinite loop.
Such loops can be broken using break or go-to statements in the loop. We can
set up time delay loop using the null statement as follow:
for(j=1000;j>0;j--)
{
}
The loop executed
1000 times without producing any output; it simply causes a time delay. Notice
that the body of the loop contains only a semicolon, known as null statement.
This can also be written as :
for(i=1000; i>0;i--);
This implies that
C compiler will not give an error message. If we place a semicolon by mistake
at the end of a for statement. The semicolon will be considered as a null
statement and the program may produce some nonsense.
Loops can be
nested (i.e. embedded) one within another. The inner and outer loops need not
be generated by the same type of control structure. It is essential that one
loop be completely embedded within the other. There can be no overlap. Also
each loop must be controlled by a different index.
DECISION CONTROL STRUCTURE :
The
if-else statement:
The if-else
statement is used to carry out a logical test and then take one of two possible
actions depending on the outcome of the test (i.e. whether the outcome is true
or false).The else position of the if-else statement is optional. Thus, in its
simplest general form, the statement can be written.
If(expression)
statement;
The expression must be
placed in parenthesis, as shown. In this form, the statement will be executed
only if the expression has non-zero value (i.e. true). If the expression has a
value of zero (i.e. expression is false), then the statement will be ignored.
The statement can be either simple or compound. In practice, it is often
compound statement, which may include other control statements. The general
form of an if statement which include the else clause is
If(expression)
statement 1;
else
statement
2;
If the expression has a
non-zero value (i.e. if expression is true), then statement 1 will be executed.
Otherwise, (i.e. expression is false), statement 2 will be executed. It is
possible to next if…else statement within one-another, just as we did with
loops, there are several different forms that nested if…else two-layer nesting
is : In this situation, one can complete if…else statement will be executed if
expression is nonzero(true) and another complete if else statement will be
executed if expression is false (zero). It is of course, possible that
statement 1, statement2, statement3 and statement4 will contain another if…else
statements. We would then have multi layer nesting. Some other forms of two
layer are :
1 If<exp1>
{
statement1;
}
else
{
if<exp2>
{
statement2;
}
}
2 if<exp1>
{
if<exp2>
{
statement1;
}
else
{
statement2;
}
else
{
statement3;
}
1. If the first if expression has a non-zero
value (i.e. if expression is true), then statement 1 will be executed.
Otherwise, (i.e. expression is false), second if expression is evaluated and
test in else block if it return non zero value then statement 2 will be
executed.
2. If the first if expression has a non-zero
value (i.e. if expression is true), then it check second if expression if
it return non – zero value then statement 1 will be executed. Otherwise statement 2 will be executed. But first if
expression has return zero then execute Statement – 3
3 if<exp1>
{
if<exp2>
{
statement1;
}
else
{
statement2;
}
else
{
if<exp3>
{
Statement3;
}
else
{
Statement4;
}
4 if<exp1>
{
statement1;
}
else if
<exp2>
{
statement2;
}
else if<exp3>
{
Statement 3;
}
else
{
Statement 4;
}
}
}
3. If the first if expression has a non-zero
value (i.e. if expression is true), then it check second if expression and
execute statement 1 or 2 otherwise it check
third if expression and execute statement 3 or 4
4. If the first if expression has a non-zero
value then it execute statement 1 otherwise it check second if expression and
execute statement 2 otherwise execute last if expression and execute statement
3 if all expression are false then it execute statement 4.
THE GOTO STATEMENT :
The goto statement
is used to alter the normal sequence of program execution by transferring
control to some other part of the program. In its general for the goto statement
is written as goto label; Where label is an identifier used to label the target
statement to which control will be transferred.
Control may be
transferred to any other statement within the program. The target statement
must be labeled and the label must be followed by a color. Thus the target
statement will appear as label : statement. Each labeled statement within the
program must have unique label, i.e. no two statement can have same label.
The
common application of goto are :
1. Branching around statement or groups of
statements under conditions.
2. Jumping to the end of a loop under certain
conditions, thus by passing the reminder of the loop during the loop during the
current pass.
3. Jumping completely out of a loop under
certain conditions, thus terminating the execution of the loop.
Branching ground
statement can be accomplished with the if-else statement, jumping to the end of
a loop can be carried out with the continue statement, and jumping out of a
loop easily completed using the break statement. The uses of these structured
features are preferable to the used of the goto statement because the use of
goto tends to encourage logic that skips all over the program.
Occasional situations do
arise, however, in which the goto statement can be useful. Consider, for
example, a situation in which it is necessary to jump out of a doubly nested
loop if a certain conditions are detected. This can be accomplished with two if
break statements. One within each loop, though this is awaked. A batter solution
in this particular situation might make user of the goto statement to transfer
out of both loops at once.
BREAK STATEMENT:
The break statement is used to
terminate loops or to exit a switch. The break statement will break or
terminate the inner-most loop. It can be used within a while, a do-while, a for
or a switch statement. The break statement is written simply as break; Without
any embedded expressions or statement. For example,
For(I=1; I<=10; I++)
{
if(I==5)
break;
printf(“\nI=%d”,I);
}
The output will be 1,2,3,4 and then
break will terminate this loop and stop the execution of the for loop.
CONTINUE STATEMENT
The continue statement is used to
skip or to bypass some step or iteration of looping structure. It does not
terminate the loop but just skip or bypass the particular sequence of the loop
structure. It is simply written as continue.
For(I=1; I<=10; I++)
{
if(I==5)
continue;
printf(“\nI=%d”,I);
}
The output of the above program will
be 1,2,3,4,6,7,8,9,10. The 5th iteration of the loop will be skipped
as we have define the continue for that iteration. So it will not print the
value ‘5’
WHAT IS LANGUAGE TRANSLATORS?
As we know that computer
understand only the instruction written in the Machine language. Therefore a
program written in any other language should be translated to Machine language.
For this purpose special programs are available they are called translators or
language processors. This special programs accept the user program and check
each statement and produces a corresponding set of Machine language
instructions. There are two types of Translators.
(1)
Compiler :-
A Compiler checks the
entire program written by user and if it is free from error and mistakes then
produces a complete program in Machine language known as object program. But if
it founds some error in program then it does not execute the single statement
of the program. So compiler translate whole program in Machine language before
it starts execution.
(2)
Interpreters :-
Interpreters performs the
similar job like compiler but in different way. It translates (Interprets) one
statement at a time and if it is error – free then executes that statement.
This continues till the last statement in the program has been translated and
executed.
Thus Interpreter
translates and executes the statement before it goes to next statement. When it
founds some error in statement it will immediately stop the execution of the
program.
Since compiler of
Interpreter can translate only a particular language for which it is designed
one has to use different compiler for different languages.
Difference
of Compiler – Interpreter :-
Error finding is much
easier in Interpreter because it checks and executes each statement at a time.
So wherever it fine some error it will stop the execution. Where Compiler first
check all the statement for error and provide lists of all the errors in the
program.
Interpreter take
more time for the execution of a program compared to Compilers because it
translates and executes each statement one by one.
SWITCH-CASE Statement :
The switch statement
causes a particular group of statements to be chosen from several available
groups. The selection is based upon the current value of an expression that is
included within a switch statement. The general form of switch-case statement
is
Switch(expression)
{
Case expression1
Statement1;
Statement2;
Case expression2
Statement1;
Statement2;
Case expression3
Statement1;
Statement2;
}
Usually each of
these expression will be written as either an integer constant or a character
constant. Each individual statement following the case labels may be either
simple or complex. Where expression1 1, expression 2,………,expression m represent
constant, integer valued expression .When switch statement is executed the
expression is evaluated and control is transferred directly to the group of
statements whose case labels value matches the value of the expression. If none
of the case-label values matches the value of the expression, then non of the
groups within the switch statement w8ll be selected in this case control is
transferred directly to the statement that follows the switch statement.
Explain Concept of Recursion with example.
Recursion: When any function will call the function
itself, it is called the recursive function. When the same task is to be
performed repetitively then the recursive function can be used.
Example:
For example, factorial of
a number n can be calculated as
n! = n x (n-1) x ……… x 3 x
2 x 1.
Thus,
4! = 4 x 3 x 2 x 1
= 4 x 3!
Hence, n! = n x (n-1)!
Here we have to calculate
the factorial of a number repetitively until the number will become 0 (since 0!
= 1). Thus, the recursion of the function can be used as shown by following
example:
#include<stdio.h>
#include<conio.h>
main()
{
long
int num, ans;
int
fact(int);
clrscr();
printf(“Enter
a number : “);
scanf(“%d”,&num);
ans =
fact(num);
printf(“Factorial of number
(num”) = %ld”,ans);
getch();
}
int
fact(int n)
{
int
f = 1;
if
(n= =1)
return
f;
else
{
f
= n *fact (n-1);
return
f;
}
}
Output:
Enter a
number: 6
Factorial
of number(num!) = 720
Explanation:
Here, first time the
function fact() is called recursively function, that is, it is calling itself,
until value of n becomes 1. At this point value of f is returned to call the
function which is also fact(). This function successively returns the value to
itself until control reaches back to main().
·
main() is called inside main().
When
main() is called inside main() it will be come recursively function.
What is header file? Explain
C language permits modular
programming concept. The whole program can be divided into small individual
modules called functions. All the functions can be put in the different files.
When the functions are put in a single file or they can be put in the different
files. When the functions are put in the different files, these files can to be
included in the main program as external files. This inclusion is done with the
help of preprocessor directives. These files, which are included at the start
of main program, are known as header files.
With standard C package a
standard library of functions are provided which contains standard functions to
perform some common or repetitive task. Following is an example to include
header file in a program:
#include<stdio.h>
stdio.h is a file which
contains various input/output functions.User defined header files contain the
functions written by the user and can be used in various programs and can also
be included in the various programs and in the main program. Following is an
example to include user defined header file in a program:
#include
”mylibrary.h”
File types of header files
Header file purpose
conio.h Declares various functions used
in calling the DOS console I/O routines, like clrscr(); to clean the screen.
stdio.h Defines types and macros
needed for the standard I/O package, like printf() to print string on the
screen.
graphics.h Declares prototypes for the graphics
functions like goto (x, y) to move cursor position to location (x,y).
malloc.h Memory management functions and
variables like malloc() functions used to create memory location.
math.h Declares prototypes for the
mathematical functions, like sqrt(x) to obtain square root of a number x
What is preprocessor - Explain with Suitable Example.
The preprocessor program that processes out source
program before it is passed to the compiler. Preprocessor mainly performs two
types of expansion
II. Macro
substitution
I. File
inclusion
#include<stdio.h>
Is directive which
instructs the preprocessor to replace the content of the library file “standard
input and output”. These files are called header files.
II. Macro
substitution
#define
PI 3.14
Will replace the symbol PI with 3.14,
at all the places in program.
\\ Backslash - It is used to print \ On the Screen
\t Tab - It is used Move Cursor One Tab
Position Further
\b Backspace - It is used to Move cursor one space
Backward
\a Audible Beep - It is used to produce an audible
sound – a beep
\” Double Quotes - It is used to print “ on the Screen
\v Vertical Tab - It is used move cursor on tab
position vertically
\n New Line - It is used to move cursor to start
of new line
The data which is to be stored in
variables during the execution of the program can be of different types. There
are four basic data types supported by ‘C’
Data Type Keyword Used Size in Bytes Range of Values
Character Char 1 -128 to 127
Integer Int 2 -32768
to 32767
Floating point float
4 -3.4e38 to
3.4e38
Large floating point Double 8 -1.7e308 to1.7e308
We can change size and range of the
above data types with the following qualifiers.
sing & unsigned
shot & long
for example
Un signed Int
Can store the values ranging 0 to 255
with the bytes size of 1 bytes.
Long int
Can store value ranging -2147483648
to +2147483647 with byte size of 4 bytes.
Normally if..else..statement is used
for the two way decision making. But when we have a multiple option and
depending upon the different condition different option is to be selected then
if else if ladder is used. The general format for the if…else…if is as bellow.
If (condition 1)
Statement
1
Else
if (condition 2)
Statement
2
Else
if (condition 3)
Statement
3
.
.
.
Else
if ( condition N)
Statement
N
Else
Default
statement.
For
example if we want to make a program for calculating discount on the basic
price with the following discount terms.
Price with the following discount
terms.
For Price <= Rs. 100 No Discount
For Price >100 but <=200 10% Discount
For Price >200 but <=300 20% Discount
For Price >300 30% Discount
Then this program can be written
using if…else…if ladder as bellow.
Void main ()
{
float
price, discount;
printf(“Enter
The Price ::”);
scanf(“%f”,&price);
if(price
<= 100)
discount
= 0
else
if (price <= 200)
discount
=0.1* price;
else
if (price <= 300)
discount
= 0.2 * price;
else
discount
= 0.3 * price;
prince(“Discount = %f “,discount):
getch();
}
‘Do while’ loop is an exit control
loop. So the statement written in the body of the loop is executed first and
then the condition is checked. If the condition will be true then body will be
executed again and again as long as the condition is true. And control will
come out of the loop as soon as the condition will become false.
Syntax of do…while statement is as bellow
do
{
Body
of loop;
}while
(condition);
Here,
it is ensured that the body the body will be executed at least once even if the
condition will be false. So in situation when it is necessary to execute body
before the test is performed, this loop can be used.
For
example if we want to write a program is which we want the user to enter the positive
integers and entry will be stopped as soon as negative number is entered by the
use then do-while loop can be used in following manner
main()
{
Int
num;
do
{
Printf(“enter
a number:”);
Scanf(“%d”,&num);
}while(num>0);
}
Explain storage class in ‘ C ‘ ?
Storage class of the ‘C’ variables is decided by the
scope and life of the variables there are four storage classes in C language
Local
, Global , Static And Register Variables.
·
Local
Variables are defined inside the function and the scope of these variables is
limited to the function in which they are defined. The life of the variable is
also limited in to the function in which they are defined.
·
Global
variables are defined outside the function. They are accessible to all the
function used in program.
·
Static
variables can be global or local. But the main difference between the local and
static variable is that the life of local variables is ended once the control
goes out of the function in which the local variables are defined. While static
variables remains in the memory even if the control goes out of the function in
which they are defined.
·
Register
variables are stored directly in the register of the processor rather then in
the memory like other variables. The register variables are faster to access
than the other variables but at the same time the space variable for the register variables is
limited.
Explain Built
in Operators.
There are four
types of built in operators.
1.
Mathematical
Operators.
a. + addition
b. - Substriction
c. / Division
d. * Multiplication
e. % Remainder
(Mod)
2.
Relational
Operators.
a. == Equal
b. != Not
Equal
c. > Greater
Than
d. < Less
Than
e. >= Greater
Than or Equal
f. <= Less
Than Or Equal
3.
Logical
Operators.
a. ! Boolean
Not
b. && Boolean
AND
c. || Boolean
OR
4.
Bitwise
Operator.
a. ~ Bitwise
Negation
b. & Bitwise
AND
c. | Bitwise
OR
d. ^ Bitwise
Exclusive OR
? : operator
? : is a ternary conditional expression operator. This
operator is used with the operator for decision making in place of if…else…
statement for example.
if ( i > 4)
{
x=4;
}
else
{
x=0;
}
Can be written using ? operator as below
x=(i>4) ? 4 : 0 ;
Size of Operator
The size of operator is used to find the bytes
occupied by a variables in the memory location. The standard syntax of sizeof operator is.
m = sizeof ( variable name);
here the sizeof
operator returns the number of bytes occupied by a variable and store in to m. for
example if any variable say num is of integer type
m = sizeof(num);
will store 2 in m as the bytes occupied
by an integer variable is 2.
List all data types of ‘C’ with their size in Bytes
Following are the
basic data types used in ‘C’
Type Size Range
Char 1 -128 to +127
Unsigned Char 1 0
to 255
Signed Char 1 -128 to +127
Int 2 -32768 to
+32767
Unsigned Int
2 0
to 65535
Signed Int
2 -32768 to
+32767
Short Int
2 -32768 to
+32767
Unsigned Short
Int 2 0
to 65535
Signed Short Int 2 -32768 to
+32767
Long Int
4 -2,147,483,647 to 2,147,483,647
Signed Long Int 4 0
to 4,294,967,295
Float 4 3.4e-38 to 3.4e +38
Double 8 -1.7e308
to 1.7e +308
Long Double 16
Array:
If there are
number of similar data items to be stored, it will be difficult to give
different variable names to each item. For example, marks of 50 students,
salary of 150 employees of a company etc. In this type of problem, common
variable name with subscript are used to store the different values. This type
of subscription variables is known as array variable.
Difference between array and structure:
Array can be used
to represent the group of data with the same data types like integer, float
etc. For example, marks of the student of a class or age of each person form
the group of 100 persons.
While structure is
used to represent the group of the data with the different data types. For
example, description about the book, which will contain the information like name,
price, no. of pages, author, publication year etc.
Array can be of
single dimension or of multiple dimensions. The declaration of single dimension
array will be as below:
int marks[50];
float percentage [50]; etc…
While structure is
to be defined as a structure variable and then it is to be declared. For
example structure for the information about the book can be declared as below.
Definition of structure
struct book
{
char name[50];
float price;
int pages;
};
declaration of
structure
struct book b1;
Here b1 is a
variable of type structure book.
Storage class of
the ‘C’ variables is decided by the scope and life of the variables. There are
four storage classes in C language:
Local, Global, Static and Register
variables.
Local Variables
are defined inside the function and the scope of these variables is limited to
the function in which they are defined. The life of the variable is also
limited in to the function in which they are defined.
Global variables
are defined outside the function. They are accessible to all the functions used
in the program.
Static variables
can be global or local. But the main difference between the local and the
static variable is that the life of local variables is ended once the control
goes out of the function, in which the local variables are defined. While
static variables remain in the memory even if the control goes out of the
function, in which they are defined.
Register variables
are stored directly in the register of the processor rather than in the memory
like other variables. The register variables are faster to access than the
other variables but at the same time the space variable for the register
variables is limited
Logical
Operators :
‘C’
provides three logical operations. They are :
Operator Meaning
&& AND
|| OR
! NOT
These
operators are referred to as logical AND logical OR and logical NOT respectively.
The following table shows the result of the combined expressions depending on
the value of the expression:
Assignment
Operators:
Assignment
operators are use to form assignment expressions, which assign the value of an
expression to an identifier. The most commonly used assignment operator is =.
Assignment expression that make use of this operator are written in the form
User Defined Functions
We have mentioned earlier that one of
the strengths of C language is that C functions are easy to define and use. C
functions can be classified into two categories, namely, library functions and
user-defined functions. main is an example of user defined function. printf and
scanf belong to the category of library functions. The main distinction between
user-defined and library function is that the former are not required to be
written by user while the latter have to be developed by the user at the time
of writing a program. However the user defined function can become a part of
the C program library.
The use of functions in C serves many
advantages:
1. It facilitates top-down
modular programming . In this programming style, the high level of the overall
problem is solved first while the details of each lower-level function are
addressed later.
2. The length of a source
program can be reduced by using functions at a appropriate places.
3. It is easy to locate and
isolate a faulty function for further investigations.
4. A function may be used by
many other programs. This means that a C programmer can build on what others
have already done, instead of starting from scratch.
A Multi-Function Program
A function in simple terms can be
viewed as a black box which takes in some value (if required) and outputs some
result. The internal details of the function are hidden from rest of the
program. Every C program can be designed using a collection of these black
boxes.
THE SCPOE AND LIFETIME OF VARIABLES
IN FUNCTION
A variable in C can have any one of
the four storage classes :
Automatic variables :
Automatic variables are declared
inside a function in which they are to be utilized. They are created when the
function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are therefore private to the
function in which they are declared. Because of this property, automatic
variables are also referred to as local or internal variable.
A variable declared inside a function
without storage class specifications, by
default, an automatic number in the example below is automatic.
One important feature of automatic variable is
that their value cannot be changed accidentally. This assures that we may
declare and use the same variable name in different function in the same
program without causing any confusion to the compiler. There two consequences of
the scope and longevity of auto variables. First any variable local to main will normally live
throughout the whole program, although, it is active only in main. Secondly,
during recursion,
the nested variables are unique auto
variables, a situation similar to function, nested auto variable with identical
names.
Automatic, variable can also be defined within
a set of braces known as “blocks” they are meaningful only inside the block
where they are defined.
External variables :
Variables that are both alive and
active throughout the entire program are known as external variables. They are
also known as global variables. Unlike function in the program external
variables are declared outside a function. For
example the external declaration of integer number and float length
might appear is :
Static variables :
As the name suggest, the value of
static exist until the end of the program. A variable can be declared static
using the keyword static like:
Static int x;
Static float y;
A static variable may be either an
internal type or an external type depending on the piece of declaration.
Internal static variables are those which are declared inside a function. The
scope of internal static variable extend
up to the end of the function in which
they are defined. Therefore, internal static variable are similar to auto variables, except that they remain in
existence throughout the remainder of the program. Therefore, internal static
variables can be used to retain values between function calls.
A static variable is initialized only once,
when the program is compiled. It is never initialized again. An external static
variable is declared outside that program. The difference between a static
external variable and simple external variable is that the static external
variable is available only within the file where it is defined while the simple
external variables can be accessed by other files.
It is possible to control the scope of the
function. For example, we would like a particular function accessible only to
the function in the file in which it is defined. And not to function in other
files. This can be accomplished by defining that function with the storage
class static.
Register variable:
We can tell the compiler that a
variable should be kept in one of the machine’s register instead of keeping in
the memory where normal variables are stored. Since a register access is much
faster than a memory access. Keeping frequently accessed variables in the
register will lead to faster execution of program. This is done as follows :
Register int count;
Since only a few variables can be placed in
the register, it is important to carefully select the variable for the purpose.
POINTERS
A pointer is a variable that represents the
location of a data item, such as a variable or an array element. Pointers have
a number of useful applications. For example, pointer can be used to pass
information back and forth between a function and a reference point. In
particular, other provides a way to return multiple data items from a function via arguments. Pointer also
permits references to other functions to be specified as arguments to a given
function. This has the effect of passing function as arguments to the given functions.
Pointers are also closely associated with arrays and therefore provide an
alternative way to access individual array elements.
POINTER DECLARATIONS :
Pointer variables, like all other
variables, must be declared before, they may be used in C program. When a
pointer variable is declared, the
variable name must be preceded by an asterisk(*). This identifies the fact that
the variable is a pointer. The data type that appears in the declaration refers
to the object of the pointer. i.e. the data item that is stored in the address
represented by the pointer, rather than the pointer itself.
PASSING POINTER TO A FUNCTION :
Pointers are often passed to a
function as arguments. This allows data items within the calling portion of the
program to be accessed by the function altered within the function and then
returned to the calling portion of the program in altered form. We refer to
this use of pointer as passing of arguments by reference (or by address or by
location).
When an argument is passed by value, the data
item is copied to the function. Thus any alteration made to the data item
within the function is not carried over into the calling routine. When an
argument is passed by reference, however (i.e. when a pointer is passed to a
function) the address of a data item is passed to the function. The contents of
that address can be accessed freely, either within the function or within the
calling routine. More over change that is made to the data item(i.e. to the
contents of the address) will be recognized in both the function and the calling
routine, thus the use of pointer as a
function argument permits the corresponding data item to be altered globally
from within the function. When pointers are used as argument to a function the
formal arguments that are pointers must each be preceded by an asterisk. Also,
if a function declaration is included in the coding portion of the program. The
data type of each argument that corresponds to a pointer must be followed by an
asterisk.
ARRAY OF POINTERS:
A multidimensional array can be
expressed in terms of an array of pointers rather than as a pointer to a group
of contiguous arrays. In such situations the newly defined array will have one
less dimension that the original multidimensional array. such pointer will
indicated the beginning of separate (n-1) dimensional array.
Structures
Simple Structures
A structure is a collection of one or
more variables types grouped under a single name for easy manipulation.
The variables in a structure, unlike
those in an array, can be of different variable types.
A structure can contain any of C's
data types, including arrays and other structures. Each variable within a
structure is called a member of the structure.
The struct keyword is used to declare
structures.
A structure is a collection of one or
more variables (structure_members) that have been grouped under a single name
for easy man-ipulation.
The variables don't have to be of
the same variable type, nor do they have
to be simple variables.
Structures also can hold arrays,
pointers, and other structures.
The keyword struct identifies the
beginning of a structure definition. It's followed by a tag that is the name
given to the structure.
What is the purpose
of main( ) function ?
The function main( ) invokes other
functions within it.It is the first function to be called when the program
starts execution.
·
It is the
starting function
·
It returns
an int value to the environment that called the program
·
Recursive
call is allowed for main( ) also.
·
It is a
user-defined function
·
Program execution
ends when the closing brace of the function main( ) is reached.
·
It has two
arguments 1)argument count and 2) argument vector (represents strings passed).
Any user-defined name can also be used as parameters for main( )
instead of argc and argv
What will the preprocessor do for a program ?
The C preprocessor is used to
modify your program according to the preprocessor directives in your source
code. A preprocessor directive is a statement (such as #define) that gives the
preprocessor specific instructions on how to modify your source code.
The preprocessor is invoked as the
first part of your compiler program’s compilation step. It is usually hidden
from the programmer because it is run automatically by the compiler.
The preprocessor reads in all of
your include files and the source code you are compiling and creates a
preprocessed version of your source code. This preprocessed version has all of
its macros and constant symbols replaced by their corresponding code and value
assignments.
If your source code contains any conditional preprocessor
directives (such as #if), the preprocessor evaluates the condition and modifies
your source code accordingly.
What is the purpose of
realloc( ) ?
The function realloc(ptr,n) uses
two arguments. the first argument ptr is a pointer to a block of memory for
which the size is to be altered. The second argument n specifies the new size.
The size may be increased or decreased. If n is greater than the
old size and if sufficient space is not available subsequent to the old region,
the function realloc( ) may create a new region and all the old data are moved
to the new region.
What is Preprocessor ?
The preprocessor is used to modify
your program according to the preprocessor directives in your source code.
Preprocessor directives (such as
#define) give the preprocessor specific instructions on how to modify your
source code. The preprocessor reads in all of your include files and the source
code you are compiling and creates a preprocessed version of your source code.
This preprocessed version has all
of its macros and constant symbols replaced by their corresponding code and
value assignments. If your source code contains any conditional preprocessor
directives (such as #if), the preprocessor evaluates the condition and modifies
your source code accordingly.
The preprocessor contains many
features that are powerful to use, such as creating macros, performing
conditional compilation, inserting predefined environment variables into your
code, and turning compiler features on and off.
For the professional programmer, in-depth knowledge of the
features of the preprocessor can be one of the keys to creating fast, efficient
programs.
When should a type cast be used ?
There are two situations in which
to use a type cast. The first use is to change the type of an operand to an
arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in
order to interface with functions that expect or return void pointers.
What is the difference between calloc() and
malloc() ?
1. calloc(...) allocates a block of memory for an array of
elements of a certain size. By default the block is initialized to 0. The total
number of memory allocated will be (number_of_elements * size).
malloc(...) takes in only a single argument which is the memory
required in bytes. malloc(...) allocated bytes of memory and not blocks of
memory like calloc(...).
2. malloc(...) allocates memory blocks and returns a void pointer
to the allocated space, or NULL if there is insufficient memory available.
calloc(...)
allocates an array in memory with elements initialized to 0 and returns a
pointer to the allocated space. calloc(...) calls malloc(...) in order to use
the C++ _set_new_mode function to set the new handler mode.