SlideShare a Scribd company logo
Basics of
C- Language
Unit – I
by
Dr.T.P.Latchoumi
Overview of C language
Developed at Bell Laboratories in the early seventies by Dennis Ritchie.
Born out of two other languages – BCPL (Basic Control Programming
Language) and B.
C introduced such things as character types, floating point arithmetic, structures,
unions and the preprocessor.
The principal objective was to devise a language that was easy enough to
understand to be "high-level" – i.e. understood by general programmers, but low-
level enough to be applicable to the writing of systems-level software.
Cont…
The language should abstract the details of how the computer achieves its tasks in such a way as
to ensure that C could be portable across different types of computers, thus allowing the UNIX
operating system to be compiled on other computers with a minimum of re-writing.
C as a language was in use by 1973, although extra functionality, such as new types, was
introduced up until 1980.
In 1978, Brian Kernighan and Dennis M. Ritchie wrote the seminal work The C Programming
Language, which is now the standard reference book for C.
A formal ANSI standard for C was produced in 1989.
Cont…
In 1986, a descendant of C, called C++ was developed by Bjarne Stroustrup, which is in wide
use today. Many modern languages such as C#, Java and Perl are based on C and C++.
Using C language scientific, business and system-level applications can be developed easily.
Program
There is a close analogy between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words, which in turn are combined to form sentences
and sentences are combined to form paragraphs.
Learning C is similar and easier.
Instead of straight-away learning how to write programs, we must first know what alphabets,
numbers and special symbols are used in C, then how using them constants, variables and
keywords are constructed, and finally how are these combined to form an instruction.
Steps in English
Language Vs
C Language
Types of
Languages
Low level languages are machine level and assembly level language.
In machine level language computer only understand digital numbers
i.e. in the form of 0 and 1. So, instruction given to the computer is in
the form binary digit, which is difficult to implement instruction in
binary code. This type of program is not portable, difficult to maintain
and also error prone.
The assembly language is on other hand modified version of machine
level language. Where instructions are given in English like word as
ADD, SUM, MOV etc.
It is easy to write and understand but not understand by the machine.
So the translator used here is assembler to translate into machine level.
Although language is bit easier, programmer has to know low level
details related to low level language.
In the assembly level language the data are stored in the computer
register, which varies for different computer. Hence it is not portable.
Low level language
Types of
Languages
These languages are machine independent, means it is
portable.
 The language in this category is Pascal, COBOL, Fortran etc.
High level languages are understood by the machine.
So it needs to translate by the translator into machine level.
A translator is software which is used to translate high level
language as well as low level language in to machine level
language.
High level language
Types of translator
 Compiler
Interpreter
Assembler
Compiler
A compiler is a translator used to convert high level language to low level language.
It converts the whole program in one session and reports errors detected after the conversion.
The compiler takes time to do its work as it translates high-level code to lower-level code all at once
and then saves it to memory.
A compiler is processor-dependent and platform-dependent.
It has been addressed by alternate names as the following: special compiler, cross-compiler and,
source-to-source compiler.
Interpreter
The interpreter is similar to a compiler, it is a translator used to convert high-level programming
language to low-level programming language.
The difference is that it converts the program one line of code at a time and reports errors when
detected, while also doing the conversion.
An interpreter is faster than a compiler as it immediately executes the code upon reading the code.
It is often used as a debugging tool for software development as it can execute a single line of code at
a time.
An interpreter is also more portable than a compiler as it is processor-independent, you can work
between different hardware architectures.
Assembler
An assembler is a translator used to translate assembly language into machine language.
It has the same function as a compiler for the assembly language but works like an interpreter.
Assembly language is difficult to understand as it is a low-level programming language.
An assembler translates a low-level language, such as an assembly language to an even lower-level
language, such as the machine code.
Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its popularity as a
programming language. Naturally we will be studying many of these aspects throughout the course.
• Small size
• Extensive use of function calls
• Loose typing
• Structured language
• Low level (Bitwise) programming readily available
• Pointer implementation - extensive use of pointers for memory, array, structures and functions.
Cont…
C has now become a widely used professional language for various reasons.
• It has high-level constructs.
• It can handle low-level activities.
• It produces efficient programs.
• It can be compiled on a wide variety of computers.
Compiling &
Executing C
Program
Step 1: The program that is to be compiled is first typed
into a file on the computer system.
There are various conventions that are used for naming
files, typically be any name provided the last two characters
are “.c” or file with extension .c.
Step 2: After the source program has been entered into a
file, then proceed to have it compiled.
The compilation process is initiated by typing a special
command on the system.
When this command is entered, the name of the file that
contains the source program must also be specified.
For example, under Unix, the command to initiate program
compilation is called cc. If we are using the popular GNU C
compiler, the command we use is gcc.
A compiler is a software
program that analyzes a
program developed in a
particular computer language
and then translates it into a
form that is suitable for
execution on a particular
computer system.
Cont…
Step 3: When all the syntactic and semantic errors have
been removed from the program, the compiler then
proceeds to take each statement of the program and translate
it into a “lower” form that is equivalent to assembly
language program needed to perform the identical task.
Step 4: After the program has been translated the next step
in the compilation process is to translate the assembly
language statements into actual machine instructions.
The assembler takes each assembly language statement and
converts it into a binary format known as object code,
which is then written into another file on the system.
This file has the same name as the source file under Unix,
with the last letter an “o” (for object) instead of a “c”.
Cont…
Step 5: After the program has been translated into object
code, it is ready to be linked.
This process is once again performed automatically
whenever the cc or gcc command is issued under Unix.
The purpose of the linking phase is to get the program into a
final form for execution on the computer.
Step 6: To subsequently execute the program, the command
a.out has the effect of loading the program called a.out into
the computer‟s memory and initiating its execution.
Flowchart of
compilation
C character
Set
Letters
Uppercase characters (A-Z)
Lowercase characters (a-z)
Numbers
All the digits from 0 to 9
White spaces
Blank space
New line
Carriage return
Horizontal tab
A character denotes any
alphabet, digit or special
symbol used to represent
information.
 Valid alphabets, numbers
and special symbols allowed in
C are
Letters
Numbers
White spaces
Special Characters
Special
characters
The alphabets, numbers and special
symbols when properly combined
form constants, variables and
keywords.
C Tokens
TOKEN is the smallest unit in a 'C'
program. It is each and every word and
punctuation that you come across in
your C program. The compiler breaks a
program into the smallest possible units
(tokens) and proceeds to the various
stages of the compilation. A token is
divided into six different types, such as
Keywords, Operators, Strings,
Constants, Special Characters, and
Identifiers.
32 Keywords
Flow control (6) – if, else, return, switch, case, default
Loops (5) – for, do, while, break, continue
Common types (5) – int, float, double, char, void
For dealing with structures (3) – struct, typedef, union
Counting and sizing things (2) – enum, sizeof
Rare but still useful types (7) – extern, signed, unsigned, long, short, static, const
Keywords that is undiscouraged and which we NEVER use (1) – goto
We don't use unless we're doing something strange (3) – auto, register, volatile
Identifiers
Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and
lower case), digits and underscore (_) sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case
considered differently, for example code, Code, CODE etc.
are different identifiers.
5) identifiers are generally given in some meaningful name
such as value, net_salary, age, data etc.
6) It should not contain any whitespace character.
Identifiers are user defined word
used to name of entities like
variables, arrays, functions,
structures etc.
Constants
Constant is a any value that
cannot be changed during program
execution.
In C, any number, single
character, or character string is
known as a constant.
A constant is an entity that
doesn‟t change whereas a variable
is an entity that may change.
Operators
This is a symbol use to perform some operation on variables, operands or with the constant.
Some operator required 2 operand to perform operation or some required single operation.
Several operators are there those are, arithmetic operator, assignment, increment, decrement, logical,
conditional, comma, size of , bitwise and others.
Special
characters
The alphabets, numbers and special
symbols when properly combined
form constants, variables and
keywords.
Strings
In C programming, a string is a sequence of characters terminated with a null character 0. For
example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it
appends a null character 0 at the end by default.
Simple C
program
structure
1 ) Comment line
2) Preprocessor directive
3 ) Global variable declaration
4) main function( )
{
Local variables;
Statements;
}
User defined function
}
}
Comments
It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the
program.
It is useful in explaining the program and generally used for
documentation.
It is enclosed within the decimeters.
Comment line can be single or multiple line but should not
be nested.
It can be anywhere in the program except inside string
constant & character constant.
Preprocessor
directive
#include tells the compiler to include information about the
standard input/output library.
It is also used in symbolic constant such as #define PI
3.14(value).
The stdio.h (standard input output header file) contains
definition &declaration of system defined function such as
printf( ), scanf( ), pow( ) etc.
Generally printf() function used to display and scanf()
function used to read value
Global
declaration
This is the section where variable are declared globally so
that it can be access by all the functions used in the
program.
And it is generally declared outside the function
main()
Syntax
main()
{
……..
……..
……..
}
It is the user defined function and
every function has one main()
function from where actually
program is started and it is encloses
within the pair of curly braces.
The main( ) function can be
anywhere in the program but in
general practice it is placed in the
first position.
/*First c program
with return
statement*/
#include <stdio.h>
int main (void)
{
printf ("welcome to c Programming language.n");
return 0;
}
Output: welcome to c programming language
Constants
C Constants is the most fundamental and essential part of the C programming language. Constants in C
are the fixed values that are used in a program, and its value remains the same during the entire
execution of the program.
Constants are also called literals.
Constants can be any of the data types. const keyword defines a constant in C.
It is considered best practice to define constants using only upper-case names.
Syntax
const type constant_name;
Example
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq. units", SIDE, area);
}
Output: The area of the square with side: 10 is: 100 sq. units
Types of Constants
Constants are categorized into two basic types, and each of these types has its subtypes/categories. These are:
Primary Constants
1. Numeric Constants
Integer Constants
Real Constants
2. Character Constants
Single Character Constants
String Constants
Backslash Character Constants
Integer
Constants
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer
constant.
If no sign precedes an integer constant, it is assumed to be
positive.
The allowable range for integer constants is -32768 to
32767.
Example: 0 , -33, 32767
There are three types of integer
constants namely,
a) Decimal integer
b) Octal integer constant
c) Hexadecimal integer
Decimal Integer constant (base
10)
•It consists of any combinations of digits taken from the set 0 through 9, preceded by an optional – or +
sign.
•The first digit must be other than 0.
Embedded spaces, commas, and non-digit characters are not permitted between digits.
Valid: 0 32767 -9999 -23
Invalid:
12,245 - Illegal character (,)
10 20 30 - Illegal character (blank space)
Octal Integer Constant (base 8)
It consists of any combinations of digits taken from the set 0 through 7.
If a constant contains two or more digits, the first digit must be 0.
In programming, octal numbers are used.
Valid: 037 0 0435
Invalid:
0786 - Illegal digit 8
123 - Does not begin with zero
01.2 - Illegal character (.)
Hexadecimal Integer Constant
(base 16)
It consists of any combinations of digits taken from the set 0 through 7 andalso a through f
(either uppercase or lowercase).
The letters a through f (or A through F) represent the decimal quantities 10 through 15 respectively.
This constant must begin with either 0x or 0X.
In programming, hexadecimal numbers are used.
Valid Hexadecimal Integer Constant: 0x 0X1 0x7F Invalid Hexadecimal
Integer Constant: 0xefg - Illegal character g
123 - Does not begin with 0x
Real Constants
(Fractional
form)
The numbers containing fractional parts like 99.25 are
called real or floating points constant.
Here are the rules for creating floating point constants in
Fractional form:
1. Must have one at least one digit
2. Must have a decimal point
3. Can be positive or negative, the default is positive
4. No comma, blanks, or any other symbols are allowed
Here are some examples: 3.14, 899.0, -0.999
Real Constants
(Exponential
form)
Exponential form is used in cases when a number is too small or too
large. For example, 0.00000941 can be represented as 9.41e-6. The part
of the number before e is called mantissa i.e 9.41, whereas, the part
following e is called the exponent i.e -6.
Here are the rules for creating floating point constants in Exponential
form:
1. Mantissa and exponent must be separated by e or E.
2. Mantissa can be positive or negative, default is positive.
3. Exponent must have at least one digit.
4. The exponent can be positive or negative default is positive
Some examples of floating point numbers in exponential form are:
100.34e4, -56E10, 0.233E10, -0.94e15
By default, floating constants are of type double. We can explicitly
mention the type of a floating-point constant as a float by
appending f or F at the end of the constant.
For example: 12f, -0.87f
Character Constant
1. A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single quotes.
2. The maximum length of a character constant is 1 character.
3. String constants are enclosed within double quotes.
Single character constant
It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be noted that
the character '8' is not the same as 8. Character constants have a specific set of integer values known as
ASCII values (American Standard Code for Information Interchange).
Example:
'X', '5', ';'
The maximum length of a character constant is 1 character long. That means you cannot put more than
one character inside single quotation marks like this
'ab' // Wrong
'12' // Wrong
String constant
String constants consist of zero or more characters enclosed in double quotes (""). At the end of the
string, the null character i.e '0' is automatically placed by the compiler. Here are some examples of
string constants:
"hello"
"123"
"" // This is empty string
Although not officially part of Primary constants, string constants are given here for the sake of
completeness. C has no data type for string, they are stored as an array of characters. We will learn
more about strings in a great deal in its own chapter
Backslash
character
constant
There are some characters which
have special meaning in C
language.
They should be preceded by
backslash symbol to make use of
special function of them.
Given below is the list of special
characters and their purpose.
Symbolic
Constant
It is generally defined at the beginning of the program. Here is
the syntax of creating a Symbolic constant.
#define NAME VALUE
#define is a preprocessor directive just like #include, that's why
it doesn't end with the semicolon (;).
NAME indicates the name we want to give to our constant and
is generally written in uppercase.
VALUE can be numeric, character or string constant. Let's
create a symbolic constant called PI.
#define PI 3.141592
If we want to use constant several
times in a program, then we can
provide it a name. For example: If
there is a need to use constant Π =
3.141592 at several places in the
program, then we can give it a name
and use that name instead of writing
this long number. This constant is
called Symbolic constant.
Example 1
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '?'; /*special char cnst*/
printf("value of height :%d n", height );
printf("value of number : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n", letter_sequence);
printf("value of backslash_char : %c n", backslash_char);
}
Example 2
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq.
units" , SIDE, area);
}
Output: The area of the square
with side: 10 is: 100 sq. units
Variables
A variable is a value that can change.
A symbol or name that stands for a value.
Variables provide temporary storage for information that will
be needed during the lifespan of the computer program (or
application).
Variables store everything in your program.
• The purpose of any useful program is to modify variables.
• In a program every, variable has:
– Name (Identifier)
– Data Type
– Size
– Value
A variable is nothing but a name
given to a storage area that our
programs can manipulate.
Each variable in C has a specific
type, which determines the size and
layout of the variable's memory; the
range of values that can be stored
within that memory; and the set of
operations that can be applied to the
variable.
The name of a variable can be
composed of letters, digits, and the
underscore character. It must begin
with either a letter or an underscore.
Upper and lowercase letters are
distinct because C is case-sensitive.
Based on the basic types explained
in the previous chapter, there will
be the following basic variable
types –
Variables
definition
Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and
k; which instruct the compiler to create variables named i, j
and k of type int.
A variable definition tells the
compiler where and how much
storage to create for the variable. A
variable definition specifies a data
type and contains a list of one or
more variables of that type as
follows −
type variable_list;
Variable
initialization
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
For definition without an initializer: variables with static
storage duration are implicitly initialized with NULL (all
bytes have the value 0); the initial value of all other
variables are undefined.
Variables can be initialized
(assigned an initial value) in their
declaration. The initializer consists
of an equal sign followed by a
constant expression as follows −
type variable_name = value;
Example
#include <stdio.h>
extern int a, b;
extern int c;
extern float f;
int main () {
int a, b;
int c;
float f;
a = 10;
b = 20;
c = a + b;
printf("value of c : %d n", c);
f = 70.0/3.0;
printf("value of f : %f n", f);
return 0;
}
Output
value of c : 30
value of f : 23.333334
Difference
between variable
declaration and
definition
Local variable
Advantages of using Local Variables
• The use of local variables offer a guarantee that the values of variables will
remain intact while the task is running
• If several tasks change a single variable that is running simultaneously, then the
result may be unpredictable. But declaring it as local variable solves this issue as
each task will create its own instance of the local variable.
• You can give local variables the same name in different functions because they
are only recognized by the function they are declared in.
• Local variables are deleted as soon as any function is over and release the
memory space which it occupies.
Disadvantages of using Local Variables
• The debugging process of a local variable is quite tricky.
• Common data required to pass repeatedly as data sharing is not possible between
modules.
• They have a very limited scope.
Local variables are those that are in
scope within a specific part of the
program (function, procedure,
method, or subroutine, depending on
the programming language
employed).
The scope of local variables will be
within the function only.
These variables are declared within
the function and can‟t be accessed
outside the function.
Example 1
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44;
printf("nvalues : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80;
printf("nvalues : a = %d and b = %d", a, b);
}
Example 2
#include<stdio.h>
int main()
{
int a = 100;
{
int a = 10;
printf("Inner a = %dn", a);
}
printf("Outer a = %dn", a);
// signal to operating system everything works fine
return 0;
}
Global variable
Advantages of using Global variables
You can access the global variable from all the functions or modules in a program
You only require to declare global variable single time outside the modules.
It is ideally used for storing "constants" as it helps you keep the consistency.
A Global variable is useful when multiple functions are accessing the same data.
Disadvantages of using Global Variables
Too many variables declared as global, then they remain in the memory till
program execution is completed. This can cause of Out of Memory issue.
Data can be modified by any function. Any statement written in the program can
change the value of the global variable. This may give unpredictable results in
multi-tasking environments.
If global variables are discontinued due to code refactoring, you will need to
change all the modules where they are called.
Global variables are those that are in scope
for the duration of the programs execution.
They can be accessed by any part of the
program, and are readwrite for all
statements that access them.
The scope of global variables will be
throughout the program. These variables
can be accessed from anywhere in the
program.
This variable is defined outside the main
function. So that, this variable is visible to
main function and all other sub functions.
Example 1
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
void test()
{
printf("nnAll variables are accessed from" " test function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
Example 2
Local Vs
Global
variables
Datatypes
Data types in c refer to an extensive system used for declaring variables or functions of different types.
The type of a variable determines how much space it occupies in storage and how the bit pattern stored
is interpreted.
A programming language is proposed to help programmer to process certain kinds of data and to
provide useful output.
The task of data processing is accomplished by executing series of commands called program.
A program usually contains different types of data types (integer, float, character etc.) and need to store
the values being used in the program. C language is rich of data types.
Types
Integer types
Integer Data Types: Integers are whole numbers with a
range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its
value range limited to -32768 to +32767 (that is, -2 15 to
+215 -1).
A signed integer use one bit for storing sign and rest 15 bits
for number.
Syntax:
int <variable name>;
Example
int num1;
short int num2;
long int num3;
Example: 5, 6, 100, 2500.
Integer types
and storage
sizes
Floating point
types
The float data type is used to store fractional numbers (real
numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is
insufficient, we can use the double to define the number.
The double is same as float but with longer precision and
takes double space (8 bytes) than float.
To extend the precision further we can use long double
which occupies 10 bytes of memory space.
Syntax:
float <variable name>;
Examples
float num1;
double num2;
long double num3;
Example: 9.125, 3.1254.
Floating types
and its
storages sizes
Void data type
The void type specifies that no
value is available.
It is used in three kinds of situations
Operators
C language is rich in built-in operators and provides the
following types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Sizeof() operators
7. Ternary operators
8. Special operators
9. Unary operators
An operator is a symbol that tells
the compiler to perform specific
mathematical or logical
manipulations.
Arithmetic
operators
The following table shows all the
arithmetic operators supported by
the C language. Assume
variable A holds 10 and
variable B holds 20 then
Example
Relational
operator
The following table shows all the
relational operators supported by C.
Assume variable A holds 10 and
variable B holds 20 then −
Example
Logical
operator
Following table shows all the
logical operators supported by C
language. Assume variable A holds
1 and variable B holds 0, then −
Example
Bitwise
operator
Bitwise operator works on bits and
perform bit-by-bit operation. The
truth tables for &, |, and ^ is as
follows −
Assignment
operator
The following table lists the
assignment operators supported by
the C language −
Cont…
Example
Sizeof()
It is a much used operator in the C. It is a compile time
unary operator which can be used to compute the size of its
operand.
The result of sizeof is of unsigned integral type which is
usually denoted by size_t.
sizeof can be applied to any data-type, including primitive
types such as integer and floating-point types, pointer types,
or compound datatypes such as Structure, union etc.
Usage
sizeof() operator is used in different way according to the
operand type.
Example 1
Example 2
Ternary operator
If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is
also called as conditional operator
The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is
the result upon a true comparison, and the third is the result upon a false comparison. Ternary operator is shortened way
of writing an if-else statement.
Ternary operator is a?b:c it say that the condition a is true b will be executed else c will be executed.
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax
expression-1 ? expression-2 : expression-3
Flow diagram
Example
Unary operator
◦ unary minus
The minus operator changes the sign of its argument. A
positive number becomes negative, and a negative number
becomes positive.
int a = 10;
int b = -a; // b = -10
unary minus is different from subtraction operator, as
subtraction requires two operands.
Unary operator: are operators that act upon a
single operand to produce a new value.
Types of unary operators:
unary minus(-)
increment(++)
decrement(- -)
NOT(!)
Addressof operator(&)
sizeof()
Increment
operator
prefix increment
In this method, the operator preceeds the operand (e.g.,
++a). The value of operand will be altered before it is
used.
int a = 1;
int b = ++a; // b = 2
postfix increment
In this method, the operator follows the operand (e.g.,
a++). The value operand will be altered after it is used.
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2
It is used to increment the value of
the variable by 1. The increment
can be done in two ways:
Decrement
operator
prefix decrement
In this method, the operator preceeds the operand (e.g., – -
a). The value of operand will be altered before it is used.
int a = 1;
int b = --a; // b = 0
posfix decrement
In this method, the operator follows the operand (e.g., a- -).
The value of operand will be altered after it is used.
int a = 1;
int b = a--; // b = 1
int c = a; // c = 0
It is used to decrement the value of the
variable by 1. The decrement can be done in
two ways:
NOT and
address
operators
◦ NOT(!):
It is used to reverse the logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.
If x is true, then !x is false
If x is false, then !x is true
◦ Addressof operator(&):
It gives an address of a variable. It is used to return the memory address of a
variable. These addresses returned by the address-of operator are known as
pointers because they “point” to the variable in memory.
& gives an address on variable n
int a;
int *ptr;
ptr = &a; // address of a is copied to the location ptr.
Expressions
Expressions are the fundamental means of specifying
computations in a programming language
–To understand the expression evaluation, it is necessary to
be familiar with the orders of operator and operand
evaluation
– The essence of the imperative programming languages is
the dominant role of assignment statements
An expression is a combination of variables constants and
operators written according to the syntax of C language. In
C every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be
assigned to a variable.
Evaluation of Expressions
Precedence in Arithmetic Operators
Type conversions in expressions
Order
Category
Operator
Associativity
Evaluation of
expressions
Expressions are evaluated using an assignment statement of
the form
Variable = expression;
Variable is any valid C variable name. When the statement
is encountered, the expression is evaluated first and then
replaces the previous value of the variable on the left hand
side. All variables used in the expression must be assigned
values before evaluation is attempted.
Example of evaluation statements are
x = a * b – c
y = b / c * a
z = a – b / c + d;
Example
Precedence in
arithmetic
operators
Rules for evaluation of expression
• First parenthesized sub expression left to right are
evaluated.
• If parenthesis are nested, the evaluation begins with the
innermost sub expression.
• The precedence rule is applied in determining the order of
application of operators in evaluating sub expressions.
• 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.
An arithmetic expression without
parenthesis will be evaluated from
left to right using the rules of
precedence of operators.
There are two distinct priority levels
of arithmetic operators in C.
High priority * / %
Low priority + -
Type
conversion in
expression
The following rules apply during evaluating expressions
All short and char are automatically converted to int then
1. If one operand is long double, the other will be converted to long double and
result will be long double.
2. If one operand is double, the other will be converted to double and result will
be double.
3. If one operand is float, the other will be converted to float and result will be
float.
4. If one of the operand is unsigned long int, the other will be converted into
unsigned long int and result will be unsigned long int.
5. If one operand is long int and other is unsigned int then a. If unsigned int can
be converted to long int, then unsigned int operand will be converted as such and
the result will be long int.
…..b. Else Both operands will be converted to unsigned long int and the result
will be unsigned long int.
6. If one of the operand is long int, the other will be converted to long int and the
result will be long int.
7. If one operand is unsigned int the other will be converted to unsigned int and
the result will be unsigned int.
Implicit type conversion
C permits mixing of constants and variables of different
types in an expression. C automatically converts any
intermediate values to the proper type so that the
expression can be evaluated without loosing any
significance.
This automatic type conversion is know as implicit type
conversion
During evaluation it adheres to very strict rules and type
conversion.
If the operands are of different types the lower type is
automatically converted to the higher type before the
operation proceeds. The result is of higher type.
Operator
precedence
and
associativity
Operator precedence determines
which operator is performed first in
an expression with more than one
operators with different precedence.
For example: Solve
10 + 20 * 30
Example
Managing I/O operations
1. Standard Input (stdin)
Standard input or stdin is used for taking input from devices
such as the keyboard as a data stream.
1. Standard Output (stdout)
Standard output or stdout is used for giving output to a device
such as a monitor.
I/O operations are useful for a
program to interact with
users. stdlib is the standard C
library for input-output operations.
While dealing with input-output
operations in C, two important
streams play their role. These are:
Reading character in C
The easiest and simplest of all I/O
operations are taking a character as
input by reading that character from
standard input (keyboard).
getchar() function can be used to read
a single character.
This function is alternate
to scanf() function.
Syntax
var_name = getchar();
Writing character in C
Similar to getchar() there is another
function which is used to write
characters, but one at a time.
Syntax
putchar(var_name);
Reading and
Writing Strings
in C
The gets() function reads a string of
characters entered at the keyboard and
places them at the address pointed to by its
argument. We can type characters at the
keyboard until we strike a carriage return.
The carriage return does not become part of
the string; instead a null terminator is
placed at the end and gets() returns.
Typing mistakes can be corrected prior to
striking ENTER. The prototype for gets() is:
char* gets (char *str);
Basic console
I/O functions
Example
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string: ");
gets(str);
printf("The Entered string : %sn",str);
return 0;
}
Output:-
Enter a string: Know Program C
language
The Entered string : Know
Program C language
Comparison between gets() and
fgets()
Example
#include<stdio.h>
int main()
{
char str1[100], str2[100];
printf("Enter two string: ");
gets(str1);
fgets(str2, sizeof(str2), stdin);
//Notice displaying order
printf("String 1: %s ",str1);
printf("String 2: %s",str2);
return 0;
}
Output:-
Enter two string: Know Program
C language
String 1: Know Program String 2: C
language
C - Formatted I/O Functions
C language provide us console
input/output functions. As the name
says, the console input/output functions
allow us to -
• Read the input from the
keyboard by the user accessing the
console.
• Display the output to the user
at the console.
Note : These input and output values
could be of any primitive data type.
Format
Specifier
Scanf()
It refers to an input data which has been arranged in a specific format. This is possible in C using
scanf().
Syntax:
scanf("control string", arg1, arg2, ..., argn);
Example
OUTPUT :
Enter any character
a
Entered character is a
Enter any string ( upto 100
character )
hai
Entered string is hai
Printf()
• In C programming language, printf() function is used to print the (“character, string, float, integer, octal and hexadecimal
values”) onto the output screen.
• We use printf() function with %d format specifier to display the value of an integer variable.
• Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal
variable.
• To generate a newline,we use “n” in C printf() statement.
Note:
• C language is case sensitive. For example, printf() and scanf() are different from Printf() and Scanf(). All characters in printf()
and scanf() functions must be in lower case.
• All output starts in the leftmost box, although some output might be "padded" with blank spaces to align it to the right edge of
the field. "X"'s indicated unused positions.
Difference between puts() and
printf()
Example
Decision Making
This deals with the various methods that C can control the flow of logic in a program. Control statements can be classified as un-
conditional and conditional branch statements and loop or iterative statements. The Branch type includes:
1. Un-conditional: goto, break, return, continue, exit
2. Conditional: if, if-else, nested if, switch case statement
3. Loop or iterative: for loop, while loop, do-while loop
Conditional Statement
Sometimes we want a program to select an action from two or more alternatives. This requires a
deviation from the basic sequential order of statement execution.
Such programs must contain two or more statements that might be executed, but have some way to
select only one of the listed options each time the program is run.
This is known as conditional execution.
if statement
Statement or set of statements can be
conditionally executed using if statement.
Here, logical condition is tested which, may
either true or false.
If the logical test is true (non zero value) the
statement that immediately follows if is
executed.
If the logical condition is false the control
transfers to the next executable statement.
Example
Output:
num1 is smaller than num2
if – else
statement
The general syntax of simple if - else statement is:
The if statement is used to execute
only one action.
If there are two statements to be
executed alternatively, then if-else
statement is used.
The if-else statement is a two way
branching.
Example
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output
Enter your age:14
You are not eligible for voting
Nested if
statement
The ANSI standard specifies that
15 levels of nesting must be
supported.
In C, an else statement always
refers to the nearest if statement
in the same block and not already
associated with if.
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 ) {
/* if condition is true then check the following */
if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200n" );
}
}
Output
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
if –else – if
ladder
When faced with a situation in which a
program must select from many processing
alternatives based on the value of a single
variable,
an analyst must expand his or her use of the
basic selection structure beyond the
standard two processing branches offered
by the if statement to allow for multiple
branches.
One solution to this is to use an approach
called nesting in which one (or both)
branch(es) of a selection contain another
selection.
Example
Output
Enter a Number: -5
Given Number is Negative
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("Given Number is Positive");
}
else if(a == 0)
{
printf("Given Number is Zero");
}
else if(a < 0)
{
printf("Given Number is Negative");
}
getch();
}
The switch
case statement
The general
form of switch case statement is:
switch (expression)
{
case constant1:
statement;
break;
case constant2:
statement;
break;
default:
statement;
break;
}
The switch-case statement is used
when an expression’s value is to
be checked against several
values. If a match takes place, the
appropriate action is taken.
Three important
things to know
about switch
statement
1. The switch differs from the if in that
switch can only test for equality whereas
if can evaluate any type of relational or
logical expression.
2. No two case constants in the same
switch can have identical values. But, a
switch statement enclosed by an outer
switch may have case constants and
either same.
3. If character constants are used in the
switch statement, they are automatically
converted to integers.
Example
#include <stdio.h>
int main()
{
int num=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output:
Default: value is: 2
Looping statement
Looping is a powerful programming technique through which a group of statements is
executed repeatedly, until certain specified condition is satisfied. Looping is also called
a repetition or iterative control mechanism.
Types of Loops in C
Depending upon the position of a control statement in a program, looping in C is
classified into two types:
1. Entry controlled loop
2. Exit controlled loop
In an entry controlled loop, a condition is checked before executing the body of a loop.
It is also called as a pre-checking loop. Eg. do-while loop
In an exit controlled loop, a condition is checked after executing the body of a loop. It
is also called as a post-checking loop. Eg. for and while loop
C provides three types of loop control structures. They are:
• for statement
• while statement
• do-while statement
for statement
The for loop statement is useful to repeat a
statement/s a known number of times. The
general syntax is as follows:
for (initialization; condition; operation)
{
statement;
}
The initialization is generally an assignment
statement that is used to set the loop control
variable.
The condition is an
expression(relational/logical/arithmetic/bitwise
….) that determines when the loop exists.
The Operation defines how the loop control
variable changes each time the loop is repeated.
Example
Example
#include <stdio.h>
int main()
{
int i;
for (i=1; i<=3; i++)
{
printf("%dn", i);
}
return 0;
}
Output
1
2
3
Nested for loop
Nested loops consist of one loop placed
inside another loop. An example of a
nested for loop is:
for (initialization; condition; operation)
{
for (initialization; condition; operation)
{
statement;
}
statement;
}
Example 2
while
statement
The second loop available in ‘C’ is while
loop.
The general format of while loop is:
while (expression)
{
statement
}
A while statement is useful to repeat a
statement execution as long as a condition
remains true or an error is detected. The
while statement tests the condition before
executing the statement.
Example
#include <stdio.h >
void main()
{
int i, j, k, temp;
printf("ItI^2tI^3tI^4 n");
printf("--------------------------------n");
i = 1;
while (i < 10) /* Outer loop */
{
j = 1;
while (j < 5) /* 1st level of nesting */
{
temp = 1;
k = 1;
while (k < j)
{
temp = temp * i;
k++;
}
printf ("%dt", temp);
j++;
}
printf ("n");
i++;
}
do-while
statement
The third loop available in C is do
– while loop.
The general format of do-while is:
do
{
statement;
} while (expression);
Example1
# include <stdio.h>
main()
{
do
{
printf("x = %dn", x--);
} while(x > 0);
}
Output to the screen:
X = 3
X = 2
X = 1
Example 2
Output to the screen:
T: Train
C: Car
S: Ship
Enter your choice: T
Train
#include <stdio.h>
void main()
{
char ch;
printf("T: Trainn");
printf("C: Carn");
printf("S: Shipn");
do
{
printf("nEnter your choice: ");
fflush(stdin);
ch = getchar();
switch(ch)
{
case 'T' :
printf("nTrain");
break;
case 'C' :
printf("nCar");
break;
case 'S':
printf("nShip");
break;
default:
printf("n Invalid Choice");
}
} while(ch == 'T' || ch == 'C' || ch == 'S');
}
Difference
Unconditional statement
C has four jump statements to perform an unconditional branch:
• return
• goto
• break and
• continue
Return statement
A return statement is used to return from a function. A function can use this statement
as a mechanism to return a value to its calling function. If now value is specified,
assume that a garbage value is returned (some compilers will return 0).
The general form of return statement is:
return expression;
Where expression is any valid rvalue expression.
Example:
return x; or return(x);
return x + y or return(x + y);
return rand(x); or return(rand(x));
return 10 * rand(x); or return (10 * rand(x));
goto statement Void main()
{
int x = 6, y = 12;
if( x == y)
x++;
else
goto error;
error:
printf (“Fatal error; Exiting”);
}
The compiler doesn‟t require any formal declaration of the label identifiers.
goto statement provides a method of
unconditional transfer control to a labeled
point in the program. The goto statement
requires a destination label declared as:
label:
The label is a word (permissible length is
machine dependent) followed by a colon. The
goto statement is formally defined as:
goto label;
„
„
„
label:
break statement
void main()
{
int value;
while (scanf(“%d'', &value ) == 1 && value != 0)
{
if(value < 0)
{
printf (“Illegal valuen'');
break; /* Terminate the loop */
}
if(value > 100)
{
printf(“Invalid valuen'');
continue; /* Skip to start loop again */
}
} /* end while value != 0 */
}
We can use it to terminate a case in a
switch statement and to terminate a
loop.
Consider the following example where we
read an integer values and process them
according to the following conditions.
If the value we have read is negative, we
wish to print an error message and
abandon the loop. If the value read is
greater than 100, we wish to ignore it
and continue to the next value in the
data.
If the value is zero, we wish to terminate
the loop.
Continue
statement
/* Program to print the even numbers below 100 */
#include<stdio.h>
void main()
{
int x;
for(x = 1; x < 10; x++)
{
if (x % 2)
continue;
printf (“%dt”, x)
}
}
The continue statement forces the
next iteration of the loop to take
place, skipping any code in
between.
But the break statement forces for
termination.
An odd number causes continue to execute and the next iteration to occur, by
passing the printf () statement. A continue statement is used within a loop ( i.e for,
while, do – while) to end an iteration in while and do-while loops, a continue
statement will cause control to go directly to the conditional test and then continue
the looping process.
In the case of for, first the increment part of the loop is performed, next the
conditional test is executed and finally the loop continues.
Difference
Exit statement
Void menu(void)
{
char ch;
printf(“B: Breakfast“);
printf(“L: Lunch“);
printf(“D: Dinner”);
printf(“E: Exit”);
printf(“Enter your choice: “);
do
{
ch = getchar();
switch (ch)
{
case „B‟ :
printf (“time for breakfast”);
break;
case „L‟ :
printf (“time for lunch”);
break;
case „D‟ :
printf (“time for dinner”);
break;
case „E‟ :
Just as we can break out of a loop, we can
break out of a program by using the
standard library function exit(). This
function causes immediate termination of
the entire program, forcing a return to the
operation system.
The general form of the exit() function is:
void exit (int return_code);
The value of the return_code is returned to
the calling process, which is usually the
operation system. Zero is generally used as
a return code to indicate normal program
termination.
exit (0); /* return to operating system */
}
} while (ch != „B‟ && ch != „L‟ && ch != „D‟);
}
Unit 1

More Related Content

What's hot

Programming in c
Programming in cProgramming in c
Programming in c
vishnu973656
 
Copmuter Languages
Copmuter LanguagesCopmuter Languages
Copmuter Languages
actanimation
 
Programming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwaresProgramming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwares
Nisarg Amin
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
meisaina
 
Language translator
Language translatorLanguage translator
Language translator
asmakh89
 
Programming Languages An Intro
Programming Languages An IntroProgramming Languages An Intro
Programming Languages An IntroKimberly De Guzman
 
Introduction to c language
Introduction to c language Introduction to c language
Introduction to c language
BAKRANIYA KALPESH
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
Akhil Kaushik
 
Fundamentals of programming final
Fundamentals of programming finalFundamentals of programming final
Fundamentals of programming final
Ricky Recto
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer ProgrammingProf. Erwin Globio
 
Programming assignment help
Programming assignment helpProgramming assignment help
Programming assignment help
www.myassignmenthelp.net
 
Compilers
CompilersCompilers
WEBSITE DEVELOPMENT
WEBSITE DEVELOPMENTWEBSITE DEVELOPMENT
WEBSITE DEVELOPMENT
shahzadebaujiti
 
The Programmer Life Cycle
The Programmer Life CycleThe Programmer Life Cycle
The Programmer Life Cycle
Russell Ovans
 
Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2
Mohd Harris Ahmad Jaal
 

What's hot (20)

Programming in c
Programming in cProgramming in c
Programming in c
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
df
dfdf
df
 
Copmuter Languages
Copmuter LanguagesCopmuter Languages
Copmuter Languages
 
Programming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwaresProgramming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwares
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Language translator
Language translatorLanguage translator
Language translator
 
Programming Languages An Intro
Programming Languages An IntroProgramming Languages An Intro
Programming Languages An Intro
 
Introduction to c language
Introduction to c language Introduction to c language
Introduction to c language
 
compiler vs interpreter
compiler vs interpretercompiler vs interpreter
compiler vs interpreter
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
Fundamentals of programming final
Fundamentals of programming finalFundamentals of programming final
Fundamentals of programming final
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
Programming assignment help
Programming assignment helpProgramming assignment help
Programming assignment help
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
Compilers
CompilersCompilers
Compilers
 
WEBSITE DEVELOPMENT
WEBSITE DEVELOPMENTWEBSITE DEVELOPMENT
WEBSITE DEVELOPMENT
 
The Programmer Life Cycle
The Programmer Life CycleThe Programmer Life Cycle
The Programmer Life Cycle
 
Computer
ComputerComputer
Computer
 
Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2
 

Similar to Unit 1

CS3251-_PIC
CS3251-_PICCS3251-_PIC
Programming in C
Programming in CProgramming in C
Programming in C
Rvishnupriya2
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
Subramanyambharathis
 
C.pdf
C.pdfC.pdf
2 Programming Language.pdf
2 Programming Language.pdf2 Programming Language.pdf
2 Programming Language.pdf
KINGZzofYouTube
 
Compiler design slide share
Compiler design slide shareCompiler design slide share
Compiler design slide share
Sudhaa Ravi
 
Introduction to C Programming Language.pptx
Introduction to C Programming Language.pptxIntroduction to C Programming Language.pptx
Introduction to C Programming Language.pptx
AnithaTAssistantProf
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computer
zaheeriqbal41
 
C Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYC Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYRajeshkumar Reddy
 
C Lang notes.ppt
C Lang notes.pptC Lang notes.ppt
C Lang notes.ppt
ShivanadhuniBhanuPra
 
C programme presentation
C programme presentationC programme presentation
C programme presentation
DharmaKumariBhandari
 
computerprogramminglanguages-201216152310.pptx
computerprogramminglanguages-201216152310.pptxcomputerprogramminglanguages-201216152310.pptx
computerprogramminglanguages-201216152310.pptx
Subramanian Mani
 
Intoduction to c language
Intoduction to c languageIntoduction to c language
Intoduction to c language
Student
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
Ali Raza
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
Noel Malle
 
class1.pdf
class1.pdfclass1.pdf
class1.pdf
SujalSalvi4
 
Computer programming languages
Computer programming languagesComputer programming languages
Computer programming languages
SubramanianMuthusamy3
 
Programming Fundamental Slide No.1
Programming Fundamental Slide No.1Programming Fundamental Slide No.1
Programming Fundamental Slide No.1
Arslan Hussain
 

Similar to Unit 1 (20)

CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
Programming in C
Programming in CProgramming in C
Programming in C
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
 
C.pdf
C.pdfC.pdf
C.pdf
 
C_NOTES.pdf
C_NOTES.pdfC_NOTES.pdf
C_NOTES.pdf
 
Programming in c
Programming in cProgramming in c
Programming in c
 
2 Programming Language.pdf
2 Programming Language.pdf2 Programming Language.pdf
2 Programming Language.pdf
 
Compiler design slide share
Compiler design slide shareCompiler design slide share
Compiler design slide share
 
Introduction to C Programming Language.pptx
Introduction to C Programming Language.pptxIntroduction to C Programming Language.pptx
Introduction to C Programming Language.pptx
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computer
 
C Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDYC Unit 1 notes PREPARED BY MVB REDDY
C Unit 1 notes PREPARED BY MVB REDDY
 
C Lang notes.ppt
C Lang notes.pptC Lang notes.ppt
C Lang notes.ppt
 
C programme presentation
C programme presentationC programme presentation
C programme presentation
 
computerprogramminglanguages-201216152310.pptx
computerprogramminglanguages-201216152310.pptxcomputerprogramminglanguages-201216152310.pptx
computerprogramminglanguages-201216152310.pptx
 
Intoduction to c language
Intoduction to c languageIntoduction to c language
Intoduction to c language
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
 
class1.pdf
class1.pdfclass1.pdf
class1.pdf
 
Computer programming languages
Computer programming languagesComputer programming languages
Computer programming languages
 
Programming Fundamental Slide No.1
Programming Fundamental Slide No.1Programming Fundamental Slide No.1
Programming Fundamental Slide No.1
 

More from TPLatchoumi

Unit 3
Unit 3Unit 3
Unit 3
TPLatchoumi
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
Unit iii
Unit iiiUnit iii
Unit iii
TPLatchoumi
 
Unit i
Unit iUnit i
Unit i
TPLatchoumi
 
Unit ii
Unit iiUnit ii
Unit ii
TPLatchoumi
 
Unit v
Unit vUnit v
Unit v
TPLatchoumi
 
Unit iv
Unit ivUnit iv
Unit iv
TPLatchoumi
 
17 cs002
17 cs00217 cs002
17 cs002
TPLatchoumi
 

More from TPLatchoumi (9)

Unit 3
Unit 3Unit 3
Unit 3
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Unit i
Unit iUnit i
Unit i
 
Unit ii
Unit iiUnit ii
Unit ii
 
Unit v
Unit vUnit v
Unit v
 
Unit iv
Unit ivUnit iv
Unit iv
 
Coa
Coa Coa
Coa
 
17 cs002
17 cs00217 cs002
17 cs002
 

Recently uploaded

Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 

Recently uploaded (20)

Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 

Unit 1

  • 1. Basics of C- Language Unit – I by Dr.T.P.Latchoumi
  • 2. Overview of C language Developed at Bell Laboratories in the early seventies by Dennis Ritchie. Born out of two other languages – BCPL (Basic Control Programming Language) and B. C introduced such things as character types, floating point arithmetic, structures, unions and the preprocessor. The principal objective was to devise a language that was easy enough to understand to be "high-level" – i.e. understood by general programmers, but low- level enough to be applicable to the writing of systems-level software.
  • 3. Cont… The language should abstract the details of how the computer achieves its tasks in such a way as to ensure that C could be portable across different types of computers, thus allowing the UNIX operating system to be compiled on other computers with a minimum of re-writing. C as a language was in use by 1973, although extra functionality, such as new types, was introduced up until 1980. In 1978, Brian Kernighan and Dennis M. Ritchie wrote the seminal work The C Programming Language, which is now the standard reference book for C. A formal ANSI standard for C was produced in 1989.
  • 4. Cont… In 1986, a descendant of C, called C++ was developed by Bjarne Stroustrup, which is in wide use today. Many modern languages such as C#, Java and Perl are based on C and C++. Using C language scientific, business and system-level applications can be developed easily.
  • 5. Program There is a close analogy between learning English language and learning C language. The classical method of learning English is to first learn the alphabets used in the language, then learn to combine these alphabets to form words, which in turn are combined to form sentences and sentences are combined to form paragraphs. Learning C is similar and easier. Instead of straight-away learning how to write programs, we must first know what alphabets, numbers and special symbols are used in C, then how using them constants, variables and keywords are constructed, and finally how are these combined to form an instruction.
  • 7. Types of Languages Low level languages are machine level and assembly level language. In machine level language computer only understand digital numbers i.e. in the form of 0 and 1. So, instruction given to the computer is in the form binary digit, which is difficult to implement instruction in binary code. This type of program is not portable, difficult to maintain and also error prone. The assembly language is on other hand modified version of machine level language. Where instructions are given in English like word as ADD, SUM, MOV etc. It is easy to write and understand but not understand by the machine. So the translator used here is assembler to translate into machine level. Although language is bit easier, programmer has to know low level details related to low level language. In the assembly level language the data are stored in the computer register, which varies for different computer. Hence it is not portable. Low level language
  • 8. Types of Languages These languages are machine independent, means it is portable.  The language in this category is Pascal, COBOL, Fortran etc. High level languages are understood by the machine. So it needs to translate by the translator into machine level. A translator is software which is used to translate high level language as well as low level language in to machine level language. High level language
  • 9. Types of translator  Compiler Interpreter Assembler
  • 10. Compiler A compiler is a translator used to convert high level language to low level language. It converts the whole program in one session and reports errors detected after the conversion. The compiler takes time to do its work as it translates high-level code to lower-level code all at once and then saves it to memory. A compiler is processor-dependent and platform-dependent. It has been addressed by alternate names as the following: special compiler, cross-compiler and, source-to-source compiler.
  • 11. Interpreter The interpreter is similar to a compiler, it is a translator used to convert high-level programming language to low-level programming language. The difference is that it converts the program one line of code at a time and reports errors when detected, while also doing the conversion. An interpreter is faster than a compiler as it immediately executes the code upon reading the code. It is often used as a debugging tool for software development as it can execute a single line of code at a time. An interpreter is also more portable than a compiler as it is processor-independent, you can work between different hardware architectures.
  • 12. Assembler An assembler is a translator used to translate assembly language into machine language. It has the same function as a compiler for the assembly language but works like an interpreter. Assembly language is difficult to understand as it is a low-level programming language. An assembler translates a low-level language, such as an assembly language to an even lower-level language, such as the machine code.
  • 13. Characteristics of C We briefly list some of C's characteristics that define the language and also have lead to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course. • Small size • Extensive use of function calls • Loose typing • Structured language • Low level (Bitwise) programming readily available • Pointer implementation - extensive use of pointers for memory, array, structures and functions.
  • 14. Cont… C has now become a widely used professional language for various reasons. • It has high-level constructs. • It can handle low-level activities. • It produces efficient programs. • It can be compiled on a wide variety of computers.
  • 15. Compiling & Executing C Program Step 1: The program that is to be compiled is first typed into a file on the computer system. There are various conventions that are used for naming files, typically be any name provided the last two characters are “.c” or file with extension .c. Step 2: After the source program has been entered into a file, then proceed to have it compiled. The compilation process is initiated by typing a special command on the system. When this command is entered, the name of the file that contains the source program must also be specified. For example, under Unix, the command to initiate program compilation is called cc. If we are using the popular GNU C compiler, the command we use is gcc. A compiler is a software program that analyzes a program developed in a particular computer language and then translates it into a form that is suitable for execution on a particular computer system.
  • 16. Cont… Step 3: When all the syntactic and semantic errors have been removed from the program, the compiler then proceeds to take each statement of the program and translate it into a “lower” form that is equivalent to assembly language program needed to perform the identical task. Step 4: After the program has been translated the next step in the compilation process is to translate the assembly language statements into actual machine instructions. The assembler takes each assembly language statement and converts it into a binary format known as object code, which is then written into another file on the system. This file has the same name as the source file under Unix, with the last letter an “o” (for object) instead of a “c”.
  • 17. Cont… Step 5: After the program has been translated into object code, it is ready to be linked. This process is once again performed automatically whenever the cc or gcc command is issued under Unix. The purpose of the linking phase is to get the program into a final form for execution on the computer. Step 6: To subsequently execute the program, the command a.out has the effect of loading the program called a.out into the computer‟s memory and initiating its execution.
  • 19. C character Set Letters Uppercase characters (A-Z) Lowercase characters (a-z) Numbers All the digits from 0 to 9 White spaces Blank space New line Carriage return Horizontal tab A character denotes any alphabet, digit or special symbol used to represent information.  Valid alphabets, numbers and special symbols allowed in C are Letters Numbers White spaces Special Characters
  • 20. Special characters The alphabets, numbers and special symbols when properly combined form constants, variables and keywords.
  • 21. C Tokens TOKEN is the smallest unit in a 'C' program. It is each and every word and punctuation that you come across in your C program. The compiler breaks a program into the smallest possible units (tokens) and proceeds to the various stages of the compilation. A token is divided into six different types, such as Keywords, Operators, Strings, Constants, Special Characters, and Identifiers.
  • 22. 32 Keywords Flow control (6) – if, else, return, switch, case, default Loops (5) – for, do, while, break, continue Common types (5) – int, float, double, char, void For dealing with structures (3) – struct, typedef, union Counting and sizing things (2) – enum, sizeof Rare but still useful types (7) – extern, signed, unsigned, long, short, static, const Keywords that is undiscouraged and which we NEVER use (1) – goto We don't use unless we're doing something strange (3) – auto, register, volatile
  • 23. Identifiers Rules for naming identifiers are: 1) name should only consists of alphabets (both upper and lower case), digits and underscore (_) sign. 2) first characters should be alphabet or underscore 3) name should not be a keyword 4) since C is a case sensitive, the upper case and lower case considered differently, for example code, Code, CODE etc. are different identifiers. 5) identifiers are generally given in some meaningful name such as value, net_salary, age, data etc. 6) It should not contain any whitespace character. Identifiers are user defined word used to name of entities like variables, arrays, functions, structures etc.
  • 24. Constants Constant is a any value that cannot be changed during program execution. In C, any number, single character, or character string is known as a constant. A constant is an entity that doesn‟t change whereas a variable is an entity that may change.
  • 25. Operators This is a symbol use to perform some operation on variables, operands or with the constant. Some operator required 2 operand to perform operation or some required single operation. Several operators are there those are, arithmetic operator, assignment, increment, decrement, logical, conditional, comma, size of , bitwise and others.
  • 26. Special characters The alphabets, numbers and special symbols when properly combined form constants, variables and keywords.
  • 27. Strings In C programming, a string is a sequence of characters terminated with a null character 0. For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character 0 at the end by default.
  • 28. Simple C program structure 1 ) Comment line 2) Preprocessor directive 3 ) Global variable declaration 4) main function( ) { Local variables; Statements; } User defined function } }
  • 29. Comments It indicates the purpose of the program. It is represented as /*……………………………..*/ Comment line is used for increasing the readability of the program. It is useful in explaining the program and generally used for documentation. It is enclosed within the decimeters. Comment line can be single or multiple line but should not be nested. It can be anywhere in the program except inside string constant & character constant.
  • 30. Preprocessor directive #include tells the compiler to include information about the standard input/output library. It is also used in symbolic constant such as #define PI 3.14(value). The stdio.h (standard input output header file) contains definition &declaration of system defined function such as printf( ), scanf( ), pow( ) etc. Generally printf() function used to display and scanf() function used to read value
  • 31. Global declaration This is the section where variable are declared globally so that it can be access by all the functions used in the program. And it is generally declared outside the function
  • 32. main() Syntax main() { …….. …….. …….. } It is the user defined function and every function has one main() function from where actually program is started and it is encloses within the pair of curly braces. The main( ) function can be anywhere in the program but in general practice it is placed in the first position.
  • 33. /*First c program with return statement*/ #include <stdio.h> int main (void) { printf ("welcome to c Programming language.n"); return 0; } Output: welcome to c programming language
  • 34. Constants C Constants is the most fundamental and essential part of the C programming language. Constants in C are the fixed values that are used in a program, and its value remains the same during the entire execution of the program. Constants are also called literals. Constants can be any of the data types. const keyword defines a constant in C. It is considered best practice to define constants using only upper-case names. Syntax const type constant_name;
  • 35. Example #include<stdio.h> main() { const int SIDE = 10; int area; area = SIDE*SIDE; printf("The area of the square with side: %d is: %d sq. units", SIDE, area); } Output: The area of the square with side: 10 is: 100 sq. units
  • 36. Types of Constants Constants are categorized into two basic types, and each of these types has its subtypes/categories. These are: Primary Constants 1. Numeric Constants Integer Constants Real Constants 2. Character Constants Single Character Constants String Constants Backslash Character Constants
  • 37. Integer Constants An integer constant must have at least one digit. It must not have a decimal point. It can either be positive or negative. No commas or blanks are allowed within an integer constant. If no sign precedes an integer constant, it is assumed to be positive. The allowable range for integer constants is -32768 to 32767. Example: 0 , -33, 32767 There are three types of integer constants namely, a) Decimal integer b) Octal integer constant c) Hexadecimal integer
  • 38. Decimal Integer constant (base 10) •It consists of any combinations of digits taken from the set 0 through 9, preceded by an optional – or + sign. •The first digit must be other than 0. Embedded spaces, commas, and non-digit characters are not permitted between digits. Valid: 0 32767 -9999 -23 Invalid: 12,245 - Illegal character (,) 10 20 30 - Illegal character (blank space)
  • 39. Octal Integer Constant (base 8) It consists of any combinations of digits taken from the set 0 through 7. If a constant contains two or more digits, the first digit must be 0. In programming, octal numbers are used. Valid: 037 0 0435 Invalid: 0786 - Illegal digit 8 123 - Does not begin with zero 01.2 - Illegal character (.)
  • 40. Hexadecimal Integer Constant (base 16) It consists of any combinations of digits taken from the set 0 through 7 andalso a through f (either uppercase or lowercase). The letters a through f (or A through F) represent the decimal quantities 10 through 15 respectively. This constant must begin with either 0x or 0X. In programming, hexadecimal numbers are used. Valid Hexadecimal Integer Constant: 0x 0X1 0x7F Invalid Hexadecimal Integer Constant: 0xefg - Illegal character g 123 - Does not begin with 0x
  • 41. Real Constants (Fractional form) The numbers containing fractional parts like 99.25 are called real or floating points constant. Here are the rules for creating floating point constants in Fractional form: 1. Must have one at least one digit 2. Must have a decimal point 3. Can be positive or negative, the default is positive 4. No comma, blanks, or any other symbols are allowed Here are some examples: 3.14, 899.0, -0.999
  • 42. Real Constants (Exponential form) Exponential form is used in cases when a number is too small or too large. For example, 0.00000941 can be represented as 9.41e-6. The part of the number before e is called mantissa i.e 9.41, whereas, the part following e is called the exponent i.e -6. Here are the rules for creating floating point constants in Exponential form: 1. Mantissa and exponent must be separated by e or E. 2. Mantissa can be positive or negative, default is positive. 3. Exponent must have at least one digit. 4. The exponent can be positive or negative default is positive Some examples of floating point numbers in exponential form are: 100.34e4, -56E10, 0.233E10, -0.94e15 By default, floating constants are of type double. We can explicitly mention the type of a floating-point constant as a float by appending f or F at the end of the constant. For example: 12f, -0.87f
  • 43. Character Constant 1. A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes. 2. The maximum length of a character constant is 1 character. 3. String constants are enclosed within double quotes.
  • 44. Single character constant It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be noted that the character '8' is not the same as 8. Character constants have a specific set of integer values known as ASCII values (American Standard Code for Information Interchange). Example: 'X', '5', ';' The maximum length of a character constant is 1 character long. That means you cannot put more than one character inside single quotation marks like this 'ab' // Wrong '12' // Wrong
  • 45. String constant String constants consist of zero or more characters enclosed in double quotes (""). At the end of the string, the null character i.e '0' is automatically placed by the compiler. Here are some examples of string constants: "hello" "123" "" // This is empty string Although not officially part of Primary constants, string constants are given here for the sake of completeness. C has no data type for string, they are stored as an array of characters. We will learn more about strings in a great deal in its own chapter
  • 46. Backslash character constant There are some characters which have special meaning in C language. They should be preceded by backslash symbol to make use of special function of them. Given below is the list of special characters and their purpose.
  • 47. Symbolic Constant It is generally defined at the beginning of the program. Here is the syntax of creating a Symbolic constant. #define NAME VALUE #define is a preprocessor directive just like #include, that's why it doesn't end with the semicolon (;). NAME indicates the name we want to give to our constant and is generally written in uppercase. VALUE can be numeric, character or string constant. Let's create a symbolic constant called PI. #define PI 3.141592 If we want to use constant several times in a program, then we can provide it a name. For example: If there is a need to use constant Π = 3.141592 at several places in the program, then we can give it a name and use that name instead of writing this long number. This constant is called Symbolic constant.
  • 48. Example 1 #include <stdio.h> void main() { const int height = 100; /*int constant*/ const float number = 3.14; /*Real constant*/ const char letter = 'A'; /*char constant*/ const char letter_sequence[10] = "ABC"; /*string constant*/ const char backslash_char = '?'; /*special char cnst*/ printf("value of height :%d n", height ); printf("value of number : %f n", number ); printf("value of letter : %c n", letter ); printf("value of letter_sequence : %s n", letter_sequence); printf("value of backslash_char : %c n", backslash_char); }
  • 49. Example 2 #include<stdio.h> main() { const int SIDE = 10; int area; area = SIDE*SIDE; printf("The area of the square with side: %d is: %d sq. units" , SIDE, area); } Output: The area of the square with side: 10 is: 100 sq. units
  • 50. Variables A variable is a value that can change. A symbol or name that stands for a value. Variables provide temporary storage for information that will be needed during the lifespan of the computer program (or application). Variables store everything in your program. • The purpose of any useful program is to modify variables. • In a program every, variable has: – Name (Identifier) – Data Type – Size – Value A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
  • 51. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types –
  • 52. Variables definition Some valid declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int. A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list;
  • 53. Variable initialization Some examples are − extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value;
  • 54. Example #include <stdio.h> extern int a, b; extern int c; extern float f; int main () { int a, b; int c; float f; a = 10; b = 20; c = a + b; printf("value of c : %d n", c); f = 70.0/3.0; printf("value of f : %f n", f); return 0; } Output value of c : 30 value of f : 23.333334
  • 56. Local variable Advantages of using Local Variables • The use of local variables offer a guarantee that the values of variables will remain intact while the task is running • If several tasks change a single variable that is running simultaneously, then the result may be unpredictable. But declaring it as local variable solves this issue as each task will create its own instance of the local variable. • You can give local variables the same name in different functions because they are only recognized by the function they are declared in. • Local variables are deleted as soon as any function is over and release the memory space which it occupies. Disadvantages of using Local Variables • The debugging process of a local variable is quite tricky. • Common data required to pass repeatedly as data sharing is not possible between modules. • They have a very limited scope. Local variables are those that are in scope within a specific part of the program (function, procedure, method, or subroutine, depending on the programming language employed). The scope of local variables will be within the function only. These variables are declared within the function and can‟t be accessed outside the function.
  • 57. Example 1 #include<stdio.h> void test(); int main() { int m = 22, n = 44; printf("nvalues : m = %d and n = %d", m, n); test(); } void test() { int a = 50, b = 80; printf("nvalues : a = %d and b = %d", a, b); }
  • 58. Example 2 #include<stdio.h> int main() { int a = 100; { int a = 10; printf("Inner a = %dn", a); } printf("Outer a = %dn", a); // signal to operating system everything works fine return 0; }
  • 59. Global variable Advantages of using Global variables You can access the global variable from all the functions or modules in a program You only require to declare global variable single time outside the modules. It is ideally used for storing "constants" as it helps you keep the consistency. A Global variable is useful when multiple functions are accessing the same data. Disadvantages of using Global Variables Too many variables declared as global, then they remain in the memory till program execution is completed. This can cause of Out of Memory issue. Data can be modified by any function. Any statement written in the program can change the value of the global variable. This may give unpredictable results in multi-tasking environments. If global variables are discontinued due to code refactoring, you will need to change all the modules where they are called. Global variables are those that are in scope for the duration of the programs execution. They can be accessed by any part of the program, and are readwrite for all statements that access them. The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program. This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions.
  • 60. Example 1 #include<stdio.h> void test(); int m = 22, n = 44; int a = 50, b = 80; int main() { printf("All variables are accessed from main function"); printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b); test(); } void test() { printf("nnAll variables are accessed from" " test function"); printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b); }
  • 63. Datatypes Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. A programming language is proposed to help programmer to process certain kinds of data and to provide useful output. The task of data processing is accomplished by executing series of commands called program. A program usually contains different types of data types (integer, float, character etc.) and need to store the values being used in the program. C language is rich of data types.
  • 64. Types
  • 65. Integer types Integer Data Types: Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767 (that is, -2 15 to +215 -1). A signed integer use one bit for storing sign and rest 15 bits for number. Syntax: int <variable name>; Example int num1; short int num2; long int num3; Example: 5, 6, 100, 2500.
  • 67.
  • 68. Floating point types The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space. Syntax: float <variable name>; Examples float num1; double num2; long double num3; Example: 9.125, 3.1254.
  • 70.
  • 71. Void data type The void type specifies that no value is available. It is used in three kinds of situations
  • 72. Operators C language is rich in built-in operators and provides the following types of operators: 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Bitwise Operators 5. Assignment Operators 6. Sizeof() operators 7. Ternary operators 8. Special operators 9. Unary operators An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
  • 73. Arithmetic operators The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then
  • 75. Relational operator The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then −
  • 77. Logical operator Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then −
  • 79. Bitwise operator Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
  • 80. Assignment operator The following table lists the assignment operators supported by the C language −
  • 83. Sizeof() It is a much used operator in the C. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union etc. Usage sizeof() operator is used in different way according to the operand type.
  • 86. Ternary operator If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is also called as conditional operator The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. Ternary operator is shortened way of writing an if-else statement. Ternary operator is a?b:c it say that the condition a is true b will be executed else c will be executed. Advantage of Ternary Operator Using ?: reduce the number of line codes and improve the performance of application. Syntax expression-1 ? expression-2 : expression-3
  • 89. Unary operator ◦ unary minus The minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive. int a = 10; int b = -a; // b = -10 unary minus is different from subtraction operator, as subtraction requires two operands. Unary operator: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++) decrement(- -) NOT(!) Addressof operator(&) sizeof()
  • 90. Increment operator prefix increment In this method, the operator preceeds the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1; int b = ++a; // b = 2 postfix increment In this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1; int b = a++; // b = 1 int c = a; // c = 2 It is used to increment the value of the variable by 1. The increment can be done in two ways:
  • 91. Decrement operator prefix decrement In this method, the operator preceeds the operand (e.g., – - a). The value of operand will be altered before it is used. int a = 1; int b = --a; // b = 0 posfix decrement In this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1; int b = a--; // b = 1 int c = a; // c = 0 It is used to decrement the value of the variable by 1. The decrement can be done in two ways:
  • 92. NOT and address operators ◦ NOT(!): It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. If x is true, then !x is false If x is false, then !x is true ◦ Addressof operator(&): It gives an address of a variable. It is used to return the memory address of a variable. These addresses returned by the address-of operator are known as pointers because they “point” to the variable in memory. & gives an address on variable n int a; int *ptr; ptr = &a; // address of a is copied to the location ptr.
  • 93. Expressions Expressions are the fundamental means of specifying computations in a programming language –To understand the expression evaluation, it is necessary to be familiar with the orders of operator and operand evaluation – The essence of the imperative programming languages is the dominant role of assignment statements An expression is a combination of variables constants and operators written according to the syntax of C language. In C every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable. Evaluation of Expressions Precedence in Arithmetic Operators Type conversions in expressions Order Category Operator Associativity
  • 94. Evaluation of expressions Expressions are evaluated using an assignment statement of the form Variable = expression; Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and then replaces the previous value of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. Example of evaluation statements are x = a * b – c y = b / c * a z = a – b / c + d;
  • 96. Precedence in arithmetic operators Rules for evaluation of expression • First parenthesized sub expression left to right are evaluated. • If parenthesis are nested, the evaluation begins with the innermost sub expression. • The precedence rule is applied in determining the order of application of operators in evaluating sub expressions. • 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. An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C. High priority * / % Low priority + -
  • 97. Type conversion in expression The following rules apply during evaluating expressions All short and char are automatically converted to int then 1. If one operand is long double, the other will be converted to long double and result will be long double. 2. If one operand is double, the other will be converted to double and result will be double. 3. If one operand is float, the other will be converted to float and result will be float. 4. If one of the operand is unsigned long int, the other will be converted into unsigned long int and result will be unsigned long int. 5. If one operand is long int and other is unsigned int then a. If unsigned int can be converted to long int, then unsigned int operand will be converted as such and the result will be long int. …..b. Else Both operands will be converted to unsigned long int and the result will be unsigned long int. 6. If one of the operand is long int, the other will be converted to long int and the result will be long int. 7. If one operand is unsigned int the other will be converted to unsigned int and the result will be unsigned int. Implicit type conversion C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. This automatic type conversion is know as implicit type conversion During evaluation it adheres to very strict rules and type conversion. If the operands are of different types the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type.
  • 98. Operator precedence and associativity Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence. For example: Solve 10 + 20 * 30
  • 100. Managing I/O operations 1. Standard Input (stdin) Standard input or stdin is used for taking input from devices such as the keyboard as a data stream. 1. Standard Output (stdout) Standard output or stdout is used for giving output to a device such as a monitor. I/O operations are useful for a program to interact with users. stdlib is the standard C library for input-output operations. While dealing with input-output operations in C, two important streams play their role. These are:
  • 101. Reading character in C The easiest and simplest of all I/O operations are taking a character as input by reading that character from standard input (keyboard). getchar() function can be used to read a single character. This function is alternate to scanf() function. Syntax var_name = getchar();
  • 102. Writing character in C Similar to getchar() there is another function which is used to write characters, but one at a time. Syntax putchar(var_name);
  • 103. Reading and Writing Strings in C The gets() function reads a string of characters entered at the keyboard and places them at the address pointed to by its argument. We can type characters at the keyboard until we strike a carriage return. The carriage return does not become part of the string; instead a null terminator is placed at the end and gets() returns. Typing mistakes can be corrected prior to striking ENTER. The prototype for gets() is: char* gets (char *str);
  • 105. Example #include<stdio.h> int main() { char str[100]; printf("Enter a string: "); gets(str); printf("The Entered string : %sn",str); return 0; } Output:- Enter a string: Know Program C language The Entered string : Know Program C language
  • 107. Example #include<stdio.h> int main() { char str1[100], str2[100]; printf("Enter two string: "); gets(str1); fgets(str2, sizeof(str2), stdin); //Notice displaying order printf("String 1: %s ",str1); printf("String 2: %s",str2); return 0; } Output:- Enter two string: Know Program C language String 1: Know Program String 2: C language
  • 108. C - Formatted I/O Functions C language provide us console input/output functions. As the name says, the console input/output functions allow us to - • Read the input from the keyboard by the user accessing the console. • Display the output to the user at the console. Note : These input and output values could be of any primitive data type.
  • 110. Scanf() It refers to an input data which has been arranged in a specific format. This is possible in C using scanf(). Syntax: scanf("control string", arg1, arg2, ..., argn);
  • 111. Example OUTPUT : Enter any character a Entered character is a Enter any string ( upto 100 character ) hai Entered string is hai
  • 112. Printf() • In C programming language, printf() function is used to print the (“character, string, float, integer, octal and hexadecimal values”) onto the output screen. • We use printf() function with %d format specifier to display the value of an integer variable. • Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable. • To generate a newline,we use “n” in C printf() statement. Note: • C language is case sensitive. For example, printf() and scanf() are different from Printf() and Scanf(). All characters in printf() and scanf() functions must be in lower case. • All output starts in the leftmost box, although some output might be "padded" with blank spaces to align it to the right edge of the field. "X"'s indicated unused positions.
  • 113. Difference between puts() and printf()
  • 115. Decision Making This deals with the various methods that C can control the flow of logic in a program. Control statements can be classified as un- conditional and conditional branch statements and loop or iterative statements. The Branch type includes: 1. Un-conditional: goto, break, return, continue, exit 2. Conditional: if, if-else, nested if, switch case statement 3. Loop or iterative: for loop, while loop, do-while loop
  • 116. Conditional Statement Sometimes we want a program to select an action from two or more alternatives. This requires a deviation from the basic sequential order of statement execution. Such programs must contain two or more statements that might be executed, but have some way to select only one of the listed options each time the program is run. This is known as conditional execution.
  • 117. if statement Statement or set of statements can be conditionally executed using if statement. Here, logical condition is tested which, may either true or false. If the logical test is true (non zero value) the statement that immediately follows if is executed. If the logical condition is false the control transfers to the next executable statement.
  • 119. if – else statement The general syntax of simple if - else statement is: The if statement is used to execute only one action. If there are two statements to be executed alternatively, then if-else statement is used. The if-else statement is a two way branching.
  • 120. Example #include <stdio.h> int main() { int age; printf("Enter your age:"); scanf("%d",&age); if(age >=18) { /* This statement will only execute if the * above condition (age>=18) returns true */ printf("You are eligible for voting"); } else { /* This statement will only execute if the * condition specified in the "if" returns false. */ printf("You are not eligible for voting"); } return 0; } Output Enter your age:14 You are not eligible for voting
  • 121. Nested if statement The ANSI standard specifies that 15 levels of nesting must be supported. In C, an else statement always refers to the nearest if statement in the same block and not already associated with if.
  • 122. Example #include <stdio.h> int main () { /* local variable definition */ int a = 100; int b = 200; /* check the boolean condition */ if( a == 100 ) { /* if condition is true then check the following */ if( b == 200 ) { /* if condition is true then print the following */ printf("Value of a is 100 and b is 200n" ); } } Output Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 printf("Exact value of a is : %dn", a ); printf("Exact value of b is : %dn", b ); return 0; }
  • 123. if –else – if ladder When faced with a situation in which a program must select from many processing alternatives based on the value of a single variable, an analyst must expand his or her use of the basic selection structure beyond the standard two processing branches offered by the if statement to allow for multiple branches. One solution to this is to use an approach called nesting in which one (or both) branch(es) of a selection contain another selection.
  • 124. Example Output Enter a Number: -5 Given Number is Negative #include<stdio.h> #include<conio.h> void main() { int a; printf("Enter a Number: "); scanf("%d",&a); if(a > 0) { printf("Given Number is Positive"); } else if(a == 0) { printf("Given Number is Zero"); } else if(a < 0) { printf("Given Number is Negative"); } getch(); }
  • 125. The switch case statement The general form of switch case statement is: switch (expression) { case constant1: statement; break; case constant2: statement; break; default: statement; break; } The switch-case statement is used when an expression’s value is to be checked against several values. If a match takes place, the appropriate action is taken.
  • 126. Three important things to know about switch statement 1. The switch differs from the if in that switch can only test for equality whereas if can evaluate any type of relational or logical expression. 2. No two case constants in the same switch can have identical values. But, a switch statement enclosed by an outer switch may have case constants and either same. 3. If character constants are used in the switch statement, they are automatically converted to integers.
  • 127. Example #include <stdio.h> int main() { int num=2; switch(num+2) { case 1: printf("Case1: Value is: %d", num); case 2: printf("Case1: Value is: %d", num); case 3: printf("Case1: Value is: %d", num); default: printf("Default: Value is: %d", num); } return 0; } Output: Default: value is: 2
  • 128. Looping statement Looping is a powerful programming technique through which a group of statements is executed repeatedly, until certain specified condition is satisfied. Looping is also called a repetition or iterative control mechanism. Types of Loops in C Depending upon the position of a control statement in a program, looping in C is classified into two types: 1. Entry controlled loop 2. Exit controlled loop In an entry controlled loop, a condition is checked before executing the body of a loop. It is also called as a pre-checking loop. Eg. do-while loop In an exit controlled loop, a condition is checked after executing the body of a loop. It is also called as a post-checking loop. Eg. for and while loop C provides three types of loop control structures. They are: • for statement • while statement • do-while statement
  • 129. for statement The for loop statement is useful to repeat a statement/s a known number of times. The general syntax is as follows: for (initialization; condition; operation) { statement; } The initialization is generally an assignment statement that is used to set the loop control variable. The condition is an expression(relational/logical/arithmetic/bitwise ….) that determines when the loop exists. The Operation defines how the loop control variable changes each time the loop is repeated.
  • 131. Example #include <stdio.h> int main() { int i; for (i=1; i<=3; i++) { printf("%dn", i); } return 0; } Output 1 2 3
  • 132. Nested for loop Nested loops consist of one loop placed inside another loop. An example of a nested for loop is: for (initialization; condition; operation) { for (initialization; condition; operation) { statement; } statement; }
  • 134. while statement The second loop available in ‘C’ is while loop. The general format of while loop is: while (expression) { statement } A while statement is useful to repeat a statement execution as long as a condition remains true or an error is detected. The while statement tests the condition before executing the statement.
  • 135. Example #include <stdio.h > void main() { int i, j, k, temp; printf("ItI^2tI^3tI^4 n"); printf("--------------------------------n"); i = 1; while (i < 10) /* Outer loop */ { j = 1; while (j < 5) /* 1st level of nesting */ { temp = 1; k = 1; while (k < j) { temp = temp * i; k++; } printf ("%dt", temp); j++; } printf ("n"); i++; }
  • 136. do-while statement The third loop available in C is do – while loop. The general format of do-while is: do { statement; } while (expression);
  • 137. Example1 # include <stdio.h> main() { do { printf("x = %dn", x--); } while(x > 0); } Output to the screen: X = 3 X = 2 X = 1
  • 138. Example 2 Output to the screen: T: Train C: Car S: Ship Enter your choice: T Train #include <stdio.h> void main() { char ch; printf("T: Trainn"); printf("C: Carn"); printf("S: Shipn"); do { printf("nEnter your choice: "); fflush(stdin); ch = getchar(); switch(ch) { case 'T' : printf("nTrain"); break; case 'C' : printf("nCar"); break; case 'S': printf("nShip"); break; default: printf("n Invalid Choice"); } } while(ch == 'T' || ch == 'C' || ch == 'S'); }
  • 140. Unconditional statement C has four jump statements to perform an unconditional branch: • return • goto • break and • continue
  • 141. Return statement A return statement is used to return from a function. A function can use this statement as a mechanism to return a value to its calling function. If now value is specified, assume that a garbage value is returned (some compilers will return 0). The general form of return statement is: return expression; Where expression is any valid rvalue expression. Example: return x; or return(x); return x + y or return(x + y); return rand(x); or return(rand(x)); return 10 * rand(x); or return (10 * rand(x));
  • 142. goto statement Void main() { int x = 6, y = 12; if( x == y) x++; else goto error; error: printf (“Fatal error; Exiting”); } The compiler doesn‟t require any formal declaration of the label identifiers. goto statement provides a method of unconditional transfer control to a labeled point in the program. The goto statement requires a destination label declared as: label: The label is a word (permissible length is machine dependent) followed by a colon. The goto statement is formally defined as: goto label; „ „ „ label:
  • 143. break statement void main() { int value; while (scanf(“%d'', &value ) == 1 && value != 0) { if(value < 0) { printf (“Illegal valuen''); break; /* Terminate the loop */ } if(value > 100) { printf(“Invalid valuen''); continue; /* Skip to start loop again */ } } /* end while value != 0 */ } We can use it to terminate a case in a switch statement and to terminate a loop. Consider the following example where we read an integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is greater than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop.
  • 144. Continue statement /* Program to print the even numbers below 100 */ #include<stdio.h> void main() { int x; for(x = 1; x < 10; x++) { if (x % 2) continue; printf (“%dt”, x) } } The continue statement forces the next iteration of the loop to take place, skipping any code in between. But the break statement forces for termination. An odd number causes continue to execute and the next iteration to occur, by passing the printf () statement. A continue statement is used within a loop ( i.e for, while, do – while) to end an iteration in while and do-while loops, a continue statement will cause control to go directly to the conditional test and then continue the looping process. In the case of for, first the increment part of the loop is performed, next the conditional test is executed and finally the loop continues.
  • 146. Exit statement Void menu(void) { char ch; printf(“B: Breakfast“); printf(“L: Lunch“); printf(“D: Dinner”); printf(“E: Exit”); printf(“Enter your choice: “); do { ch = getchar(); switch (ch) { case „B‟ : printf (“time for breakfast”); break; case „L‟ : printf (“time for lunch”); break; case „D‟ : printf (“time for dinner”); break; case „E‟ : Just as we can break out of a loop, we can break out of a program by using the standard library function exit(). This function causes immediate termination of the entire program, forcing a return to the operation system. The general form of the exit() function is: void exit (int return_code); The value of the return_code is returned to the calling process, which is usually the operation system. Zero is generally used as a return code to indicate normal program termination. exit (0); /* return to operating system */ } } while (ch != „B‟ && ch != „L‟ && ch != „D‟); }