Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
101 views

Unit-II Introduction To C Programming

The document discusses C programming basics including header files, the structure of a C program, data types, and compilation and linking processes. It provides details on the history and features of C language, as well as the basic data types used in C including character, integer, floating point, and double. It also describes constants, variables, operators, and input/output operations in C programming.

Uploaded by

gokul kannan.m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Unit-II Introduction To C Programming

The document discusses C programming basics including header files, the structure of a C program, data types, and compilation and linking processes. It provides details on the history and features of C language, as well as the basic data types used in C including character, integer, floating point, and double. It also describes constants, variables, operators, and input/output operations in C programming.

Uploaded by

gokul kannan.m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

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
International
Algol 1960
Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

Kernighan &
K&RC 1978
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.
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 E8 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 = %d\n", c); c=5
c += a; // c is 10
printf("c = %d\n", c); c = 10
c -= a; // c is 5
printf("c = %d\n", c); C=5
c *= a; // c is 25
printf("c = %d\n", c); c=25
c /= a; // c is 5
printf("c = %d\n", c); c=1
c %= a; // c = 0
printf("c = %d\n", 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


If c = 5 and d = 2 then,
Logical AND. True only if all
&& expression ((c==5) && (d>5))
operands are true
equals to0.
If c = 5 and d = 2 then,
Logical OR. True only if
|| expression ((c==5) || (d>5))
either one operand is true
equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5)


!
operand is 0 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); (a == b) && (c > b) is 1
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b); (a == b) && (c < b) is 0
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b); (a == b) || (c < b) is 1
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b); (a != b) || (c < b) is 0
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b); !(a != b) is 1
printf("!(a != b) is %d \n", result);
result = !(a == b); !(a == b) is 0
printf("!(a == b) is %d \n", result);
return 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


• 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 %d\n", c ); Line 1 - Value of c is 12
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c ); Line 2 - Value of c is 61
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c ); Line 3 - Value of c is 49
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c ); Line 4 - Value of c is -61
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c ); Line 5 - Value of c is 240
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", 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 sizeof(x) return size of
an variable the variable x
& Returns the address &x ; return address of the
of an variable 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:%d\n",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
Expressions
• 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.
• 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.
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
Input and Output operations
• C language 2 types of input/output statements are available.
• I/O operations carried out through function calls.
I/O functions

Unformatted I/O Formatted I/O


INPUT OUTPUT
INPUT OUTPUT
Getc() Putc() Scanf() Printf()
Getchar() Putchaar() Fscanf() Fprintf()
Gets() Puts()
Getche()
Getch()
• 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 continue\n ");
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
if statement An if statement consists of a boolean expression
1
followed by one or more statements.
if...else statement An if statement can be followed by an
2 optional else statement, which executes when the Boolean
expression is false.
nested if statements You can use one if or else if statement inside
3
another if or else if statement(s).
switch statement A switch statement allows a variable to be tested
4
for equality against a list of values.
nested switch statements You can use one switch statement inside
5
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 20\n" );
}
printf("value of a is : %d\n", 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 20\n" );
}
else
{
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", 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 10\n" ); }
else if( a == 20 ) { printf("Value of a is 20\n" ); }
else if( a == 30 ) { printf("Value of a is 30\n" ); }
else { printf("None of the values is matching\n" ); }
printf("Exact value of a is: %d\n", 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; Value of a is 100 and b is 200
if( a == 100 ) Exact value of a is : 100
{
if( b == 200 ) Exact value of b is : 200
{
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
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 done\n" ); break;
case 'D' : printf("You passed\n" ); break;
case 'F' : printf("Better try again\n" ); break;
default : printf("Invalid grade\n" ); }
printf("Your grade is %c\n", 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; This is part of outer switch
int b = 200; This is part of inner switch
switch(a) Exact value of a is : 100
{ Exact value of b is : 200
case 100:
printf("This is part of outer switch\n", a );
switch(b)
{
case 200: printf("This is part of inner switch\n", a ); } }
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
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.
C programming language provides the following
types of loops to handle looping requirements.
S.No. Loop Type & Description
for loop Executes a sequence of statements multiple times
1
and abbreviates the code that manages the loop variable.
while loop Repeats a statement or group of statements while
2 a given condition is true. It tests the condition before
executing the loop body.
do...while loop It is more like a while statement, except that
3
it tests the condition at the end of the loop body.
nested loops You can use one or more loops inside any other
4
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); }
Example
#include <stdio.h> OUTPUT:
int main () value of a: 10
{ int a; /* for loop execution */ value of a: 11
value of a: 12
for( a = 10; a < 20; a = a + 1 )
value of a: 13
{ value of a: 14
printf("value of a: %d\n", a); value of a: 15
} value of a: 16
return 0; 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: •statement(s) may be a single
while(condition) statement or a block of statements.
•The condition may be any expression,
{ and true is any nonzero value.
statement(s); •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 () OUTPUT:
{ value of a: 10
int a = 10; /* local variable definition */ value of a: 11
while( a < 20 ) /* while loop execution */ value of a: 12
value of a: 13
{
value of a: 14
printf("value of a: %d\n", a); a++; value of a: 15
} value of a: 16
return 0; 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.
#include <stdio.h>
int main () OUTPUT:
{ value of a: 10
int a = 10; value of a: 11
do value of a: 12
{ value of a: 13
printf("value of a: %d\n", a); value of a: 14
a = a + 1; value of a: 15
} value of a: 16
while( a < 20 ); value of a: 17
return 0; value of a: 18
} value of a: 19
S. For loop While loop Do while loop
No
Syntax: For(initialization; Syntax: While(condition), { Syntax: Do { . Statements; }
1. condition;updating), { . . Statements; . } While(condition);
Statements; }
It is known as entry It is known as entry It is known as exit controlled
2.
controlled loop controlled loop. loop.
If the condition is not true If the condition is not true Even if the condition is not true
3. first time than control will first time than control will for the first time the control
never enter in a loop never enter in a loop. will enter in a loop.
There is no semicolon; There is no semicolon; There is semicolon; after the
4. after the condition in the after the condition in the condition in the syntax of the
syntax of the for loop. syntax of the while loop. do while loop.
Initialization and updating Initialization and updating Initialization and updating is
5. is the part of the syntax. is not the part of the syntax. 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

break statement Terminates the loop or switch statement and


1 transfers execution to the statement immediately following the
loop or switch.
continue statement Causes the loop to skip the remainder of its
2
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;
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 ) OUTPUT
{
printf("value of a: %d\n", a); value of a: 10
a++; value of a: 11
if( a < 15) value of a: 12
{
break; value of a: 13
}} value of a: 14
return 0; 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;
#include <stdio.h>
int main () OUTPUT:
{int a = 10; value of a: 10
do { value of a: 11
if( a == 15) value of a: 12
{ value of a: 13
a = a + 1; value of a: 14
continue; value of a: 15
} value of a: 16
printf("value of a: %d\n", a); a++; } value of a: 17
while( a < 20 ); value of a: 18
return 0; } 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;
#include <stdio.h>
int main ()
{ OUTPUT:
int a = 10; value of a: 10
LOOP: do
{
value of a: 11
if( a == 15) value of a: 12
{ value of a: 13
a = a + 1; value of a: 14
goto LOOP;
} value of a: 15
printf("value of a: %d\n", a); a++; value of a: 16
} value of a: 17
while( a < 20 );
value of a: 18
return 0;
} 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.

You might also like