SlideShare a Scribd company logo
UNIT-II-C PROGRAMMING BASICS
Introduction to C programming – Header files –
Structure of a C program – compilation and
linking processes – Constants, Variables – Data
Types – Expressions – operators – Input and
Output operations – Decision Making and
Branching – Looping statements- Programming
Examples
• ‘C’ is high level language and is the upgraded version of
another language (Basic Combined Program Language).
• C language was designed at Bell laboratories in the early
1970’s by Dennis Ritchie.
• Dennis Ritchie is known as the founder of the c language.
• C being popular in the modern computer world can be used in
Mathematical Scientific, Engineering and Commercial
applications.
• The most popular Operating system UNIX is written in C
language.
• This language also has the features of low level languages
and hence called as “System Programming Language”
Language Year Developed By
Algol 1960
International
Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K & R C 1978
Kernighan &
Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
Features of C language
• Simple, versatile, general purpose language
• It has rich set of Operators
• Program execution are fast and efficient
• Can easily manipulates with bits, bytes and addresses
• Varieties of data types are available
• Separate compilation of functions is possible and such
functions can be called by any C program
• Block- structured language
• Can be applied in System programming areas like operating
systems, compilers & Interpreters, Assembles, Text Editors,
Print Spoolers, Network Drivers, Modern Programs, Data
Bases, Language Interpreters, Utilities etc.
Structure of c program
Header files
• A header file is a file with extension .h which contains C
function declarations and macro definitions to be shared
between several source files.
• There are two types of header files:
• The files that the programmer writes .
• The files that comes with your compiler.
Sr.No. Header Files & Description
1 stdio.h Input/Output functions
2 conio.h Console Input/Output functions
3 stdlib.h General utility functions
4 math.h Mathematics functions
5 string.h String functions
6 ctype.h Character handling functions
7 time.h Date and time functions
8 float.h Limits of float types
9 limits.h Size of basic types
10 wctype.h Functions to determine the type contained in wide
character data.
Compilation and linking processes
• Compilation refers to the processing of source code files (.c, .cc, or
.cpp) and the creation of an 'object' file.
• This step doesn't create anything the user can actually run.
• Instead, the compiler merely produces the machine language instructions
that correspond to the source code file that was compiled.
• For instance, if you compile (but don't link) three separate files, you will
have three object files created as output, each with the name
<filename>.o or <filename>.obj (the extension will depend on your
compiler).
• Each of these files contains a translation of your source code file into a
machine language file -- but you can't run them yet! You need to turn
them into executables your operating system can use.
• Linking refers to the creation of a single executable file
from multiple object files.
• In this step, it is common that the linker will complain
about undefined functions (commonly, main itself).
• During compilation, if the compiler could not find the
definition for a particular function, it would just assume
that the function was defined in another file.
• If this isn't the case, there's no way the compiler would
know -- it doesn't look at the contents of more than one
file at a time.
• The linker, on the other hand, may look at multiple files
and try to find references for the functions that weren't
mentioned.
• there are separate compilation and linking steps.
• First, it's probably easier to implement things that way.
• The compiler does its thing, and the linker does its thing --
by keeping the functions separate, the complexity of the
program is reduced.
• Another (more obvious) advantage is that this allows the
creation of large programs without having to redo the
compilation step every time a file is changed. Instead,
using so called "conditional compilation“.
• it is necessary to compile only those source files that have
changed; for the rest, the object files are sufficient input
for the linker.
• Finally, this makes it simple to implement libraries of pre-
compiled code: just create object files and link them just
like any other object file.
• (The fact that each file is compiled separately from
information contained in other files, incidentally, is called
the "separate compilation model".).
• To get the full benefits of condition compilation, it's
probably easier to get a program to help you than to try
and remember which files you've changed since you last
compiled.
• Knowing the difference between the compilation phase
and the link phase can make it easier to hunt for bugs.
• Compiler errors are usually syntactic in nature -- a
missing semicolon, an extra parenthesis.
• Linking errors usually have to do with missing or multiple
definitions.
• If you get an error that a function or variable is defined
multiple times from the linker, that's a good indication that
the error is that two of your source code files have the
same function or variable.
Data types in C
• A keyword that is used for creating variables for storing
single and multiple values is called data types
• Creating a variable for storing single and multiple values
in a program as part of performing one operation.
• To perform any operation first we must store values.
• To store values we must allocate memory.
• Here we need to provide the information above the
number of bytes and type of memory that must be
allocated to store a value.
• To specify the number of bytes and memory types to the
compiler and operating system.
• we must use some set of keywords. These sets of
keywords are collectively called data types.
• Hence we can say data type is used for allocating memory
for storing value in a program by specifying the required
numbers of bytes and memory type.
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
Basic Data Types
• There are four basic data types in C language.
• character data
• Integer data
• floating point data
• double data types.
a. Character data:
• Any character of the ASCII character set can be considered as a
character data types and its maximum size can be 1 byte or 8
byte long.
• ‘Char’ is the keyword used to represent character data type in C.
• Char - a single byte size, capable of holding one character.
• b. Integer data: The keyword ‘int’ stands for the integer
data type in C and its size is either 16 or 32 bits.
• The integer data type can again be classified as
1. Long int - long integer with more digits
2. Short int - short integer with fewer digits.
3. Unsigned int - Unsigned integer
4. Unsigned short int – Unsigned short integer
5. Unsigned long int – Unsigned long integer
• As above, the qualifiers like short, long, signed or
unsigned can be applied to basic data types to derive new
data types.
• int - an Integer with the natural size of the host machine.
• c. Floating point data: - The numbers which are stored in
floating point representation with mantissa and exponent
are called floating point (real) numbers.
• These numbers can be declared as ‘float’ in C.
• float – Single – precision floating point number value.
• d. Double data : - Double is a keyword in C to represent
double precision floating point numbers.
• double - Double – precision floating point number value.
• Data Kinds in C
• Various data kinds that can be included in any C program
can fall in to the following.
• a. Constants/Literals
• b. Reserve Words Keywords
• c. Delimeters
• d. Variables/Identifiers
• a. Constans/Literals: Constants are those, which do not
change, during the execution of the program.
• Constants may be categorized in to
• Numeric Constants
• Character Constants
• String Constants
1. Numeric Constants
• Numeric constants, as the name itself indicates, are those
which consist of numerals, an optional sign and an
optional period. They are further divided into two types:
(a) Integer Constants
(b) Real Constants
• a. Integer Constants: A whole number is an integer
constant Integer constants do not have a decimal point.
These are further divided into three types depending on
the number systems they belong to.
i. Decimal integer constants
ii. Octal integer constants
iii. Hexadecimal integer constants
Decimal Integer constant is characterized by the following
properties.
It is a sequence of one or more digits ([0…9], the symbols of
decimal number system).
• It may have an optional + or – sign. In the absence of sign, the
constant is assumed to be positive.
• Commas and blank spaces are not permitted.
• It should not have a period as part of it.
• examples of valid decimal integer constants:
• 456
• -123
• examples of invalid decimal integer constants:
• 4.56 - Decimal point is not permissible
• 1,23 - Commas are not permitted
• ii. An octal integer constant is characterized by the
following properties
• It is a sequence of one or more digits ([0…7], symbols of
octal number system).
• It may have an optional + or – sign. In the absence of sign,
the constant is assumed to be positive.
• It should start with the digit 0.
• Commas and blank spaces are not permitted.
• It should not have a period as part of it.
Some examples of valid octal integer constants:
• 0456
• -0123
• +0123
Some examples of invalid octal integer constants:
• 04.56 - Decimal point is not permissible
• 04,56 - Commas are not permitted
• x34 - x is not permissible symbol
• 568 - 8 is not a permissible symbol
• iii. An hexadecimal integer constant is characterized
by the following properties
• It is a sequence of one or more symbols ([0…9][A….Z],
the symbols of Hexadecimal number system).
• It may have an optional + or - sign. In the absence of sign,
the constant is assumed to be positive.
• It should start with the symbols 0X or 0x.
• Commas and blank spaces are not permitted.
• It should not have a period as part of it.
Some examples of valid hexadecimal integer constants:
• 0x456
• -0x123
• 0x56A
• 0XB78
Some examples of invalid hexadecimal integer constants:
• 0x4.56 - Decimal point is not permissible
• 0x4,56 - Commas are not permitted.
• b. Real Constants
• The real constants also known as floating point constants are
written in two forms:
(i) Fractional form,
(ii) Exponential form.
(i) Fractional form: The real constants in Fractional form are
characterized by the following characteristics:
• Must have at least one digit.
• Must have a decimal point.
• May be positive or negative and in the absence of sign taken
as positive.
• Must not contain blanks or commas in between digits.
• May be represented in exponential form, if the value is too
higher or too low.
Some examples of valid real constants:
• 456.78
• -123.56
Some examples of invalid real constants:
• 4.56 - Blank spaces are not permitted
• 4,56 - Commas are not permitted
• 456 - Decimal point missing
ii. Exponential Form
• The exponential form offers a convenient way for writing
very large and small real constant.
• For example, 56000000.00, which can be written as
0.56*, 108 is written as 0.56E8 or 0.56e8 in exponential
form.
• 0.000000234, which can be written as 0.234 * 10-6 is
written as 0.234E-6 or 0.234e-6 in exponential form.
• The letter E or e stand for exponential form.
• A real constant expressed in exponential form has two parts:
• (i) Mantissa part,
• (ii) Exponent part.
• Mantissa is the part of the real constant to the left of E or e,
and the Exponent of a real constant is to the right of E or e.
• Mantissa and Exponent of the above two number
Mantissa Exponent Mantissa Exponent
0.56 E 8 0.234 E -6
In the above examples, 0.56 and 0.234 are the mantissa parts
of the first and second numbers, respectively, and 8 and -6
are the exponent parts of the first and second number,
respectively.
• The real constants in exponential form and characterized
by the following characteristics:
• The mantissa must have at least one digit.
• The mantissa is followed by the letter E or e and the
exponent.
• The exponent must have at least one digit and must be an
integer.
• A sign for the exponent is optional
Some examples of valid real constants:
• 3E4
• 23e-6
• 0.34E6
Some examples of invalid real constants:
• 23E - No digit specified for exponent
• 23e4.5 - Exponent should not be a fraction
• 23,4e5 - Commas are not allowed
• 256*e8- * not allowed
2. Character Constants
• Any character enclosed with in single quotes (‘) is called
character constant.
• A character constant:
• May be a single alphabet, single digit or single special
character placed with in single quotes.
• Has a maximum length of 1 character.
Here are some examples,
• ‘C’
• ‘c’
• ‘:’
• ‘*’
3. String Constants
• A string constant is a sequence of alphanumeric characters enclosed in
double quotes whose maximum length is 255 characters.
• Following are the examples of valid string constants:
• “My name is Krishna”
• “Bible”
• “Salary is 18000.00”
• Following are the examples of invalid string constants:
• My name is Krishna - Character are not enclosed in double quotation
marks.
• “My name is Krishna - Closing double quotation mark is missing.
• ‘My name is Krishna’ - Characters are not enclosed in double quotation
marks
b. Reserve Words/Keywords
• In C language , some words are reserved to do specific
tasks intended for them and are called Keywords or
Reserve words
.
C. Delimiters
• This is symbol that has syntactic meaning and has got
significance. These will not specify any operation to result
in a value.
Symbol Name Meaning
# Hash Pre-processor directive
, comma Variable delimiter to separate variable
: colon label delimiter
; Semicolon statement delimiter
( ) parenthesis used for expressions
{ } curly braces used for blocking of statements
[ ] square braces used along with arrays
D.Variables / Identifiers
• These are the names of the objects, whose values can be
changed during the program execution. Variables are named
with description that transmits the value it holds.
• A quantity of an item, which can be change its value during
the execution of program is called variable. It is also known
as Identifier.
• Rules for naming a variable:-
• It can be of letters, digits and underscore( _ )
• First letter should be a letter or an underscore, but it should
not be a digit.
• Reserve words cannot be used as variable names.
• Example: basic, root, rate, roll-no etc are valid names.
• Declaration of variables:
Syntax type Variable list
int i, j i, j are declared as integers
float salary salary is declared ad floating
point variable
Char gender Gender is declared as character
variable
OPERATORS
• operator is a symbol that tells the compiler to perform specific
mathematical or logical functions.
Following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operator
• Increment and decrement operators
• Conditional Operators
• Special Operators
Arithmetic Operators
• arithmetic operator performs mathematical operations such as
addition, subtraction, multiplication, division etc on
numerical values (constants and variables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)
Example 1: Arithmetic Operators
• // Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d n",c); a+b = 13
c = a-b;
printf("a-b = %d n",c); a-b = 5
c = a*b;
printf("a*b = %d n",c); a*b=36
c = a/b;
printf("a/b = %d n",c); a/b=2
c = a%b;
printf("Remainder when a divided by b = %d n",c); c=1
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
2.Increment and Decrement Operators
• C programming has two operators increment ++ and
decrement -- to change the value of an operand (constant
or variable) by 1.
• Increment ++ increases the value by 1 whereas
decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate
on a single operand.
Example :Increment and Decrement Operators
• // prefix operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d n", ++a); ++a = 11
printf("--b = %d n", --b); --b = 99
printf("++c = %f n", ++c); ++c = 11.500000
printf("--d = %f n", --d); --d = 99.500000
return 0;
}
Example prefix and post fix
a = 5
++a; // a becomes 6
a++; // a becomes 7
--a; // a becomes 6
a--; // a becomes 5
3.Assignment Operators
• assignment operator is used for assigning a value to a
variable. The most common assignment operator is =
Operator Example Same as
= a = b a = b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Example 3: Assignment Operators
• // Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c; c = a; // c is 5
printf("c = %dn", c); c = 5
c += a; // c is 10
printf("c = %dn", c); c = 10
c -= a; // c is 5
printf("c = %dn", c); C=5
c *= a; // c is 25
printf("c = %dn", c); c=25
c /= a; // c is 5
printf("c = %dn", c); c=1
c %= a; // c = 0
printf("c = %dn", c); c=0
return 0;
}
4.Relational Operators
• A relational operator checks the relationship between two operands. If the relation
is true, it returns 1; if the relation is false, it returns value 0.
• Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
Example 4: Relational Operators
// Working of relational operators
#include <stdio.h>
int main()
{ int a = 5, b = 5, c = 10;
printf("%d == %d is %d n", a, b, a == b); 5 == 5 is 1
printf("%d == %d is %d n", a, c, a == c); 5 == 10 is 0
printf("%d > %d is %d n", a, b, a > b); 5 > 5 is 0
printf("%d > %d is %d n", a, c, a > c); 5 > 10 is 0
printf("%d < %d is %d n", a, b, a < b); 5 < 5 is 0
printf("%d < %d is %d n", a, c, a < c); 5 < 10 is 1
printf("%d != %d is %d n", a, b, a != b); 5 != 5 is 0
printf("%d != %d is %d n", a, c, a != c); 5 != 10 is 1
printf("%d >= %d is %d n", a, b, a >= b); 5 >= 5 is 1
printf("%d >= %d is %d n", a, c, a >= c); 5 >= 10 is 0
printf("%d <= %d is %d n", a, b, a <= b); 5 <= 5 is 1
printf("%d <= %d is %d n", a, c, a <= c); 5 <= 10 is 1
return 0;
}
5.Logical Operators
• expression containing logical operator returns either 0 or 1 depending
upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming.
Operator Meaning Example
&&
Logical AND. True only if all
operands are true
If c = 5 and d = 2 then,
expression ((c==5) && (d>5))
equals to0.
||
Logical OR. True only if
either one operand is true
If c = 5 and d = 2 then,
expression ((c==5) || (d>5))
equals to 1.
!
Logical NOT. True only if the
operand is 0
If c = 5 then, expression !(c==5)
equals to 0.
Example 5: Logical Operators
• // Working of logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d n", result);
result = !(a != b);
printf("!(a != b) is %d n", result);
result = !(a == b);
printf("!(a == b) is %d n", result);
return 0;
}
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Explanation of logical operator program
• (a == b) && (c > b) evaluates to 1 because both
operands (a == b) and (c > b) is 1 (true).
• (a == b) && (c < b) evaluates to 0 because operand (c < b) is
0 (false).
• (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
• (a != b) || (c < b) evaluates to 0 because both
operand (a != b) and (c < b) are 0 (false).
• !(a != b) evaluates to 1 because operand (a != b) is 0 (false).
Hence, !(a != b) is 1 (true).
• !(a == b) evaluates to 0 because (a == b) is 1 (true).
Hence, !(a == b) is 0 (false).
6.Bitwise Operators
• During computation, mathematical operations like: addition, subtraction,
multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.
• Bitwise operators are used in C programming to perform bit-level operations.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
INTRODUCTION TO C PROGRAMMING in basic c language
• Bitwise operator works on bits and perform bit-by-bit
operation. The truth tables for &, |, and ^ is as follows −
p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
• Assume A = 60 and B = 13 in binary format, they will be
as follows −
• A = 0011 1100
• B = 0000 1101
• -----------------
• A&B = 0000 1100 A*B=
• A|B = 0011 1101 A+B=
• A^B = 0011 0001
• ~A = 1100 0011
1 2 4 8 16 32 64 128 256 512 1024 2048
Example
#include <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %dn", c ); Line 1 - Value of c is 12
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %dn", c ); Line 2 - Value of c is 61
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %dn", c ); Line 3 - Value of c is 49
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %dn", c ); Line 4 - Value of c is -61
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %dn", c ); Line 5 - Value of c is 240
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %dn", c ); Line 6 - Value of c is 15
}
7.Conditional Operator in C
• The conditional operator is also known as a ternary operator.
• The conditional statements are the decision-making
statements that depend upon the output of the expression.
• As a conditional operator works on three operands, so it is
also known as the ternary operator.
• The operands may be an expression, constants, or variables.
• It starts with a condition, hence it is called a conditional
operator.
• Syntax of Conditional Operator in C:
expression1 ? expression2 : expression3;
or for simplicity, we write it as
condition ? true-statement : false-statement;
The expression1 is evaluated, it is treated as a logical
condition.
If the result is non-zero then expression2 will be evaluated
otherwise expression3 will be evaluated.
The value after evaluation of expression2 or expression3
is the final result.
• The conditional operator in C works similar to the conditional
control statement if-else.
• Hence every code written using conditional operator can also be
written using if-else.
• When compared with if-else, conditional operator performance is
high.
if(expression1)
{
expression2;
}
else
{
expression3;
}
Write a C program to find the maximum in the given two
numbers using the conditional operator
#include<stdio.h>
int main()
{
float num1, num2, max;
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
max = (num1 > num2) ? num1 : num2;
printf("Maximum of %.2f and %.2f = %.2f", num1, num2,max);
return 0;
} max=(34>45)?34: 45;
8.SPECIAL OPERATORS IN C
Operator Description Example
sizeof Returns the size of
an variable
sizeof(x) return size of
the variable x
& Returns the address
of an variable
&x ; return address of the
variable x
* Pointer to a variable *x ; will be pointer to a
variable x
EXAMPLE PROGRAM FOR & AND *
OPERATORS IN C
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50; /* address of q is assigned to ptr */
ptr = &q; /* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
} OUTPUT: 50
EXAMPLE PROGRAM FOR SIZEOF() OPERATOR IN C
• sizeof() operator is used to find the memory space
allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a; char b; float c; double d;
printf("Storage size for int data type:%d n",sizeof(a));
printf("Storage size for char data type:%d n",sizeof(b));
printf("Storage size for float data type:%d n",sizeof(c));
printf("Storage size for double data type:%dn",sizeof(d));
return 0;
}
OUTPUT:
Storage size for int data type:2
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
INTRODUCTION TO C PROGRAMMING in basic c language
• Expression represent data item such as variables, constants
and are interconnected with operators as per the syntax of
the language.
• Expression is evaluated using assignment operator.
Syntax: variable = expression;
Description –any ‘C’ valid variable and expression
Example--- x=a*b-c;
Blank space is around an operator is optional and adds only
to improve readability of the program.
Expressions
• The variables that are used in an expression must be
declared at the declaration part of the program.
Algebric Expression C Expression
a+bX c a+b*c
ax2+bx+c a*x*x+b*x+c
(4ac/2a) (4*a*c)/(2*a)
Operator precedence
Rules for evaluation of expression
• Evaluate the sub expression from left to right if
parenthesized.
• Arithmetic expression from left to right using the rules of
precedence.
• Highest precedence is given to the expression with in
parenthesis
• Apply the associative rule,if more operators of the same
precedence occurs.
• Evaluate the inner most sub expression if the parenthesis are
nested.
INTRODUCTION TO C PROGRAMMING in basic c language
Type Conversion
• Type Conversion refers the process of changing an entity
of one data type into another.
• Mix the types of values in your arithmetic expression.
• To take advantage of certain features of one data type to
another.
Example:
• Integers can be stored in a more compact format and later
converted to a different format enabling operations not
previously possible.
Two types of type conversion
i.Implicit ,ii.Explicit
• Implicit-Compulsory conversion
• It’s an automatic type conversion ,mixed type expression
data of one or more subtypes can be converted to a super
type as needed at run time, so that the program will run
correctly.
• Explicit Conversion: Type Casting
• Explicit Conversion can be made to convert one data type to
another by forcefully and it is different from the implicit
conversion.
Syntax:var2=(datatype)var2;
int a =20; float(a);
float(a) will contain 20.000000
• C language 2 types of input/output statements are available.
• I/O operations carried out through function calls.
Input and Output operations
I/O functions
Formatted I/O
Unformatted I/O
INPUT OUTPUT
Getc() Putc()
Getchar() Putchaar()
Gets() Puts()
Getche()
Getch()
INPUT OUTPUT
Scanf() Printf()
Fscanf() Fprintf()
• getchar() Function
The getchar() function reads character type data form the input.
The getchar() function reads one character at a time till the user
presses the enter key.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
char c;
printf("Enter a character : ");
c = getchar();
printf("n Entered character : %c ", c);
return 0; } Enter a character : y
Entered character : y
• getch() Function
The getch() function reads the alphanumeric character input from
the user. But, that the entered character will not be displayed.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
printf("nHello, press any alphanumeric character to exit ");
getch();
return 0;
} Hello, press any alphanumeric character to exit
• getche() Function : getche() function reads the
alphanumeric character from the user input.
• Here, character you entered will be echoed to the user
until he/she presses any key.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
printf("nHello, press any alphanumeric character or symbol
to exit n ");
getche(); return 0; } Hello, press any alphanumeric
character or symbol to exit J
• putchar() Function
putchar() function prints only one character at a time.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
char c = 'K';
putchar(c);
return 0; } Note: Here, variable c is assigned to a character
'K'. The variable c is displayed by the putchar(). Use
Single quotation mark ' ' for a character.
• putch() Function
• The putch() function prints any alphanumeric character.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
char c;
printf("Press any key to continuen ");
c = getch();
printf("input : ");
putch(c);
return 0; } Press any key to continue ; input : d
• Note: The getch() function will not echo a character. The
putch() function displays the input you pressed.
• puts() Function
• The puts() function prints the charcater array or string on the console. The
puts() function is similar to printf() function, but we cannot print other than
characters using puts() function.
#include <stdio.h> //header file section
#include <conio.h>
int main()
{
char c[25];
printf("Enter your Name : ");
gets(c);
puts(c);
return 0;
}
Enter your Name: john
john
Decision Making and
Branching
• Decision making structures require that the programmer
specifies one or more conditions to be evaluated or tested
by the program, along with a statement or statements to be
executed.
• if the condition is determined to be true, and optionally,
other statements to be executed if the condition is
determined to be false.
•the general form of a typical decision making structure found in
most of the programming language
C programming
language assumes
any non-zero and non-
null values as true,
and if it is
either zero or null,
then it is assumed
as false value.
S.No. Statement & Description
1
if statement An if statement consists of a boolean expression
followed by one or more statements.
2
if...else statement An if statement can be followed by an
optional else statement, which executes when the Boolean
expression is false.
3
nested if statements You can use one if or else if statement inside
another if or else if statement(s).
4
switch statement A switch statement allows a variable to be tested
for equality against a list of values.
5
nested switch statements You can use one switch statement inside
another switch statement(s).
C - if statement
• if statement consists of a Boolean expression followed by one
or more statements.
• Syntax;
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */ }
• If the Boolean expression evaluates to true, then the block of
code inside the 'if' statement will be executed.
• If the Boolean expression evaluates to false, then the first set
of code after the end of the 'if' statement (after the closing
curly brace) will be executed.
Example
#include <stdio.h>
int main ()
{
int a = 10;
if( a < 20 )
{
printf("a is less than 20n" );
}
printf("value of a is : %dn", a);
return 0;
} OUTPUT: // a is less than 20;
value of a is : 10
C - if...else statement
• if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.
Syntax:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
• If the Boolean expression evaluates to true, then the if block will be
executed, otherwise, the else block will be executed.
• C programming language assumes any non-zero and non-null values as true,
and if it is either zero or null, then it is assumed as false value.
Example
#include <stdio.h>
int main ()
{
int a = 100; /* check the boolean condition */
if( a < 20 )
{
printf("a is less than 20n" );
}
else
{
printf("a is not less than 20n" );
}
printf("value of a is : %dn", a);
return 0;
} a is not less than 20; value of a is : 100
If...else if...else Statement
• An if statement can be followed by an optional else
if...else statement, which is very useful to test various
conditions using single if...else if statement.
• When using if...else if..else statements, there are few points
to keep in mind −
• An if can have zero or one else's and it must come after any
else if's.
• An if can have zero to many else if's and they must come
before the else.
• Once an else if succeeds, none of the remaining else if's or
else's will be tested.
• Syntax
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example:
#include <stdio.h>
int main ()
{
int a = 30;
if( a == 10 ) { printf("Value of a is 10n" ); }
else if( a == 20 ) { printf("Value of a is 20n" ); }
else if( a == 30 ) { printf("Value of a is 30n" ); }
else { printf("None of the values is matchingn" ); }
printf("Exact value of a is: %dn", a );
return 0;
} None of the values is matching
Exact value of a is: 30
nested if statements
• It is always legal in C programming to nest if-else
statements, which means you can use one if or else if
statement inside another if or else if statement.
Syntax:
if( boolean_expression 1)
{ /* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{ /* Executes when the boolean expression 2 is true */ }
}
#include <stdio.h>
int main ()
{
int a = 100; int b = 200;
if( a == 100 )
{
if( b == 200 )
{
printf("Value of a is 100 and b is 200n" );
}
}
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
C - switch statement
• switch statement allows a variable to be tested for equality against a list of
values.
• Each value is called a case, and the variable being switched on is checked for
each switch case.
• Syntax
switch(expression)
{
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
default :
statement(s);
}
• The following rules apply to a switch statement :-
• The expression used in a switch statement must have an integral or enumerated
type, or be of a class type in which the class has a single conversion function to
an integral or enumerated type.
• You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable
in the switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.
Flow Diagram
#include <stdio.h>
int main ()
{
char grade = 'B';
switch(grade)
{
case 'A' : printf("Excellent!n" ); break;
case 'B' :
case 'C' : printf("Well donen" ); break;
case 'D' : printf("You passedn" ); break;
case 'F' : printf("Better try againn" ); break;
default : printf("Invalid graden" ); }
printf("Your grade is %cn", grade );
return 0;
} Well done Your grade is B
nested switch statements
• It is possible to have a switch as a part of the statement
sequence of an outer switch.
• Even if the case constants of the inner and outer switch
contain common values, no conflicts will arise.
Syntax
switch(ch1)
{
case 'A': printf("This A is part of outer switch" );
switch(ch2)
{ case 'A': printf("This A is part of inner switch" );
break; case 'B': }
break; case 'B‘:}
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;
switch(a)
{
case 100:
printf("This is part of outer switchn", a );
switch(b)
{
case 200: printf("This is part of inner switchn", a ); } }
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
Looping statements
• A block of code needs to be executed several number of
times. In general, statements are executed sequentially.
• The first statement in a function is executed first, followed
by the second, and so on.
• Programming languages provide various control structures
that allow for more complicated execution paths.
• A loop statement allows us to execute a statement or
group of statements multiple times.
INTRODUCTION TO C PROGRAMMING in basic c language
C programming language provides the following
types of loops to handle looping requirements.
S.No. Loop Type & Description
1
for loop Executes a sequence of statements multiple times
and abbreviates the code that manages the loop variable.
2
while loop Repeats a statement or group of statements while
a given condition is true. It tests the condition before
executing the loop body.
3
do...while loop It is more like a while statement, except that
it tests the condition at the end of the loop body.
4
nested loops You can use one or more loops inside any other
while, for, or do..while loop.
FOR LOOP
• for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific
number of times.
Syntax
for ( init; condition; increment )
{ statement(s); }
INTRODUCTION TO C PROGRAMMING in basic c language
Example
#include <stdio.h>
int main ()
{ int a; /* for loop execution */
for( a = 10; a < 20; a = a + 1 )
{
printf("value of a: %dn", a);
}
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
WHILE LOOP
• while loop in C programming repeatedly executes a target
statement as long as a given condition is true.
Syntax:
while(condition)
{
statement(s);
}
•statement(s) may be a single
statement or a block of statements.
•The condition may be any expression,
and true is any nonzero value.
•The loop iterates while the condition is
true.
•When the condition becomes false, the
program control passes to the line
immediately following the loop.
Flow Diagram
#include <stdio.h>
int main ()
{
int a = 10; /* local variable definition */
while( a < 20 ) /* while loop execution */
{
printf("value of a: %dn", a); a++;
}
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do while
• for and while loops, which test the loop condition at the
top of the loop, the do...while loop in C programming
checks its condition at the bottom of the loop.
• A do...while loop is similar to a while loop, except the
fact that it is guaranteed to execute at least one time.
Syntax
do
{ statement(s); }
while( condition );
• the conditional expression appears at the end of the loop,
so the statement(s) in the loop executes once before the
condition is tested.
• If the condition is true, the flow of control jumps back up
to do, and the statement(s) in the loop executes again.
• This process repeats until the given condition becomes
false.
INTRODUCTION TO C PROGRAMMING in basic c language
#include <stdio.h>
int main ()
{
int a = 10;
do
{
printf("value of a: %dn", a);
a = a + 1;
}
while( a < 20 );
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
S.
No
For loop While loop Do while loop
1.
Syntax: For(initialization;
condition;updating), { .
Statements; }
Syntax: While(condition), {
. Statements; . }
Syntax: Do { . Statements; }
While(condition);
2.
It is known as entry
controlled loop
It is known as entry
controlled loop.
It is known as exit controlled
loop.
3.
If the condition is not true
first time than control will
never enter in a loop
If the condition is not true
first time than control will
never enter in a loop.
Even if the condition is not true
for the first time the control
will enter in a loop.
4.
There is no semicolon;
after the condition in the
syntax of the for loop.
There is no semicolon;
after the condition in the
syntax of the while loop.
There is semicolon; after the
condition in the syntax of the
do while loop.
5.
Initialization and updating
is the part of the syntax.
Initialization and updating
is not the part of the syntax.
Initialization and updating is
not the part of the syntax
Loop Control Statements
• Loop control statements change execution from its normal
sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.
S.No. Control Statement & Description
1
break statement Terminates the loop or switch statement and
transfers execution to the statement immediately following the
loop or switch.
2
continue statement Causes the loop to skip the remainder of its
body and immediately retest its condition prior to reiterating.
3 go to statement Transfers control to the labeled statement.
Break statement
• a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes
at the next statement following the loop.
• It can be used to terminate a case in the switch statement
• If you are using nested loops, the break statement will
stop the execution of the innermost loop and start
executing the next line of code after the block.
Syntax
break;
INTRODUCTION TO C PROGRAMMING in basic c language
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %dn", a);
a++;
if( a < 15)
{
break;
} }
return 0;
}
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
CONTINUE STATEMENT
• continue statement in C programming works somewhat
like the break statement. Instead of forcing termination, it
forces the next iteration of the loop to take place, skipping
any code in between.
• for loop, continue statement causes the conditional test
and increment portions of the loop to execute.
• For the while and do...while loops, continue statement
causes the program control to pass to the conditional tests.
Syntax
continue;
INTRODUCTION TO C PROGRAMMING in basic c language
#include <stdio.h>
int main ()
{int a = 10;
do {
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %dn", a); a++; }
while( a < 20 );
return 0; }
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement
• goto statement in C programming provides an
unconditional jump from the 'goto' to a labeled statement
in the same function.
• NOTE − Use of goto statement is highly discouraged in
any programming language because it makes difficult to
trace the control flow of a program, making the program
hard to understand and hard to modify. Any program that
uses a goto can be rewritten to avoid them.
Syntax
goto label;
.. .
label: statement;
INTRODUCTION TO C PROGRAMMING in basic c language
#include <stdio.h>
int main ()
{
int a = 10;
LOOP: do
{
if( a == 15)
{
a = a + 1;
goto LOOP;
}
printf("value of a: %dn", a); a++;
}
while( a < 20 );
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Infinite Loop
• A loop becomes an infinite loop if a condition never
becomes false.
• The for loop is traditionally used for this purpose. Since
none of the three expressions that form the 'for' loop are
required, you can make an endless loop by leaving the
conditional expression empty.
• For()
#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.n");
}
return 0;
}
the conditional expression is absent, it is assumed to be true. You may have
an initialization and increment expression, but C programmers more
commonly use the for(;;) construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
Ad

More Related Content

What's hot (20)

Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
Atul Sehdev
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
R.K.College of engg & Tech
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
C++
C++C++
C++
Shyam Khant
 
Bitwise Operators in C
Bitwise Operators in CBitwise Operators in C
Bitwise Operators in C
yndaravind
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
Ashim Lamichhane
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Tokens_C
Tokens_CTokens_C
Tokens_C
Prabhu Govind
 
C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17
manjurkts
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
Maria Stella Solon
 
Secrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory ManagementSecrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory Management
Abhishek Sur
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Pointer arithmetic in c
Pointer arithmetic in c Pointer arithmetic in c
Pointer arithmetic in c
sangrampatil81
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
Srinivas Narasegouda
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
samt7
 
introduction to c language
 introduction to c language introduction to c language
introduction to c language
Rai University
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
Atul Sehdev
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
Bitwise Operators in C
Bitwise Operators in CBitwise Operators in C
Bitwise Operators in C
yndaravind
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17
manjurkts
 
Secrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory ManagementSecrets of .NET Assemblies and Memory Management
Secrets of .NET Assemblies and Memory Management
Abhishek Sur
 
Pointer arithmetic in c
Pointer arithmetic in c Pointer arithmetic in c
Pointer arithmetic in c
sangrampatil81
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
Srinivas Narasegouda
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
samt7
 
introduction to c language
 introduction to c language introduction to c language
introduction to c language
Rai University
 

Similar to INTRODUCTION TO C PROGRAMMING in basic c language (20)

Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
Kathmandu University
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
Malikireddy Bramhananda Reddy
 
C language unit-1
C language unit-1C language unit-1
C language unit-1
Malikireddy Bramhananda Reddy
 
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDYC LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Mahfuzur Rahman
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
Mangala R
 
Unit ii
Unit   iiUnit   ii
Unit ii
sathisaran
 
c++
 c++  c++
c++
SindhuVelmukull
 
Best_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptxBest_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptx
nilaythakkar7
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
Ronaldo Aditya
 
introductiontothecomputerprogramming.pptx
introductiontothecomputerprogramming.pptxintroductiontothecomputerprogramming.pptx
introductiontothecomputerprogramming.pptx
beenish75
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
Gilbert NZABONITEGEKA
 
Basics of C Prog Lang.pdf
Basics of C Prog Lang.pdfBasics of C Prog Lang.pdf
Basics of C Prog Lang.pdf
KalighatOkira
 
Object Oriented Programming Using C++.pptx
Object Oriented Programming  Using C++.pptxObject Oriented Programming  Using C++.pptx
Object Oriented Programming Using C++.pptx
bscit6
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
 
Module_1_Introduction-to-Problem-Solving.pdf
Module_1_Introduction-to-Problem-Solving.pdfModule_1_Introduction-to-Problem-Solving.pdf
Module_1_Introduction-to-Problem-Solving.pdf
MaheshKini3
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
Dr. SURBHI SAROHA
 
EC2311-Data Structures and C Programming
EC2311-Data Structures and C ProgrammingEC2311-Data Structures and C Programming
EC2311-Data Structures and C Programming
Padma Priya
 
C PROGRAMMING LANGUAGE.pptx
 C PROGRAMMING LANGUAGE.pptx C PROGRAMMING LANGUAGE.pptx
C PROGRAMMING LANGUAGE.pptx
AnshSrivastava48
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
Mangala R
 
Best_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptxBest_of_438343817-A-PPT-on-C-language.pptx
Best_of_438343817-A-PPT-on-C-language.pptx
nilaythakkar7
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
Ronaldo Aditya
 
introductiontothecomputerprogramming.pptx
introductiontothecomputerprogramming.pptxintroductiontothecomputerprogramming.pptx
introductiontothecomputerprogramming.pptx
beenish75
 
Basics of C Prog Lang.pdf
Basics of C Prog Lang.pdfBasics of C Prog Lang.pdf
Basics of C Prog Lang.pdf
KalighatOkira
 
Object Oriented Programming Using C++.pptx
Object Oriented Programming  Using C++.pptxObject Oriented Programming  Using C++.pptx
Object Oriented Programming Using C++.pptx
bscit6
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
 
Module_1_Introduction-to-Problem-Solving.pdf
Module_1_Introduction-to-Problem-Solving.pdfModule_1_Introduction-to-Problem-Solving.pdf
Module_1_Introduction-to-Problem-Solving.pdf
MaheshKini3
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
Dr. SURBHI SAROHA
 
EC2311-Data Structures and C Programming
EC2311-Data Structures and C ProgrammingEC2311-Data Structures and C Programming
EC2311-Data Structures and C Programming
Padma Priya
 
C PROGRAMMING LANGUAGE.pptx
 C PROGRAMMING LANGUAGE.pptx C PROGRAMMING LANGUAGE.pptx
C PROGRAMMING LANGUAGE.pptx
AnshSrivastava48
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
Ad

More from GOKULKANNANMMECLECTC (6)

GAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GAME THEORY AND MONTE CARLO SEARCH SPACE TREEGAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GOKULKANNANMMECLECTC
 
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASICINTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
GOKULKANNANMMECLECTC
 
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptxtcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
GOKULKANNANMMECLECTC
 
Tcp congestion control topic in high speed network
Tcp congestion control topic  in high speed networkTcp congestion control topic  in high speed network
Tcp congestion control topic in high speed network
GOKULKANNANMMECLECTC
 
KandR_TCP (1).ppt notes for congestion control
KandR_TCP (1).ppt    notes for congestion controlKandR_TCP (1).ppt    notes for congestion control
KandR_TCP (1).ppt notes for congestion control
GOKULKANNANMMECLECTC
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
GAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GAME THEORY AND MONTE CARLO SEARCH SPACE TREEGAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GOKULKANNANMMECLECTC
 
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASICINTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
GOKULKANNANMMECLECTC
 
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptxtcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
GOKULKANNANMMECLECTC
 
Tcp congestion control topic in high speed network
Tcp congestion control topic  in high speed networkTcp congestion control topic  in high speed network
Tcp congestion control topic in high speed network
GOKULKANNANMMECLECTC
 
KandR_TCP (1).ppt notes for congestion control
KandR_TCP (1).ppt    notes for congestion controlKandR_TCP (1).ppt    notes for congestion control
KandR_TCP (1).ppt notes for congestion control
GOKULKANNANMMECLECTC
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
Ad

Recently uploaded (20)

6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Uses of drones in civil construction.pdf
Uses of drones in civil construction.pdfUses of drones in civil construction.pdf
Uses of drones in civil construction.pdf
surajsen1729
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Journal of Soft Computing in Civil Engineering
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation RateModeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Journal of Soft Computing in Civil Engineering
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Uses of drones in civil construction.pdf
Uses of drones in civil construction.pdfUses of drones in civil construction.pdf
Uses of drones in civil construction.pdf
surajsen1729
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 

INTRODUCTION TO C PROGRAMMING in basic c language

  • 1. UNIT-II-C PROGRAMMING BASICS Introduction to C programming – Header files – Structure of a C program – compilation and linking processes – Constants, Variables – Data Types – Expressions – operators – Input and Output operations – Decision Making and Branching – Looping statements- Programming Examples
  • 2. • ‘C’ is high level language and is the upgraded version of another language (Basic Combined Program Language). • C language was designed at Bell laboratories in the early 1970’s by Dennis Ritchie. • Dennis Ritchie is known as the founder of the c language. • C being popular in the modern computer world can be used in Mathematical Scientific, Engineering and Commercial applications. • The most popular Operating system UNIX is written in C language. • This language also has the features of low level languages and hence called as “System Programming Language”
  • 3. Language Year Developed By Algol 1960 International Group BCPL 1967 Martin Richard B 1970 Ken Thompson Traditional C 1972 Dennis Ritchie K & R C 1978 Kernighan & Dennis Ritchie ANSI C 1989 ANSI Committee ANSI/ISO C 1990 ISO Committee
  • 4. Features of C language • Simple, versatile, general purpose language • It has rich set of Operators • Program execution are fast and efficient • Can easily manipulates with bits, bytes and addresses • Varieties of data types are available • Separate compilation of functions is possible and such functions can be called by any C program • Block- structured language • Can be applied in System programming areas like operating systems, compilers & Interpreters, Assembles, Text Editors, Print Spoolers, Network Drivers, Modern Programs, Data Bases, Language Interpreters, Utilities etc.
  • 5. Structure of c program
  • 6. Header files • A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files. • There are two types of header files: • The files that the programmer writes . • The files that comes with your compiler.
  • 7. Sr.No. Header Files & Description 1 stdio.h Input/Output functions 2 conio.h Console Input/Output functions 3 stdlib.h General utility functions 4 math.h Mathematics functions 5 string.h String functions 6 ctype.h Character handling functions 7 time.h Date and time functions 8 float.h Limits of float types 9 limits.h Size of basic types 10 wctype.h Functions to determine the type contained in wide character data.
  • 8. Compilation and linking processes • Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. • This step doesn't create anything the user can actually run. • Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. • For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name <filename>.o or <filename>.obj (the extension will depend on your compiler). • Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use.
  • 9. • Linking refers to the creation of a single executable file from multiple object files. • In this step, it is common that the linker will complain about undefined functions (commonly, main itself). • During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. • If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. • The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.
  • 10. • there are separate compilation and linking steps. • First, it's probably easier to implement things that way. • The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. • Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation“. • it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker.
  • 11. • Finally, this makes it simple to implement libraries of pre- compiled code: just create object files and link them just like any other object file. • (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".). • To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled.
  • 12. • Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. • Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. • Linking errors usually have to do with missing or multiple definitions. • If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.
  • 13. Data types in C • A keyword that is used for creating variables for storing single and multiple values is called data types • Creating a variable for storing single and multiple values in a program as part of performing one operation. • To perform any operation first we must store values. • To store values we must allocate memory. • Here we need to provide the information above the number of bytes and type of memory that must be allocated to store a value.
  • 14. • To specify the number of bytes and memory types to the compiler and operating system. • we must use some set of keywords. These sets of keywords are collectively called data types. • Hence we can say data type is used for allocating memory for storing value in a program by specifying the required numbers of bytes and memory type.
  • 17. Basic Data Types • There are four basic data types in C language. • character data • Integer data • floating point data • double data types. a. Character data: • Any character of the ASCII character set can be considered as a character data types and its maximum size can be 1 byte or 8 byte long. • ‘Char’ is the keyword used to represent character data type in C. • Char - a single byte size, capable of holding one character.
  • 18. • b. Integer data: The keyword ‘int’ stands for the integer data type in C and its size is either 16 or 32 bits. • The integer data type can again be classified as 1. Long int - long integer with more digits 2. Short int - short integer with fewer digits. 3. Unsigned int - Unsigned integer 4. Unsigned short int – Unsigned short integer 5. Unsigned long int – Unsigned long integer • As above, the qualifiers like short, long, signed or unsigned can be applied to basic data types to derive new data types. • int - an Integer with the natural size of the host machine.
  • 19. • c. Floating point data: - The numbers which are stored in floating point representation with mantissa and exponent are called floating point (real) numbers. • These numbers can be declared as ‘float’ in C. • float – Single – precision floating point number value. • d. Double data : - Double is a keyword in C to represent double precision floating point numbers. • double - Double – precision floating point number value.
  • 20. • Data Kinds in C • Various data kinds that can be included in any C program can fall in to the following. • a. Constants/Literals • b. Reserve Words Keywords • c. Delimeters • d. Variables/Identifiers • a. Constans/Literals: Constants are those, which do not change, during the execution of the program.
  • 21. • Constants may be categorized in to • Numeric Constants • Character Constants • String Constants 1. Numeric Constants • Numeric constants, as the name itself indicates, are those which consist of numerals, an optional sign and an optional period. They are further divided into two types: (a) Integer Constants (b) Real Constants
  • 22. • a. Integer Constants: A whole number is an integer constant Integer constants do not have a decimal point. These are further divided into three types depending on the number systems they belong to. i. Decimal integer constants ii. Octal integer constants iii. Hexadecimal integer constants
  • 23. Decimal Integer constant is characterized by the following properties. It is a sequence of one or more digits ([0…9], the symbols of decimal number system). • It may have an optional + or – sign. In the absence of sign, the constant is assumed to be positive. • Commas and blank spaces are not permitted. • It should not have a period as part of it. • examples of valid decimal integer constants: • 456 • -123 • examples of invalid decimal integer constants: • 4.56 - Decimal point is not permissible • 1,23 - Commas are not permitted
  • 24. • ii. An octal integer constant is characterized by the following properties • It is a sequence of one or more digits ([0…7], symbols of octal number system). • It may have an optional + or – sign. In the absence of sign, the constant is assumed to be positive. • It should start with the digit 0. • Commas and blank spaces are not permitted. • It should not have a period as part of it.
  • 25. Some examples of valid octal integer constants: • 0456 • -0123 • +0123 Some examples of invalid octal integer constants: • 04.56 - Decimal point is not permissible • 04,56 - Commas are not permitted • x34 - x is not permissible symbol • 568 - 8 is not a permissible symbol
  • 26. • iii. An hexadecimal integer constant is characterized by the following properties • It is a sequence of one or more symbols ([0…9][A….Z], the symbols of Hexadecimal number system). • It may have an optional + or - sign. In the absence of sign, the constant is assumed to be positive. • It should start with the symbols 0X or 0x. • Commas and blank spaces are not permitted. • It should not have a period as part of it.
  • 27. Some examples of valid hexadecimal integer constants: • 0x456 • -0x123 • 0x56A • 0XB78 Some examples of invalid hexadecimal integer constants: • 0x4.56 - Decimal point is not permissible • 0x4,56 - Commas are not permitted.
  • 28. • b. Real Constants • The real constants also known as floating point constants are written in two forms: (i) Fractional form, (ii) Exponential form. (i) Fractional form: The real constants in Fractional form are characterized by the following characteristics: • Must have at least one digit. • Must have a decimal point. • May be positive or negative and in the absence of sign taken as positive. • Must not contain blanks or commas in between digits. • May be represented in exponential form, if the value is too higher or too low.
  • 29. Some examples of valid real constants: • 456.78 • -123.56 Some examples of invalid real constants: • 4.56 - Blank spaces are not permitted • 4,56 - Commas are not permitted • 456 - Decimal point missing
  • 30. ii. Exponential Form • The exponential form offers a convenient way for writing very large and small real constant. • For example, 56000000.00, which can be written as 0.56*, 108 is written as 0.56E8 or 0.56e8 in exponential form. • 0.000000234, which can be written as 0.234 * 10-6 is written as 0.234E-6 or 0.234e-6 in exponential form. • The letter E or e stand for exponential form.
  • 31. • A real constant expressed in exponential form has two parts: • (i) Mantissa part, • (ii) Exponent part. • Mantissa is the part of the real constant to the left of E or e, and the Exponent of a real constant is to the right of E or e. • Mantissa and Exponent of the above two number Mantissa Exponent Mantissa Exponent 0.56 E 8 0.234 E -6 In the above examples, 0.56 and 0.234 are the mantissa parts of the first and second numbers, respectively, and 8 and -6 are the exponent parts of the first and second number, respectively.
  • 32. • The real constants in exponential form and characterized by the following characteristics: • The mantissa must have at least one digit. • The mantissa is followed by the letter E or e and the exponent. • The exponent must have at least one digit and must be an integer. • A sign for the exponent is optional Some examples of valid real constants: • 3E4 • 23e-6 • 0.34E6
  • 33. Some examples of invalid real constants: • 23E - No digit specified for exponent • 23e4.5 - Exponent should not be a fraction • 23,4e5 - Commas are not allowed • 256*e8- * not allowed
  • 34. 2. Character Constants • Any character enclosed with in single quotes (‘) is called character constant. • A character constant: • May be a single alphabet, single digit or single special character placed with in single quotes. • Has a maximum length of 1 character. Here are some examples, • ‘C’ • ‘c’ • ‘:’ • ‘*’
  • 35. 3. String Constants • A string constant is a sequence of alphanumeric characters enclosed in double quotes whose maximum length is 255 characters. • Following are the examples of valid string constants: • “My name is Krishna” • “Bible” • “Salary is 18000.00” • Following are the examples of invalid string constants: • My name is Krishna - Character are not enclosed in double quotation marks. • “My name is Krishna - Closing double quotation mark is missing. • ‘My name is Krishna’ - Characters are not enclosed in double quotation marks
  • 36. b. Reserve Words/Keywords • In C language , some words are reserved to do specific tasks intended for them and are called Keywords or Reserve words .
  • 37. C. Delimiters • This is symbol that has syntactic meaning and has got significance. These will not specify any operation to result in a value. Symbol Name Meaning # Hash Pre-processor directive , comma Variable delimiter to separate variable : colon label delimiter ; Semicolon statement delimiter ( ) parenthesis used for expressions { } curly braces used for blocking of statements [ ] square braces used along with arrays
  • 38. D.Variables / Identifiers • These are the names of the objects, whose values can be changed during the program execution. Variables are named with description that transmits the value it holds. • A quantity of an item, which can be change its value during the execution of program is called variable. It is also known as Identifier. • Rules for naming a variable:- • It can be of letters, digits and underscore( _ ) • First letter should be a letter or an underscore, but it should not be a digit. • Reserve words cannot be used as variable names. • Example: basic, root, rate, roll-no etc are valid names.
  • 39. • Declaration of variables: Syntax type Variable list int i, j i, j are declared as integers float salary salary is declared ad floating point variable Char gender Gender is declared as character variable
  • 40. OPERATORS • operator is a symbol that tells the compiler to perform specific mathematical or logical functions. Following types of operators − • Arithmetic Operators • Relational Operators • Logical Operators • Bitwise Operators • Assignment Operator • Increment and decrement operators • Conditional Operators • Special Operators
  • 41. Arithmetic Operators • arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables). Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * multiplication / division % remainder after division (modulo division)
  • 42. Example 1: Arithmetic Operators • // Working of arithmetic operators #include <stdio.h> int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d n",c); a+b = 13 c = a-b; printf("a-b = %d n",c); a-b = 5 c = a*b; printf("a*b = %d n",c); a*b=36 c = a/b; printf("a/b = %d n",c); a/b=2 c = a%b; printf("Remainder when a divided by b = %d n",c); c=1 return 0; }
  • 43. Output a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1
  • 44. 2.Increment and Decrement Operators • C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. • Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.
  • 45. Example :Increment and Decrement Operators • // prefix operators #include <stdio.h> int main() { int a = 10, b = 100; float c = 10.5, d = 100.5; printf("++a = %d n", ++a); ++a = 11 printf("--b = %d n", --b); --b = 99 printf("++c = %f n", ++c); ++c = 11.500000 printf("--d = %f n", --d); --d = 99.500000 return 0; }
  • 46. Example prefix and post fix a = 5 ++a; // a becomes 6 a++; // a becomes 7 --a; // a becomes 6 a--; // a becomes 5
  • 47. 3.Assignment Operators • assignment operator is used for assigning a value to a variable. The most common assignment operator is = Operator Example Same as = a = b a = b += a += b a = a+b -= a -= b a = a-b *= a *= b a = a*b /= a /= b a = a/b %= a %= b a = a%b
  • 48. Example 3: Assignment Operators • // Working of assignment operators #include <stdio.h> int main() { int a = 5, c; c = a; // c is 5 printf("c = %dn", c); c = 5 c += a; // c is 10 printf("c = %dn", c); c = 10 c -= a; // c is 5 printf("c = %dn", c); C=5 c *= a; // c is 25 printf("c = %dn", c); c=25 c /= a; // c is 5 printf("c = %dn", c); c=1 c %= a; // c = 0 printf("c = %dn", c); c=0 return 0; }
  • 49. 4.Relational Operators • A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. • Relational operators are used in decision making and loops. Operator Meaning of Operator Example == Equal to 5 == 3 is evaluated to 0 > Greater than 5 > 3 is evaluated to 1 < Less than 5 < 3 is evaluated to 0 != Not equal to 5 != 3 is evaluated to 1 >= Greater than or equal to 5 >= 3 is evaluated to 1 <= Less than or equal to 5 <= 3 is evaluated to 0
  • 50. Example 4: Relational Operators // Working of relational operators #include <stdio.h> int main() { int a = 5, b = 5, c = 10; printf("%d == %d is %d n", a, b, a == b); 5 == 5 is 1 printf("%d == %d is %d n", a, c, a == c); 5 == 10 is 0 printf("%d > %d is %d n", a, b, a > b); 5 > 5 is 0 printf("%d > %d is %d n", a, c, a > c); 5 > 10 is 0 printf("%d < %d is %d n", a, b, a < b); 5 < 5 is 0 printf("%d < %d is %d n", a, c, a < c); 5 < 10 is 1 printf("%d != %d is %d n", a, b, a != b); 5 != 5 is 0 printf("%d != %d is %d n", a, c, a != c); 5 != 10 is 1 printf("%d >= %d is %d n", a, b, a >= b); 5 >= 5 is 1 printf("%d >= %d is %d n", a, c, a >= c); 5 >= 10 is 0 printf("%d <= %d is %d n", a, b, a <= b); 5 <= 5 is 1 printf("%d <= %d is %d n", a, c, a <= c); 5 <= 10 is 1 return 0; }
  • 51. 5.Logical Operators • expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. Operator Meaning Example && Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to0. || Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0.
  • 52. Example 5: Logical Operators • // Working of logical operators #include <stdio.h> int main() { int a = 5, b = 5, c = 10, result; result = (a == b) && (c > b); printf("(a == b) && (c > b) is %d n", result); result = (a == b) && (c < b); printf("(a == b) && (c < b) is %d n", result); result = (a == b) || (c < b); printf("(a == b) || (c < b) is %d n", result); result = (a != b) || (c < b); printf("(a != b) || (c < b) is %d n", result); result = !(a != b); printf("!(a != b) is %d n", result); result = !(a == b); printf("!(a == b) is %d n", result); return 0; } (a == b) && (c > b) is 1 (a == b) && (c < b) is 0 (a == b) || (c < b) is 1 (a != b) || (c < b) is 0 !(a != b) is 1 !(a == b) is 0
  • 53. Explanation of logical operator program • (a == b) && (c > b) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true). • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false). • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true). • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false). • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true). • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).
  • 54. 6.Bitwise Operators • During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power. • Bitwise operators are used in C programming to perform bit-level operations. Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left >> Shift right
  • 56. • Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
  • 57. • Assume A = 60 and B = 13 in binary format, they will be as follows − • A = 0011 1100 • B = 0000 1101 • ----------------- • A&B = 0000 1100 A*B= • A|B = 0011 1101 A+B= • A^B = 0011 0001 • ~A = 1100 0011 1 2 4 8 16 32 64 128 256 512 1024 2048
  • 58. Example #include <stdio.h> main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %dn", c ); Line 1 - Value of c is 12 c = a | b; /* 61 = 0011 1101 */ printf("Line 2 - Value of c is %dn", c ); Line 2 - Value of c is 61 c = a ^ b; /* 49 = 0011 0001 */ printf("Line 3 - Value of c is %dn", c ); Line 3 - Value of c is 49 c = ~a; /*-61 = 1100 0011 */ printf("Line 4 - Value of c is %dn", c ); Line 4 - Value of c is -61 c = a << 2; /* 240 = 1111 0000 */ printf("Line 5 - Value of c is %dn", c ); Line 5 - Value of c is 240 c = a >> 2; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %dn", c ); Line 6 - Value of c is 15 }
  • 59. 7.Conditional Operator in C • The conditional operator is also known as a ternary operator. • The conditional statements are the decision-making statements that depend upon the output of the expression. • As a conditional operator works on three operands, so it is also known as the ternary operator. • The operands may be an expression, constants, or variables. • It starts with a condition, hence it is called a conditional operator.
  • 60. • Syntax of Conditional Operator in C: expression1 ? expression2 : expression3; or for simplicity, we write it as condition ? true-statement : false-statement; The expression1 is evaluated, it is treated as a logical condition. If the result is non-zero then expression2 will be evaluated otherwise expression3 will be evaluated. The value after evaluation of expression2 or expression3 is the final result.
  • 61. • The conditional operator in C works similar to the conditional control statement if-else. • Hence every code written using conditional operator can also be written using if-else. • When compared with if-else, conditional operator performance is high. if(expression1) { expression2; } else { expression3; }
  • 62. Write a C program to find the maximum in the given two numbers using the conditional operator #include<stdio.h> int main() { float num1, num2, max; printf("Enter two numbers: "); scanf("%f %f", &num1, &num2); max = (num1 > num2) ? num1 : num2; printf("Maximum of %.2f and %.2f = %.2f", num1, num2,max); return 0; } max=(34>45)?34: 45;
  • 63. 8.SPECIAL OPERATORS IN C Operator Description Example sizeof Returns the size of an variable sizeof(x) return size of the variable x & Returns the address of an variable &x ; return address of the variable x * Pointer to a variable *x ; will be pointer to a variable x
  • 64. EXAMPLE PROGRAM FOR & AND * OPERATORS IN C #include <stdio.h> int main() { int *ptr, q; q = 50; /* address of q is assigned to ptr */ ptr = &q; /* display q's value using ptr variable */ printf("%d", *ptr); return 0; } OUTPUT: 50
  • 65. EXAMPLE PROGRAM FOR SIZEOF() OPERATOR IN C • sizeof() operator is used to find the memory space allocated for each C data types. #include <stdio.h> #include <limits.h> int main() { int a; char b; float c; double d; printf("Storage size for int data type:%d n",sizeof(a)); printf("Storage size for char data type:%d n",sizeof(b)); printf("Storage size for float data type:%d n",sizeof(c)); printf("Storage size for double data type:%dn",sizeof(d)); return 0; }
  • 66. OUTPUT: Storage size for int data type:2 Storage size for char data type:1 Storage size for float data type:4 Storage size for double data type:8
  • 68. • Expression represent data item such as variables, constants and are interconnected with operators as per the syntax of the language. • Expression is evaluated using assignment operator. Syntax: variable = expression; Description –any ‘C’ valid variable and expression Example--- x=a*b-c; Blank space is around an operator is optional and adds only to improve readability of the program. Expressions
  • 69. • The variables that are used in an expression must be declared at the declaration part of the program. Algebric Expression C Expression a+bX c a+b*c ax2+bx+c a*x*x+b*x+c (4ac/2a) (4*a*c)/(2*a)
  • 70. Operator precedence Rules for evaluation of expression • Evaluate the sub expression from left to right if parenthesized. • Arithmetic expression from left to right using the rules of precedence. • Highest precedence is given to the expression with in parenthesis • Apply the associative rule,if more operators of the same precedence occurs. • Evaluate the inner most sub expression if the parenthesis are nested.
  • 72. Type Conversion • Type Conversion refers the process of changing an entity of one data type into another. • Mix the types of values in your arithmetic expression. • To take advantage of certain features of one data type to another. Example: • Integers can be stored in a more compact format and later converted to a different format enabling operations not previously possible. Two types of type conversion i.Implicit ,ii.Explicit
  • 73. • Implicit-Compulsory conversion • It’s an automatic type conversion ,mixed type expression data of one or more subtypes can be converted to a super type as needed at run time, so that the program will run correctly. • Explicit Conversion: Type Casting • Explicit Conversion can be made to convert one data type to another by forcefully and it is different from the implicit conversion. Syntax:var2=(datatype)var2; int a =20; float(a); float(a) will contain 20.000000
  • 74. • C language 2 types of input/output statements are available. • I/O operations carried out through function calls. Input and Output operations I/O functions Formatted I/O Unformatted I/O INPUT OUTPUT Getc() Putc() Getchar() Putchaar() Gets() Puts() Getche() Getch() INPUT OUTPUT Scanf() Printf() Fscanf() Fprintf()
  • 75. • getchar() Function The getchar() function reads character type data form the input. The getchar() function reads one character at a time till the user presses the enter key. #include <stdio.h> //header file section #include <conio.h> int main() { char c; printf("Enter a character : "); c = getchar(); printf("n Entered character : %c ", c); return 0; } Enter a character : y Entered character : y
  • 76. • getch() Function The getch() function reads the alphanumeric character input from the user. But, that the entered character will not be displayed. #include <stdio.h> //header file section #include <conio.h> int main() { printf("nHello, press any alphanumeric character to exit "); getch(); return 0; } Hello, press any alphanumeric character to exit
  • 77. • getche() Function : getche() function reads the alphanumeric character from the user input. • Here, character you entered will be echoed to the user until he/she presses any key. #include <stdio.h> //header file section #include <conio.h> int main() { printf("nHello, press any alphanumeric character or symbol to exit n "); getche(); return 0; } Hello, press any alphanumeric character or symbol to exit J
  • 78. • putchar() Function putchar() function prints only one character at a time. #include <stdio.h> //header file section #include <conio.h> int main() { char c = 'K'; putchar(c); return 0; } Note: Here, variable c is assigned to a character 'K'. The variable c is displayed by the putchar(). Use Single quotation mark ' ' for a character.
  • 79. • putch() Function • The putch() function prints any alphanumeric character. #include <stdio.h> //header file section #include <conio.h> int main() { char c; printf("Press any key to continuen "); c = getch(); printf("input : "); putch(c); return 0; } Press any key to continue ; input : d • Note: The getch() function will not echo a character. The putch() function displays the input you pressed.
  • 80. • puts() Function • The puts() function prints the charcater array or string on the console. The puts() function is similar to printf() function, but we cannot print other than characters using puts() function. #include <stdio.h> //header file section #include <conio.h> int main() { char c[25]; printf("Enter your Name : "); gets(c); puts(c); return 0; } Enter your Name: john john
  • 81. Decision Making and Branching • Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed. • if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
  • 82. •the general form of a typical decision making structure found in most of the programming language C programming language assumes any non-zero and non- null values as true, and if it is either zero or null, then it is assumed as false value.
  • 83. S.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if...else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 nested switch statements You can use one switch statement inside another switch statement(s).
  • 84. C - if statement • if statement consists of a Boolean expression followed by one or more statements. • Syntax; if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } • If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed. • If the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.
  • 85. Example #include <stdio.h> int main () { int a = 10; if( a < 20 ) { printf("a is less than 20n" ); } printf("value of a is : %dn", a); return 0; } OUTPUT: // a is less than 20; value of a is : 10
  • 86. C - if...else statement • if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax: if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
  • 87. • If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed. • C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
  • 88. Example #include <stdio.h> int main () { int a = 100; /* check the boolean condition */ if( a < 20 ) { printf("a is less than 20n" ); } else { printf("a is not less than 20n" ); } printf("value of a is : %dn", a); return 0; } a is not less than 20; value of a is : 100
  • 89. If...else if...else Statement • An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. • When using if...else if..else statements, there are few points to keep in mind − • An if can have zero or one else's and it must come after any else if's. • An if can have zero to many else if's and they must come before the else. • Once an else if succeeds, none of the remaining else if's or else's will be tested.
  • 90. • Syntax if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ }
  • 91. Example: #include <stdio.h> int main () { int a = 30; if( a == 10 ) { printf("Value of a is 10n" ); } else if( a == 20 ) { printf("Value of a is 20n" ); } else if( a == 30 ) { printf("Value of a is 30n" ); } else { printf("None of the values is matchingn" ); } printf("Exact value of a is: %dn", a ); return 0; } None of the values is matching Exact value of a is: 30
  • 92. nested if statements • It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement. Syntax: if( boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } }
  • 93. #include <stdio.h> int main () { int a = 100; int b = 200; if( a == 100 ) { if( b == 200 ) { printf("Value of a is 100 and b is 200n" ); } } printf("Exact value of a is : %dn", a ); printf("Exact value of b is : %dn", b ); return 0; } Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200
  • 94. C - switch statement • switch statement allows a variable to be tested for equality against a list of values. • Each value is called a case, and the variable being switched on is checked for each switch case. • Syntax switch(expression) { case constant-expression : statement(s); break; case constant-expression : statement(s); break; default : statement(s); }
  • 95. • The following rules apply to a switch statement :- • The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
  • 97. #include <stdio.h> int main () { char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!n" ); break; case 'B' : case 'C' : printf("Well donen" ); break; case 'D' : printf("You passedn" ); break; case 'F' : printf("Better try againn" ); break; default : printf("Invalid graden" ); } printf("Your grade is %cn", grade ); return 0; } Well done Your grade is B
  • 98. nested switch statements • It is possible to have a switch as a part of the statement sequence of an outer switch. • Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. Syntax switch(ch1) { case 'A': printf("This A is part of outer switch" ); switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': } break; case 'B‘:}
  • 99. #include <stdio.h> int main () { int a = 100; int b = 200; switch(a) { case 100: printf("This is part of outer switchn", a ); switch(b) { case 200: printf("This is part of inner switchn", a ); } } printf("Exact value of a is : %dn", a ); printf("Exact value of b is : %dn", b ); return 0; } This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200
  • 100. Looping statements • A block of code needs to be executed several number of times. In general, statements are executed sequentially. • The first statement in a function is executed first, followed by the second, and so on. • Programming languages provide various control structures that allow for more complicated execution paths. • A loop statement allows us to execute a statement or group of statements multiple times.
  • 102. C programming language provides the following types of loops to handle looping requirements. S.No. Loop Type & Description 1 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 2 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 3 do...while loop It is more like a while statement, except that it tests the condition at the end of the loop body. 4 nested loops You can use one or more loops inside any other while, for, or do..while loop.
  • 103. FOR LOOP • for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax for ( init; condition; increment ) { statement(s); }
  • 105. Example #include <stdio.h> int main () { int a; /* for loop execution */ for( a = 10; a < 20; a = a + 1 ) { printf("value of a: %dn", a); } return 0; } OUTPUT: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 106. WHILE LOOP • while loop in C programming repeatedly executes a target statement as long as a given condition is true. Syntax: while(condition) { statement(s); } •statement(s) may be a single statement or a block of statements. •The condition may be any expression, and true is any nonzero value. •The loop iterates while the condition is true. •When the condition becomes false, the program control passes to the line immediately following the loop.
  • 108. #include <stdio.h> int main () { int a = 10; /* local variable definition */ while( a < 20 ) /* while loop execution */ { printf("value of a: %dn", a); a++; } return 0; } OUTPUT: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 109. Do while • for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop. • A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. Syntax do { statement(s); } while( condition );
  • 110. • the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. • If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. • This process repeats until the given condition becomes false.
  • 112. #include <stdio.h> int main () { int a = 10; do { printf("value of a: %dn", a); a = a + 1; } while( a < 20 ); return 0; } OUTPUT: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 113. S. No For loop While loop Do while loop 1. Syntax: For(initialization; condition;updating), { . Statements; } Syntax: While(condition), { . Statements; . } Syntax: Do { . Statements; } While(condition); 2. It is known as entry controlled loop It is known as entry controlled loop. It is known as exit controlled loop. 3. If the condition is not true first time than control will never enter in a loop If the condition is not true first time than control will never enter in a loop. Even if the condition is not true for the first time the control will enter in a loop. 4. There is no semicolon; after the condition in the syntax of the for loop. There is no semicolon; after the condition in the syntax of the while loop. There is semicolon; after the condition in the syntax of the do while loop. 5. Initialization and updating is the part of the syntax. Initialization and updating is not the part of the syntax. Initialization and updating is not the part of the syntax
  • 114. Loop Control Statements • Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. S.No. Control Statement & Description 1 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 go to statement Transfers control to the labeled statement.
  • 115. Break statement • a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. • It can be used to terminate a case in the switch statement • If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax break;
  • 117. #include <stdio.h> int main () { int a = 10; while( a < 20 ) { printf("value of a: %dn", a); a++; if( a < 15) { break; } } return 0; } OUTPUT value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
  • 118. CONTINUE STATEMENT • continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. • for loop, continue statement causes the conditional test and increment portions of the loop to execute. • For the while and do...while loops, continue statement causes the program control to pass to the conditional tests. Syntax continue;
  • 120. #include <stdio.h> int main () {int a = 10; do { if( a == 15) { a = a + 1; continue; } printf("value of a: %dn", a); a++; } while( a < 20 ); return 0; } OUTPUT: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 121. goto statement • goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function. • NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them. Syntax goto label; .. . label: statement;
  • 123. #include <stdio.h> int main () { int a = 10; LOOP: do { if( a == 15) { a = a + 1; goto LOOP; } printf("value of a: %dn", a); a++; } while( a < 20 ); return 0; } OUTPUT: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 124. Infinite Loop • A loop becomes an infinite loop if a condition never becomes false. • The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty. • For()
  • 125. #include <stdio.h> int main () { for( ; ; ) { printf("This loop will run forever.n"); } return 0; } the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
  翻译: