Course File2-Module 1
Course File2-Module 1
History
C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas
were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL ( Combined
Programming Language ) was developed with the purpose of creating a language that was capable of
both high level, machine independent programming and would still allow the programmer to control
the behavior of individual bits of information. The one major drawback of CPL was that it was too
large for use in many applications. In 1967, BCPL ( Basic CPL ) was created as a scaled down
version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell
Labs, took this process further by developing the B language. B was a scaled down version of BCPL
written specifically for use in systems programming. Finally in 1972, a co-worker of Ken Thompson,
Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of
developing the language we now know as C.
C's power and flexibility soon became apparent. Because of this, the Unix operating system which
was originally written in assembly language, was almost immediately re-written in C ( only the
assembly language code needed to "bootstrap" the C code was kept ). During the rest of the 1970's, C
spread throughout many colleges and universities because of it's close ties to Unix and the
availability of C compilers. Soon, many different organizations began using their own versions of C
causing compatibility problems. In response to this in 1983, the American National Standards
Institute ( ANSI ) formed a committee to establish a standard definition of C which became known as
ANSI Standard C. The standardization process took six years. The ANSI C standard was finally
adopted in December 1989, with the first copies becoming available in early 1990. The standard was
also adopted by ISO (International Standards Organization), and the resulting standard was typically
referred to as ANSI/ISO Standard C, or simply ANSI/ISO C. Today C is in widespread use with a
rich standard library of functions.
1
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
Significant Language Features
C is a powerful, flexible language that provides fast program execution and imposes few constraints
on the programmer. It allows low level access to information and commands while still retaining the
portability and syntax of a high level language. These qualities make it a useful language for both
systems programming and general purpose programs.
C's power and fast program execution come from it's ability to access low level commands, similar to
assembly language, but with high level syntax. It's flexibility comes from the many ways the
programmer has to accomplish the same tasks. C includes bitwise operators along with powerful
pointer manipulation capabilities. C imposes few constraints on the programmer. The main area this
shows up is in C's lack of type checking. This can be a powerful advantage to an experienced
programmer but a dangerous disadvantage to a novice.
Another strong point of C is it's use of modularity. Sections of code can be stored in libraries for re-
use in future programs. This concept of modularity also helps with C's portability and execution
speed. The core C language leaves out many features included in the core of other languages. These
functions are instead stored in the C Standard Library where they can be called on when needed.. An
example of this concept would be C's lack of built in I/O capabilities. I/O functions tend to slow
down program execution and also be machine independent when running optimally. For these
reasons, they are stored in a library separately from the C language and only included when
necessary.
C is often called a middle-level computer language. This does not mean that C is less powerful,
harder to use, or less developed than a high-level language such as Pascal; nor does it imply that C is
similar to, or presents the problems associated with, assembly language. The definition of C as a
middle-level language means that it combines elements of high-level languages with the
functionalism of assembly language. As a middle-level language, C allows the manipulation of bits,
bytes, and addressesthe basic elements with which the computer functions. Despite this fact, C
code is surprisingly portable. Portability means that it is possible to adapt software written for one
type of computer to another. For example, if a program written for one type of CPU can be moved
easily to another, that program is portable. All high-level programming languages support the
2
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
concept of data types. 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. Common data types are integer, character, and real.
Although C has several basic built-in data types, it is not a strongly typed language like Pascal or
Ada. In fact, C will allow almost all type conversions. For example, character and integer types may
be freely intermixed in most expressions. Traditionally C performs no run-time error checking such
as array-boundary checking or argument-type compatibility checking. These checks are the
responsibility of the programmer. A special feature of C is that it allows the direct manipulation of
bits, bytes, words, and pointers. This makes it well suited for system-level programming, where these
operations are common. Another important aspect of C is that it has only 32 keywords (5 more were
added by C99, but these are not supported by C++), which are the commands that make up the C
language. This is far fewer than most other languages.
C PREPROCESSOR DIRECTIVES:
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. We'll refer to the C
Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column.
Preprocessor Syntax/Description
Syntax: #define
This macro defines constant value and can be any of the
Macro basic data types.
Predefined Macros
Header file
A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the
files that the programmer writes and the files that comes with your compiler.
You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes along with
your compiler.
Including a header file is equal to copying the content of the header file but we do not do it
because it will be error-prone and it is not a good idea to copy the content of a header file in the
source files, especially if we have multiple source files in a program.
4
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in the header files and include that header file
wherever it is required.
Include Syntax
Both the user and the system header files are included using the preprocessing
directive #include. It has the following two forms
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of
system directories. You can prepend directories to this list with the -I option while compiling
your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file. You can prepend directories to this list with the -I option
while compiling your source code.
C language is rich in data types. The fundamental data types which can be used in C are integer data
types, character data types and floating point data types. Integer data type is used to represent an
integer-valued number. Character data type represents one single alphabet or a single-digit integer.
Each character type has an equivalent integer representation. Integer and character data types can be
augmented by the use of the data type qualifiers, short, long, signed and unsigned. The range of
values which belong to each category varies with respect to the qualifiers and so, the memory
requirement.
Floating point data types are used to represent real numbers. Basic floating point data type offers six
digits of precision. Double precision data type can be used to achieve a precision of 14 digits. To
extend the precision further more, we may use the extended double precision floating point data type.
Each of the above discussed data types and their corresponding keywords are given in the table
below.
5
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
EXPRESSIONS
Expressions in C are classified according to the operators used in them. The classifications are,
Relational expression.
Logical expression.
Arithmetic expression.
1. Relational expression.
An expression containing a relational operator is termed as relational expression. The list of all
relational operators is given below
OPERATOR MEANING
== Is equal to.
7
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
used in decision statements such as if, and while to decide the course of action of a running
program. When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results are compared.
2. Logical expression.
Logical expressions are the expressions where logical operators are used to combine more than one
relational expression. Logical expressions are also called compound relational expressions. The
logical operators used in C are && (logical AND), || (logical OR), and ! (logical NOT). Logical
expressions also yields a value of one or zero, and used in decision statements.
Format of a logical expression:
(rel-expression-1) logical operator (rel-expression-2)
Where rel-expression-1 and rel-expression-2 are relational expressions. The values of the above
statement when different logical operators are used is given below
3. ARITHMETIC EXPRESSIONS
8
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
C Expression
Algebraic Expression
axbc a*bc
(m + n) (x + y) (m + n) * (x + y)
(a x b / c) a*b/c
(x / y) + c x/y+c
Evaluation of Expressions
Low priority + -
If parentheses are nested, the evaluation begins with the innermost sub expression.
The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.
Arithmetic expressions are evaluated from left to right using the rules of precedence.
When Parenthesis are used, the expressions within parenthesis assume highest priority.
Operators in C Language
C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform certain mathematical or logical manipulations. Operators are used in
program to manipulate data and variables.
C operators can be classified into following types,
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
1. Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description
10
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
% remainder of division
2. Relation operators
The following table shows all relation operators supported by C.
Operator Description
> Check if operand on the left is greater than operand on the right
11
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
3. Logical operators
C language supports following 3 logical operators. Suppose a=1 and b=0,
|| Logical OR (a || b) is true
4. Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bits from right to left. Bitwise operators are not applied to float or double.
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
12
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the
same precedence.
Example :
a = 0001000
b= 2
a << b = 0100000
a >> b = 0000010
5. Assignment Operators
Assignment operators supported by C language are as follows.
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b
13
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
-= subtracts right operand from the left operand and assign the result to left operand a-=b is same as a=a-b
*= mutiply left operand with the right operand and assign the result to left operand a*=b is same as a=a*b
/= divides left operand with the right operand and assign the result to left operand a/=b is same as a=a/b
%= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b
6. Conditional operator
It is also known as ternary operator and used to evaluate conditional expression.
epr1 ? expr2 : expr3
Eg: r = (m>n) ? m : n
If m is greater than n then r=m otherwise r=n
7. Special operator
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
14
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
In any programming language, the interface forms a very important part. It deals with
taking data from the user and displaying back the output. For this purpose, we require the input-
output operations. Since this is an important concept for any programming language, I would like
to take it in parts rather than as a long single article. So this article deals with the basics of input
operations.
Reading ,processing ,and writing of data are the three essential functions of a computer program .
Most programs take some data as input and display the processed data , often known as
information or results, on a suitable medium.
Unlike other high-level languages , C does not have any built-in input/output statements as part
of its syntax . All input / output operations are carried out through function calls such as printf
and scanf. There exist several functions that have more or less become standard for input and
output operations in C. These functions are collectively known as the standard I/O library.
Each program that uses a standard input/output function must contain the statement
#include <stdio.h>
at the beginning. However, there might be exceptions. For example, this is not necessary for the
functions printf and scanf which have been defined as part of the C language.
The file name stdio.h is an abbreviation for standard input -output header file. The instruction
#include <stdio.h> tells the compiler to search for a file named stdio.h and place its contents at
this point in the program. The contents of the header file become part of the source code when it
is compiled.
The simplest of all input/output operations is reading a character from the standard input unit
(usually the keyboard) and writing it to the standard output unit (usually the screen). Reading a
15
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
single character can be done by using the function getchar. The getchar takes the following
form:
variable_name = getchar();
variable_name is a valid C name that has been declared as char type. When this statement is
encountered , the computer waits until a key is pressed and then assigns this character as a value
to getchar function . Since getchar is used on the right-hand side of an assignment statement ,
the character value of getchar is in turn assigned to the variable name on the left.
For example
char name;
name = getchar();
will assign the character 'H' to the variable name when we press the key H on the keyboard .
Since getchar is a function ,it requires a set of parentheses as shown.
The putchar function which in analogus to getchar function can be used for writing characters
one at a time to the output terminal. The general form is
Where variable is a valid C type variable that has already been declared
Ex:-
putchar ( c);
#include < stdio.h > // Inserts stdio.h header file into the Pgm
void main ( ) // Beginning of main function.
{
16
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
C supports testing of the character keyed in by the user by including the file ctype.h & the
functions which can be used after including this file are
The gets function relieves the string from standard input device while put S outputs the string to
the standard output device. A strong is an array or set of characters.
The function gets accepts the name of the string as a parameter, and fills the string with
characters that are input from the keyboard till newline character is encountered. (That is till we
press the enter key). All the end function gets appends a null terminator as must be done to any
string and returns.
The puts function displays the contents stored in its parameter on the standard screen.
The standard form of the gets function is
17
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
Formatted Input
Formatted input refers to an input data that has been arranged in a particular format . For
example, consider the following data:
15.73 123 John
This line contains three pieces of data, arranged in a particular form. Such data has to be read
conforming to the format of its appearance. For example, the first part of the data should be read
into a variable float, the second into int, and the third part into char. This is possible in C using
the scanf function .
The general form of scanf is
18
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
The control string specifies the field format in which the data is to be entered and the arguments
arg1 ,arg2, .....argn specify the address of locations where the data is stored . Control string and
arguments are seperated by commas.
scanf Format Codes:
printf();
The most simple output statement can be produced in C Language by using printf statement. It allows
you to display information required to the user and also prints the variables we can also format the output
and provide text labels. The simple statement such as
Syntax
19
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
The conversion string includes all the text labels, escape character and conversion specifiers
required for the desired output. The variable includes all the variable to be printed in order they
are to be printed. There must be a conversion specifies after each variable.
CONTROL STATEMENTS
C provides two sytles of flow control:
Branching
Looping
Branching is deciding what actions to take and looping is deciding how many times to
take a certain action.
BRANCHING :
Branching is so called because the program chooses to follow one branch or another.
IF_ELSE
Use an if statement
IF STATEMENT
The if statement is used to conditionally execute a block of code based on whether a test condition is
true. If the condition is true the block of code is executed, otherwise it is skipped.
SYNTAX
if (condition)
true_statements ;
20
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
OR
if (condition)
true_statement ;
OR
if (condition)
true_statements ;
else
false_statements ;
PROGRAM FLOW
3. If condition evaluates to false and an else clause exists, the false_statement(s) are executed.
EXAMPLE
#include <stdio.h>
int main(void)
{
int number = 75;
int mark;
printf("Your examination mark\n");
printf("Enter your score, please\n");
21
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
scanf("%d",&mark);
if (mark >= number)
{
printf("Incredible, you passed with a merit\n");
}
return 0;
}
The "==" is called a relational operator. Relational operators, ==, !=, >, >=, <, and <=, are used to
compare two values.
Else Statement
The else statement provides a way to execute one block of code if a condition is true, another if it is
false.
Example:
#include <stdio.h>
int main(void)
{
int number = 75;
int mark;
printf("Your examination mark\n");
scanf("%d",&mark);
{
printf("Incredible, you have passed with a merit\n");
}
else
{
printf("You failed, unlucky\n");
}
22
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
return 0;
}
LOOPING :
A) FOR LOOP
SYNTAX
for (initialization ; test ; increment)
statements ;
OR
statement ;
PROGRAM FLOW
1. The initialization is first executed. This is typically something like int i=0, which creates a
new variable with initial value 0, to act as a counter. Variables that you declare in this part
of the for loop cease to exist after the execution of the loop is completed. Multiple,
comma separated, expressions are allowed in the initialization section. But declaration
expressions may not be mixed with other expressions.
2. The boolean expression test is then evaluated. This is typically something like i<10.
Multiple, comma separated, expressions are not allowed. If test evaluates to true, flow
contiues to step 3. Otherwise the loop exits.
4. Then the statement increment is executed. It is typically something like i++ , which
increments i by one or i+=2 , which increments i by two. Multiple, comma separated,
expressions are allowed in the increment section.
EXAMPLE
B) WHILE STATEMENT
The simplest of all the c looping structures in C is the while statement . The while statement is an
entry -controlled loop statement. The test condition is evaluated and if the condition is true then the
body of the loop is executed . After the execution of the body the test condition is once again
evaluated and if it is true ,the body is executed once again. This process of repeated execution of the
body is continued until the test condition becomes false and the control is transferred out of the loop.
On exit the program is continued with the statement after the body of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements.
# include<stdio.h>
main()
{
24
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
int count,n;
float x,y;
printf(Enter the values of x and n:);
scanf(%f %d, &x, &n);
y= 1.0;
count = 1;
/* LOOP BEGINS*/
while(count<= n)
{
y = y * n;
count ++;
}
/*End of loop*/
printf( x = %f ; n = %d ; to power n = %f n , x , n, y);
}
3) DO-WHILE STATEMENT
In while statement there is a chance of skipping the entire loop without execution if the value is
not satisfying the condition . To avoid such a condition we use do while statement. In do .. while
statement the body of the loop will be executed at least once . On reaching the do statement , the
program proceeds to evaluate the body first . At the end of the loop the test condition in the in the
while statement is evaluated if the condition is true the program continues to evaluate the body
of the loop once again . This process continues as long as the condition is true . When the
condition becomes false , the loop will be terminated and the control of the program goes to the
statement that appears after the while statement .
Since the test-condition is evaluated at the bottom of the loop , the do construct provides an exit-
controlled loop and therefore the body of the loop is always executed once.
25
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
{
#define rowmax 12
main()
int row,column,y;
row = 1;
printf(_________________________________\n);
do {
column = 1;
do
column = 1;
do
y = row * column;
26
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
printf(%4d,y);
printf(\n);
row = row + 1;
printf(_______________________________________)
27
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
SWITCH STATEMENT
The switch statement is another form of the multi way decision. It is well structured, but can
only be used in certain cases where;
Only one variable is tested, All branches must depend on the value of that variable.
The variable must be an integral type.(int long, short or char).
Each possible value of the variable can control a single branch. A final ,catch all
default branch may optionally be used to trap all unspecified cases.
Syntax
Switch(expression)
case value-1:
block-1
break;
case value-2:
block-2
break;
default:
default-block
break;
Hopefully an example will clarify things. This is a program which accepts four mathematical
symbols + , - , * , / .Then the program accepts two integers a & b & displays the output as the
value of a + b , a b , a * b or a / b depending upon the symbol entered.
#include<stdio.h>
28
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
main()
int a,b;
char c;
scanf(%c,&c);
switch(c)
scanf(%d %d,&a,&b);
printf(a + b = %d\n,a+b);
break;
scanf(%d %d,&a,&b);
printf(a - b = %d\n,a-b);
break;
scanf(%d %d,&a,&b);
printf(a * b = %d\n,a*b);
break;
scanf(%d %d,&a,&b);
29
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
printf(a / b = %d\n,a/b);
break;
Here, each interesting case is listed with a corresponding action. The control passes to the
statement whose case constant- expression matches the value of switch (expression). The
switch statement can include any number of case instances, but no two case constants within the
same switch statement can have the same value. Execution of the statement body begins at the at
the selected statement and proceeds until the end of the body or until a break statement transfers
control out of the body. The break statement prevents any further statements from being
executed by leaving the switch. The default statement is executed if no case constant-expression
is equal to the value of switch(expression). If the default statement is omitted and no case match
is found, none of the statements in the switch body are executed. There can be at most one
default statement. The default statement need not come at the end, it can appear anywhere in the
body of the switch statement. A case or default label can only appear inside a switch statement.
Switch statement can be nested. A single statement can carry multiple case labels.
BREAK
int markerpos=-1;
for (index=0 ;index < 10;index++ )
{
if (values[index] ==-999 )
{
markerpos = index;
30
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
break;
}
}
if (markerpos== 999)
printf("-1 Not located in array";
else
printf("-1 Found at index %i\n\r",markerpos) ;
That's a more complicated example. It searches the 10 element array values looking for a 999
value. The variable markerpos holds the position if a 999 is found. It is initialized to -1 and after
the search this value is examined to see if a 999 was found.
CONTINUE
This does the opposite of break; Instead of terminating the loop, it immediately loops again,
skipping the rest of the code. So lets sum that integer array again, but this time we'll leave out
elements with an index of 4 and 5.
You probably won't use continue very often but it's useful on the odd occasion.
NESTED LOOP
31
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
These loops are the loops which contain another looping statement in a single loop. These types
of loops are used to create matrix. Any loop can contain a number of loop statements in itself. If
we are using loop within loop that is called nested loop. In this the outer loop is used for
counting rows and the internal loop is used for counting columns
SYNTAX:-
statement;
statement;
PROGRAM
#include
void main ( )
int i, j;
clrscr ( );
{
32
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: [email protected] Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
printf (*)
printf (\n);
getch ( );
****
****
****
****
33