SlideShare une entreprise Scribd logo
1  sur  125
Télécharger pour lire hors ligne
UNIT 2
C PROGRAMMING BASICS
What is C?
• Language written by Brian Kernighan and
Dennis Ritchie
• C has been used as a general – purpose
language because of its popularity
• It was written to become first “portable”
language
Why use C?
• Mainly because it produces code that runs nearly as fast as code
written in assembly language. Some examples of the use of C might be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Data Bases
• Language Interpreters
• Utilities
Mainly because of the portability that writing standard C programs can
offer
History
• 1960 : -
• ALGOL was found by International group of computer users.
• COBOL was found for commercial application usage.
• FORTRAN was found for scientific applications.
• In 1967: -
• Basic Combined Programming Language (BCPL)
• developed by Martin Richards at Cambridge University.
• a single language which can program all possible applications,
• In 1970: -
• a language called B was developed by Ken Thompson at AT & T’s Bell Labs.
History
• In 1972: -
• Dennis Ritchie at Bell Labs developed a language with some additional
features of BPCL and B called C.
• In 1978: -
• Publication of The C Programming Language by Kernighan & Ritchie caused a
revolution in the computing world.
• In 1983: -
• the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the
ANSI standard, or "ANSI C", was completed late 1988.
Why C Still Useful?
• C characteristics:
 Highly structured language
 Handle bit-level operations
 Machine independent language-highly portable
 Supports variety of data types and powerful set of operators
 Supports dynamic memory management by using concept of pointers
• C is used to develope:
 System software - Compilers, Editors, embedded systems
 data compression, graphics and computational geometry, utility programs
 databases, operating systems, device drivers, system level routines
 there are zillions of lines of C legacy code
 Also used in application programs
Programming languages
• Some understandable directly by computers
• Others require “translation” steps
• Various programming languages
• Machine language
• Assembly language
• High-level language
• Machine language
• Natural language of a particular computer
• Consists of strings of numbers(1s, 0s)
• Instruct computer to perform elementary
operations one at a time
• Machine dependent
Programming languages
• Assembly Language
• English like abbreviations
• Assemblers:
• Translators of programs
• Convert assembly language programs to machine language.
• E.g. add overtime to base pay and store result in gross pay
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
Programming languages
• High-level languages
• To speed up the programming process
• Single statements for accomplishing substantial tasks
• Compilers - convert high-level programs into machine
language
• E.g. add overtime to base pay and store result in gross pay
grossPay = basePay + overtimePay
Basics of C Environment
• C systems consist of 3 parts
• Environment
• Language
• C Standard Library
• Development environment has 6 phases
 Edit - Writing the source code by using some IDE or editor
 Pre-processor - Already available routines
 Compile - translates or converts source to object code for a
specific platform ie., source code -> object code
 Link - resolves external references and produces the executable
module
 Load – put the program into the memory
 Execute – runs the program
Basics of C Environment
Editor DiskPhase 1
Program edited in
Editor and stored
on disk
Preprocessor DiskPhase 2
Preprocessor
program processes
the code
Compiler DiskPhase 3
Creates object code
and stores on disk
Linker DiskPhase 4
Links object code
with libraries and
stores on disk
Basics of C Environment
LoaderPhase 5
Puts program in
memory
Primary memory
CPUPhase 6
Takes each instruction
and executes it storing
new data values
Primary memory
Executing a C Program
Steps involved in execution are
• Creating the program
• Compiling the program
• Linking the program with functions that are needed from the
C library
• Executing the program
Executing a C Program
Edit
Program
Source
Code
Compile
Object
Code
Link Object
Code Executable
Library
Files
Basics Structure of C Program
Documentation section
Link section
Definition section
Global declaration section
main() function section
{
Declaration part
Executable part
}
Subprogram section
(user defined function)
Simple C Program
/* A first C Program*/
#include <stdio.h>
void main()
{
printf("Hello World n");
}
Simple C Program
• Line 1: #include <stdio.h>
• As part of compilation, the C compiler runs a program called
the C preprocessor. The preprocessor is able to add and
remove code from your source file.
• In this case, the directive #include tells the preprocessor to
include code from the file stdio.h.
• This file contains declarations for functions that the program
needs to use. A declaration for the print function is in this file.
Simple C Program
• Line 2: void main()
• This statement declares the main function.
• C program can contain many functions but must always have
one main function.
• A function is a self-contained module of code that can
accomplish some task.
• Functions are examined later.
• "void" specifies the return type of main. In this case, nothing is
returned to the operating system.
Simple C Program
• Line 3: {
• This opening bracket denotes the start of the
program.
Simple C Program
• Line 4: printf("Hello Worldn");
• printf is a function from a standard C library that is
used to print strings to the standard output, normally
your screen.
• The "n" is a special format modifier that tells the
printf to put a line feed at the end of the line.
• If there were another printf in this program, its string
would print on the next line.
Simple C Program
• Line 5: }
• This closing bracket denotes the end of the
program.
C Character Set
• Characters are the basic building blocks in C program,
equivalent to ‘letters’ in English language
• Characters can be used to form words, numbers and
expressions
• Characters in C are grouped into following categories
• Letters ex:a…z,A…Z
• Digits ex:0…9
• Special characters ex:,,&,@,_,+,-,…..
• White spaces ex:blank space
horizontal tab
new line…….
C Tokens
• In a passage of text, individual words and punctuation marks
are called tokens
• In a C source program, the basic element recognized by the
compiler is the "token."
• C Tokens are
 Keywords - int, float, while
 Identifiers - sum, main
 Constants - 100, -55.5
 Strings - “ABC”, “Hello”
 Operators - +, -, *, /, ++
 Special symbols - {, },[, ]
Keywords
• All keywords are reserved words have fixed meanings and
these meanings cannot be changed
• Have special meaning to the compiler, cannot be used as
identifiers in our program.
• Keywords serve as basic building blocks for program
statement
• Keywords must be written in lowercase
• Displayed in BLUE color in MS Visual C++
Some Keywords
Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers
• Refer to the names of variables, functions and arrays
• User defined names and consist of a letters and
digits, with a letter as a first character
Rules for Identifiers
• First character must be an alphabet
• Must consist of only letters, digits and underscore
• Only first 32 characters are significant
• Cannot use a keyword
• Must not contain white space
• Case sensitive-Identifier Sub differ from sub
Identifiers
Examples of legal identifier:
Student_age, Item10, counter, number_of_character
Examples of illegal identifier
Student age (embedded blank)
continue (continue is a reserved word)
10thItem (the first character is a digit)
Principal+interest (contain operator character +)
1. Avoid excessively short and cryptic names such as x or wt. Instead,
use a more readable and descriptive names such as student_major
and down_payment.
2. Use underscores or capital letters to separate words in identifiers
that consist of two or more words. Example, student_major or
studentMajor are much easier to read than studentmajor.
Recommendations forConstructingIdentifiers
Constants
• Constants refers to fixed values that do not change during the
execution a program
Types of Constants
Numeric Constants
 Integer Constants - 234, 045, 0x2A, 0X3B
 Real Constants - 2.345, 0.64e-2
Character Constants
 Single Character Constants ‘5’, ‘A’
 String Constants “Hello”
IntegerConstant
Positive or negative whole numbers with no fractional part
Optional + or – sign before the digit.
It can be decimal (base 10), octal (base 8) or hexadecimal (base 16)
Hexadecimal is very useful when dealing with binary numbers
Example:
const int MAX_NUM = 10;
const int MIN_NUM = -90;
const int Hexadecimal_Number = 0xf87;
RulesforDecimalIntegerConstant
1. Decimal integer constants must begin with a nonzero decimal digit, the
only exception being 0, and can contain decimal digital values of 0 through
9. An integer that begins with 0 is considered an octal constant
2. If the sign is missing in an integer constant, the computer assumes a
positive value.
3. Commas are not allowed in integer constants. Therefore, 1,500 is illegal; it
should be 1500.
Example of legal integer constants are –15, 0, +250 and 7550
Example of illegal constants
0179 is illegal since the first digit is zero
1F8 is illegal since it contains letter ‘F’
1,700 is illegal since it contains comma
FloatingPointConstant
• Positive or negative decimal numbers with an integer part(optional), a
decimal point, and a fractional part (optional)
Example 2.0, 2., 0.2, .2, 0., 0.0, .0
• It can be written in conventional or scientific way
• 20.35 is equivalent to 0.2035E+2 (0.2035 x 102 )
• 0.0023 is equivalent to 0.23e-2 (0.23 x 10-2)
• E or e stand for “exponent”
• In scientific notation, the decimal point may be omitted.
Example: -8.0 can rewritten as -8e0
Floating Point Constant
• C support 3 type of Floating-point: float (4 bytes), double (8 bytes), long
double (16 bytes)
• By default, a constant is assumed of type double
• Suffix f(F) or l(L) is used to specify float and long double respectively
Example:
const float balance = 0.125f;
const float interest = 6.8e-2F
const long double PI = 3.1412L;
const long double planet_distance = 2.1632E+30l
• A character enclosed in a single quotation
mark
• Example:
• const char letter = ‘n’;
• const char number = ‘1’;
• printf(“%c”, ‘S’);
• Output would be: S
How to write a single quotation mark?
‘’’ is ambiguous, so escape character – back slash 
Example:
‘’’
Character Constants
String Literals
• A sequence of any number of characters surrounded by
double quotation marks.
• Example:
• “Human Revolution”
• How to write special double quotation mark?
• “”” is ambiguous, so use escape character
• Example: printf(“He shouted, “Run!””);
output: He shouted, “Run!”
- The escape character along with any character that follow it is
called Escape Sequence
BackslashCharacter Constants
Escape
Sequence
Name Meaning
a Alert Sounds a beep
b Back space Backs up 1 character
f Form feed Starts a new screen of page
n New line Moves to beginning of next line
r Carriage return Moves to beginning of current line
t Horizontal tab Moves to next tab position
v Vertical tab Moves down a fixed amount
 Back slash Prints a back slash
’ Single quotation Prints a single quotation
” Double quotation Prints a double quotation
? Question mark Prints a question mark
Backslash Character Example
Program
#include<stdio.h>
void main()
{
printf("nabc");
printf("rdef");
printf("bghin");
printf("HaitHello");
}
Output
deghi
Hai Hello
Variables
• A variable is a data name used for storing a data value
• The value may be changed during program execution
Rules for defining variables
• Must begin with a character
• Should not be a C keyword
• May be combination of lower and upper characters
• Should not start with a digit
• Maximum characters upto 31 characters
Example
Sum, avg_wt, item
Declaration of Variables
• Syntax for declaring a variable is as follows
data-type v1,v2,….vn;
Example
int i,j,sum;
float avg;
double ratio;
unsigned int fact;
DATATYPE
• Datatype is the most important attributes of an identifier. It
detemines the possible values.
• Classification of Datatypes
-Basic Datatypes
-Derived datatypes
-User-defined datatypes
Basic/Primitive Datatypes:
Character (char)
Integer (int)
Single-precision floating point (float)
Double-precision floating point (double)
No value available (void)
Derived Datatypes:
Array type (char[], int[])
Pointer type (char*, int*)
Functiontype (int(int,int), float(int))
• User-defined datatypes
It provides flexibility to the user to create new datatypes.
Newly created called User-defined datatypes.
Structure
Union
Enumeration
Syntax:
data_type variable_name
Example:
int age;
char ch;
float avg;
int a,b,c;
Data Types
Initializing Variables
• Variables declared can be assigned or initialized using an assignment
operator ‘=‘
Syntax:
variable_name=constant;
or
data_type variable_name=constant;
Example:
int age; char ch=‘A’;
age=10; float avg=10.5;
Data Types in C
Type Keyword
Byte
s
Range
character char 1 -128...127
integer int 2 -32768...32767
short integer short 2 -32768...32767
long integer long 4 -2,147,483,648...2,147,438,647
long long
integer
long long 8
-9223372036854775808 …
9223372036854775807
unsigned
character
unsigned char 1 0...255
unsigned
integer
unsigned int 2 0...4,294,967,295
unsigned short
integer
unsigned short 2 0...65535
unsigned long
integer
unsigned long 4 0...4,294,967,295
single-precision float 4 1.2E-38...3.4E38
double-
precision
double 8 2.2E-308...1.8E308
Expressions
• Operands
It specifies an entity on which an operation is
to be performed. It may be a variable name, a
constant, a function call or a macro name
eg: a=printf(“Hello”)+2
• Operators
It specifies the operation to be applied to its
operands.
SimpleExpressionand Compound
Expression
• An Expression has only one operator called
Simple expression
eg: a+2
• An Expression has more than one operator
called Compound Expression.
eg: b=2+3*5
Properties Of Operators
• Precedence
• Associativity
Precedence:
• Priority allotted to the operator
• Each operator in C has a precedence associated with it.
• In compound expression, if the operator involved
different precedence, the operator of highest precedence
operates first.
Ex: 8+9*2-10
=8+18-10
=26-10
=16
Associativity:
• Expression having operators with equal precedence
• associativity property decides which operation is
performed first
• In compound expression, when several operators of
the same precedence appear together, the operators are
evaluated according to their associativity.
Types: Left to Right Right to left
12*4/8%2 x=8+5%2
= 48/8%2 =8+1
= 6%2 =9
= 0
• Operators has same precedence- same
associativity
• If operators are left-to-right, applied in a
left-to-right order
• If operators are right-to-left, applied in a
right-to-left order
• Multiplication and division operators are
left-to-right associative
Operators
• An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations
Classification of Operators:
Number of operands on which an operator operates
The role of an operator
Classification based on Number of operands
• Unary- it operates on only one operand
Eg: &, sizeof operator, !, ~, ++, --
• Binary – it operates on two operands
eg: *, /, <<, ==,&&, &
• Ternary- it operates on three operands
eg: ?:
Classification based on Role of
Operator
Arithmetic Operators +, -, *, /, %
Relational Operators <, <=, >, >=, ==, !=
Logical Operators &&, ||, !
Assignment Operators =
Increment and Decrement Operators ++,--
Conditional Operators ?=
Bitwise Operators &,|, ^, <<, >>
Special Operators ,, sizeof, &, * ., ->
Arithmetic Operators
C Operation Algebraic C
Addition (+) f + 7 f + 7
Subtraction (-) p – c p – c
Multiplication (*) bm b * c
Division (/) x / y x / y
Modulus (%) r mod s r % s
Arithmetic Operators Example
Program
#include <stdio.h>
#include <conio.h>
void main()
{
int x,y, a,s,m,d,r;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d%d”,&x,&y);
a = x + y;
printf(“a = %dn",a);
s = x - y;
printf(“s = %dn",s);
m = x * y;
printf(“m = %dn",m);
d = x / y;
printf(“d = %dn",d);
r = x % y;
printf("r = %dn",r);
}
Output
Enter two numbers:10 20
a = 30
s = -10
m = 200
d = 0
r = 10
Binary Arithmetic operators
• It is used in 3 different modes
Integer mode
Relational Operators
• Greater than >
• Less than <
• Greater than or equal to >=
• Less than or equal to <=
• Equal to ==
• Not equal to !=
Condition true return 1
Condition false return 0
Relational Operators Example
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,r;
clrscr();
printf(“Enter 2 nos. x & y:”);
scanf(“%d%d”,&x,&y);
r=(x==y);
printf("%dn",r);
r=(x!=y);
printf("%dn",r);
r=(x>y);
printf("%dn",r);
r=(x>=y);
printf("%dn",r);
r=(x<y);
printf("%dn",r);
r=(x<=y);
printf("%dn",r);
}
Output
Enter 2 nos. x & y: 10 20
0
1
0
0
1
1
Logical Operators
Operator Example Meaning
&& (Logical AND)
(Condition1) &&
(Condition2)
Both conditions should
satisfy to proceed
|| (Logical OR)
(Condition1) ||
(Condition2)
Either one condition
satisfied proceed to
next operation
! (Logical NOT) !(Condition1)
The condition not
satisfied proceed to
next operation
Logical Operators
Example
if ((x>20) && (x<100)) printf("x is inside open interval
20-
100");
if ((x<5) || (x>20)) printf("x is not inside closed interval 5-20");
if (!(x>20)) printf("x is smaller or equal to 20");
Logical Operators Example
//Greatest of 3 numbers using
logical operators
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
clrscr();
printf(“Enter 3 nos. x ,y,z:”);
scanf(“%d%d%d”,&x,&y,&z);
if((x>y)&&(x>z))
printf(“x is greatest”);
if((y>x)&&(y>z))
printf(“y is greatest”);
if((z>x)&&(z>y))
printf(“z is greatest”);
}
Output
Enter 3 nos. x ,y,z: 40 20 30
x is greatest
Enter 3 nos. x ,y,z: 10 40 30
y is greatest
Enter 3 nos. x ,y,z: 10 20 30
z is greatest
Assignment operators
Operator Example Meaning
= 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
Increment/Decrement
operators
Operator Example Meaning
++ a++
First does the operation
and increments the value
+ + ++a
First Increments the value
and does the operation
-- a--
First does the operation
and decrements the
value
-- --a
First decrements the
value and does the
operation
Increment/Decrement
operators
Program
void main()
{
int c;
c = 5;
printf(“%dn”, c);
printf(“%dn”, c++);
printf(“%dnn”, c);
c = 5;
printf(“%dn”, c);
printf(“%dn”, ++c);
printf(“%dn”, c);
}
Output
5
5
6
5
6
6
c=10
x=c++ + ++c;
x=? C=?
Conditional Operator
Conditional Operator (?:) is ternary operator (demands 3 operands),
and is used in certain situations, replacing if-else condition phrases.
Conditional operator’s syntax is:
condition?expression1:expression2;
If condition is true, expression1 is executed.
If condition is false, expression2 is executed.
Example:
int a, b, c;
...
c = a > b ? a : b; // if a>b "execute" a, else b and
assign the value to
c
Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One‟s Complement
<< Left Shift
>> Right Shift
Bitwise Operators Example
Let A=0x56 and B=0x32
A & B ( Bitwise AND )
0 1 0 1 0 1 1 0
0 0 1 1 0 0 1 0
---------------------
0 0 0 1 0 0 1 0
---------------------
A ^ B ( Bitwise XOR )
0 1 0 1 0 1 1 0
0 0 1 1 0 0 1 0
---------------------
0 1 1 0 0 10 0
---------------------
A | B ( Bitwise OR )
0 1 0 1 0 1 1 0
0 0 1 1 0 0 1 0
---------------------
0 1 1 1 0 1 1 0
---------------------
~ A ( Complement )
0 1 0 1 0 1 1 0
---------------------
1 0 1 0 1 0 0 1
---------------------
Bitwise Operators Example
Let A=0x56
A << 2 ( Left Shift )
0 1 0 1 0 1 1 0 << 2  0 1 0 1 0 1 1 0 0 0 ( 0x158 )
A >> 2 ( Right Shift )
0 1 0 1 0 1 1 0 >> 1  0 1 0 1 0 1 1 ( 0x2B)
NOTE:
For multiply given number by two, left shifted by one time, i.e., a<<1
For divide given number by two, right shifted by one time, i.e., a>>1
Bitwise Operators Example
Write a program to shift inputed data by three bits left and right
Program
void main()
{
int x,y;
clrscr();
printf(“Enter value of x:”);
scanf(“%d”,&x);
y=x<<3;
printf(“Left shifted data=%d”,y);
printf(“Right shifted data=%d”,x>>3);
}
Output: Enter value of x:16
Left shifted data=128
Right shifted data=2
Special Operators
• C supports some special operators such as comma operator, size of
operator, pointer operators (& and *) and member selection
operators (. and ->).
• The size of and the comma operators are discussed here. The
remaining operators will see in pointer chapter
Comma Operator
• The comma operator can be used to link related expressions
together. A comma-linked list of expressions are evaluated left to
right and value of right most expression is the value of the combined
expression.
Example
value = (x = 10, y = 5, x + y);
for (n=1, m=10, n <=m; n++,m++)
t = x, x = y, y = t;
Special Operators
Sizeof Operator
• The operator sizeof gives the size of the data type or variable in
terms of bytes occupied in the memory. The operand may be a
variable, a constant or a data type qualifier.
• The size of operator is normally used to determine the lengths of
arrays and structures when their sizes are not known to the
programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.
Example
int sum;
m = sizeof(sum);  2
n = sizeof(long int);  4
k = sizeof(235L);  4
Expressions
Arithmetic Expressions
• An expression is a combination of variables constants and operators
written according to the syntax of C language.
Algebraic
Expression
C Expression
a x b – c a * b – c
(m + n) (x + y) (m + n) * (x + y)
3x2 +2x + 1 3*x*x+2*x+1
Expressions
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the
form
Variable = expression;
Variable is any valid C variable name.
The expression is evaluated first and then replaces the
previous value of the variable on the left hand side.
All variables used in the expression must be assigned values
before evaluation is attempted.
Example
x = a * b – c
y = b / c * a
z = a – b / c + d;
Decision Making - Branching
• Decision making statements are used to skip or to execute a group of
statements based on the result of some condition.
• The decision making statements are,
− simple if statement
− if…else statement
− nested if
− else … if ladder
− switch statement
− goto
• These statements are also called branching statements
Simple if statement
Syntax:
if(condition)
{
Statements;
}
if(condition)
Statements;
False
True (Bypass)
Simple if - Example
# include <stdio.h>
void main ()
{
int number;
printf("Type a number:");
scanf("%d",&number);
if (number < 0)
number = -number;
printf ("The absolute value is %d",number);
}
Output
Type a number -50
The absolute value is 50
if - else statement
Syntax:
if(condition)
{
True block statements;
}
else
{
False block statements;
}
if(condi
tion)
True Block
Statement
False
True
False Block
Statements
if – else Example
# include <stdio.h>
void main ()
{
int num;
printf ("Type a number:");
scanf ("%d", &num);
if (number < 0)
printf(“The number is negative”);
else
printf(“The number is positive”);
}
Output
Type a number 50
The number is positive
if – else Example
#include<stdio.h>
void main()
{
Int num;
printf ("Enter a number:");
scanf ("%d",&num);
if (num%2==0)
printf ("The number is
EVEN.n");
else
printf ("The number is ODD.n");
}
Output
Enter a number 125
The number is ODD
Nested if Statement
• if statement may itself can contain another if statement is known as nested if
statement.
Syntax:
if(condition1)
{
if(condition2)
{
True block statement of condition1 & 2;
}
else
{
False block statement of condition2;
}
}
else
{
False block statements of condition1;
}
Nested if Statement
condition1
True Block Statements of
condition 1 & 2;
False
True
False Block Statements of
condition 1;
if(condition2)
True
False Block Statements of
condition 2;
False
Nested if Example
# include <stdio.h>
void main()
{
int n1,n2,n3,big;
printf (“Enter 3 numbers:");
scanf ("%d %d %d", &n1,&n2,&n3);
if (n1 > n2)
{
if(n1 > n3)
big = n1;
else
big = n3;
}
if(n2 > n3)
big = n2;
else
big = n3;
printf(“The largest number is: %d”,big);
}
Output
Enter 3 numbers:10 25 20
The largest number is: 25
Else - if Ladder Statement
Syntax
if (condition1)
statement block 1;
else if (condition2)
statement block 2;
else if (condition3)
statement block 3;
:
:
else if (condition)
statement block n;
else
default statement;
Else - if Ladder Statement
If(condition1)
Default Statements;
True
False
Statements1;
Else if(condition2)
True
Statements2;
False
Else if(condition3)
Statements3;
False
True
Else - if Ladder Example
#include <stdio.h>
void main ()
{
int mark;
printf ("Enter mark:");
scanf ("%d", &mark);
if (mark <= 100 && mark >= 70)
printf ("n Distinction");
else if (mark >= 60)
printf("n First class");
else if (mark >= 50)
printf ("n Second class");
else
printf ("Fail");
}
Output
Enter mark: 75
Distinction
Switch Statement
Syntax
switch ( expression )
{
case value1: program statement;
......
break;
case value2: program statement;
.......
break;
…….
…….
case valuen: program statement;
.......
break;
default: program statement;
.......
break;
}
Switch Statement
Switch (Expression)
Case 1 Statements
Case 2 Statements
Case 3 Statements
Case 4 Statements
Switch Statement Example
#include <stdio.h>
void main ()
{
int num1, num2, result;
char operator;
printf ("Enter two numbers:");
scanf ("%d %d", &num1, &num2);
printf ("Enter an operator:");
scanf ("%c", &operator);
switch (operator)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
result = num1 / num2;
break;
default:
printf ("n unknown operator");
break;
}
printf (“Result=%d", result);
}
Output
Enter two numbers:10 20
Enter an operator:+
Result=30
Switch Statement Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[100];
int i,count=0;
clrscr();
printf("Enter line of text:");
gets(st);
for(i=0;st[i]!='0';i++)
{
switch(st[i])
{
case 'a': count++;
break;
case 'e': count++;
break;
case 'i': count++;
break;
case 'o': count++;
break;
case 'u': count++;
break;
}
}
printf("n Number of vowels: %d",count);
getch();
}
Output
Enter line of text: Hello World
Number of vowels: 3
goto statement
•The goto statement used to transfer the program control unconditionally from
one statement to another statement.
•The general usage is as follows:
goto label; Label:
………… …………
.............. …………
………… …………
………… …………
Label: Statement; goto label;
…………
•The goto requires a label in order to identify the place where the branch is to
be made.
•A label is a valid variable name followed by a colon.
goto statement example
#include <stdio.h>
void main ()
{
int n, sum = 0, i = 0;
printf ("Enter a number:");
scanf ("%d", &n);
inc: i++;
sum += i;
if (i < n)
goto inc;
printf ("n 1+2+3+…+%d = %d",n,sum)
}
Output
Enter a number:5
1+2+3+…+5=15
Looping statements
• The test may be either to determine whether the i has repeated the
specified number of times or to determine whether the particular
condition has been met.
• Type of Looping Statements are
• while statement
• do-while statement
• for statement
while statement
Syntax
while (test condition)
{
body of the loop;
}
While
(test
condition)
Body of the i;
False
True
while statement example
#include<stdio.h>
void main()
{
int n,x,sum=0;
printf("Enter a number: ");
scanf("%d",&n);
while(n>0)
{
x=n%10;
sum=sum+x;
n=n/10;
}
printf("Sum of digits of a number=%d",sum);
}
Output
Enter a number: 275
Sum of digits of a number=14
while statement example
#include<stdio.h>
void main()
{
int num,r,sum=0,temp;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
while(num!=0)
{
r=num%10;
sum=sum+(r*r*r);
num=num/10;
}
if(sum==temp)
printf("%d is an Armstrong number“
,temp);
else
printf("%d is not an Armstrong number“
,temp);
}
Output
Enter a number: 275
275 is an Armstrong number
Enter a number: 153
153 is an Armstrong number
do..while statement
• Since the body of the i is executed first and then the i condition is
checked we can be assured that the body of the i is executed at least
once.
Syntax
do
{
body of the loop;
}
while (test condition);
do..while statement
While
(test
condition)
Body of the loop
False
True
do
do..while statement example
#include<stdio.h>
void main()
{
int num=0, rev_num=0;
printf(“Enter the number:”);
scanf(“%d”,&num);
do
{
ld=num%10;
rev_num=rev_num*10+ld;
num=num/10;
} while(num>0);
printf(“nReversed number is %d”,rev_num);
}
Output
Enter the number:275
Reversed number is 572
while and do..while comparison
While Do…while
1) Syntax:
while(condition)
{
Body of the loop
}
1) Syntax:
do
{
Body of the loop
}while(condition);
2) This is decision making and
looping statement
2) This is also -decision making
and looping statement
3) This is the top tested loop 3) This is the bottom tested loop
4)Loop will not be executed if the
condition is false in first check
4) Loop will be executed atleast
once even though the condition is
false in first check
for statement
■ The for loop is most commonly and popularly used looping statement in C. The
for loop allows us to specify three things about the loop control variable i in a
single line. They are,
■ Initializing the value for the i
■ Condition in the i counter to determine whether the loop should continue or
not
■ Incrementing or decrementing the value of i counter each time the program
segment has been executed.
Syntax
for(initialization; test condition;increment/decrement)
{
body of the loop;
}
for statement
test condition
Initialization;
False
True
Increment/Decrement;
Body of the loop
for statement example
// Number 1 to 10 divisible by 2 but not
divisible by 3 and 5
#include<stdio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i%2==0&&i%3!=0&&i%5!=0)
printf("%dn",i);
}
}
Output
2
4
8
for statement example
//12+22+32+…. n2
#include<stdio.h> //<math.h>
void main()
{
int n, i,sum=0;
printf(“Enter the number:”);
scanf(“%d”, &n);
for(i=1;i <= n;i++)
{
sum = sum + i*i; //pow(i,2)
}
printf(“Sum of series=%d”,sum);
}
Output
Enter the number:5
Sum of series=55
break statement
■ Sometimes while executing a loop it becomes desirable to skip a part of
the loop or quit the loop as soon as certain condition occurs.
■ For example consider searching a particular number in a set of 100
numbers. As soon as the search number is found it is desirable to
terminate the loop.
■ C language permits a jump from one statement to another within a loop
as well as to jump out of the loop.
■ The break statement allows us to accomplish this task. A break statement
provides an early exit from for, while, do and switch constructs.
■ A break causes the innermost enclosing loop or switch to be exited
immediately.
break statement
#include<stdio.h>
void main()
{
int mark, i=0,sum=0;
float avg;
printf(“Enter the marks, -1 to end:”);
while(1)
{
scanf(“%d”, &mark);
if(mark == -1)
break;
sum+=mark;
i++;
}
avg=(float)sum/i;
printf(“nThe average marks is: %f”, avg);
}
Output
Enter the marks, -1 to end:
55
22
11
66
-1
The average marks is:38.500000
continue statement
■During loop operations it may be necessary to skip
a part of the body of the loop under certain
conditions.
■Like the break statement C supports similar
statement called continue statement.
■The continue statement causes the loop to be
continued with the next iteration after skipping
any statement in between.
continue statement
#include < stdio.h >
void main()
{
int i, num, sum=0;
printf(“Enter the integer:”);
for (i = 0; i < 5; i++)
{
scanf(“%d”, &num);
if(num < 0)
{
printf(“You have entered a negative numbern”);
continue;
}
sum+=num;
}
printf(“Sum of positive numbers entered = %d”,sum);
}
Output
Enter the integer:11 22 33 -1
You have entered a negative number
44
Sum of positive numbers entered =110
break and continue comparison
Break Continue
1) Syntax:
break;
1) Syntax:
continue;
2) Takes the control to outside of
the loop
2) Takes the control to beginning
of the loop
3) It is used in switch statement 3) It is not used in switch
statement
4) Example:
for(i=0;i<n;i++)
{
if(i==3)
break;
}
4) Example:
for(i=0;i<n;i++)
{
if(i==3)
continue;
}
Input and Output Functions
Input and Output Functions
Unformatted
Functions
Formatted Functions
scanf()
printf()
getch()
getche()
getchar()
gets()
putch()
putchar()
puts()
Formatted Functions
Formatted Input:
• Input data is arranged in a particular format
• I/P values are taken by using scanf function
• Syntax:
• scanf(“control string”,arg1,arg2…argn) ;
control string - includes format specifications and optional number
specifying field width and the conversion character %
arg1,arg2,… - address of locations where the data are stored
 Example: scanf(“%3d%2d”,&a,&b);
An Example Program
# include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2;
clrscr();
printf (“Enter two values:”) ;
scanf(“%3d%4d”, &num1, &num2);
printf (“nThe Entered Values are:%d %d”, num1, num2) ;
getch();
}
Output 1:
Enter two values: 1342 2422
The Entered Values are: 134 2
Output 2:
Enter two values: 134 2422
The Entered Values are: 134 2422
An Example Program
# include<stdio.h>
#include<conio.h>
void main ( )
{
float n1, n2, n3;
clrscr();
printf (“Enter three values:”) ;
scanf(“%f%f%f”, &n1,&n2,&n3);
printf (“nThe Entered Values are:%ft%ft%f”, n1, n2, n3) ;
getch();
}
Output:
Enter three values: 123.44 4.7 678
The Entered Values are:123.440000 4.700000 678.000000
An Example Program
#include <stdio.h>
#include <conio.h>
void main()
{
float c, f;
clrscr();
printf("Enter temp in Centigrade: ");
scanf("%f",&c);
f = ( 1.8 * c ) + 32;
printf("Temp in Fahrenheit: %0.2f",f);
getch();
}
Output:
Enter temp in Centigrade: 95.6
Temp in Fahrenheit: 204.08
An Example Program
# include<stdio.h>
#include<conio.h>
void main ( )
{
char s1[10],s2[10];
clrscr();
printf (“Enter two strings:”) ;
scanf(“%3s%2s”,s1,s2);
printf (“nThe Entered Values are:%st%s”,s1,s2) ;
getch();
}
Output:
Enter two strings : hello world
The Entered Values are:hel lo
Formatted Functions
Formatted Output:
• printf statement displays the information required to user
with specified format
• Syntax:
printf(“control string”,arg1,arg2…argn) ;
control string - field format which includes format
specifications and optional number specifying field width and
the conversion character %, blanks, tabs and newline.
arg1,arg2,… - name of the variables
Example: printf(“%dt%fn”,sum1,sum2);
Format for various output
Flag output justification
+ (right justification) - (left justification)
Width Specifier minimum field width for an output value
TYPE FORMAT EXPLANATION
Integer %wd w-width
Float %w.cf w-width
c-no. of digits after decimal point
String %w.cs w-width of total characters
c-no. of characters to display
Example
• INTEGER
printf(“%d”,12345); 12345
printf(“%3d”,12345); 12345
printf(“%7d”,12345); 12345
printf(“%-7d”,12345); 12345
• FLOAT
printf(“%f”,123.45); 123.450000
printf(“%4.2f”,123.45); 123.45
printf(“%9.3d”,12345); 123.450
• STRING
printf(“%s”,”Hello World”); Hello World
printf(“%6.2s”,”Hello World”); He
printf(“%1.2s”,”Hello World”); He
Input / Output functions
#include<stdio.h>
void main()
{
int i;
float f;
char c;
double d;
printf("Enter value for i,f,c,d:");
scanf("%d %f %c %lf",&i,&f,&c,&d);
printf(“i=%dnf=%fnc=%cnd=%lf",i,f,c,d);
}
Output
Enter value for i,f,c,d: 10 2.3 A 5.6
i=10
f=2.300000
c=A
D=5.600000
Formatted & unformatted I/O
Fundamental
Data Type
Data Type
Conversion Symbol+Format
Specifier
Integer short integer %d or %i
short unsigned %u
long signed %ld
long unsigned %lu
unsigned hexadecimal %X or %x
unsigned octal %o
Real float %f or %g
double %lf
Character character %c
string %s
Unformatted Functions
Unformatted Input
getch() & getche()
 read a alphanumeric characters from the standard input
device such as the keyboard
 The character entered is not displayed by getch() function
Example : getch() & getche()
# include<stdio.h>
#include<conio.h>
void main ( )
{
clrscr();
printf (“Enter two alphabets:”) ;
getche();
getch();
}
Output:Enter two alphabets:A
Unformatted Functions
getchar()
• read a character type data from the standard input device
such as the keyboard
• Reads one character at a time till user press the enter key
Example : getchar()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char c;
clrscr();
printf (“Enter a character:”) ;
c=getchar();
printf(“c=%c”,c);
getch();
}
Output: Enter a character :A
c=A
Unformatted Functions
gets()
• read a string from the standard input device such as the
keyboard until user press the enter key
Example : gets()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char str[10];
clrscr();
printf (“Enter a string:”) ;
gets(str);
printf(“String=%s”,str);
getch();
}
Output: Enter a string :Hello
String=Hello
Unformatted Functions
putch() & putchar()
• Prints any alphanumeric character taken by the standard
input device such as the keyboard
Example:
char ch=„X‟;
putch(ch); or putchar(ch);
Output: X
Unformatted Functions
puts()
• prints the string or character array
Example : puts()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char str[10];
clrscr();
printf (“Enter a string:”) ;
gets(str);
printf (“Entered string:”) ;
puts(str);
getch();
}
Output: Enter a string :Hello
Entered string:Hello

Contenu connexe

Tendances

C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
Introduction to c language
Introduction to c languageIntroduction to c language
Introduction to c languageRavindraSalunke3
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageAbhishek Dwivedi
 
C language
C languageC language
C languageSMS2007
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageVincenzo De Florio
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language CourseVivek chan
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)Dushmanta Nath
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 

Tendances (20)

C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Cbasic
CbasicCbasic
Cbasic
 
C program
C programC program
C program
 
C programming language
C programming languageC programming language
C programming language
 
Introduction to c language
Introduction to c languageIntroduction to c language
Introduction to c language
 
C Programming
C ProgrammingC Programming
C Programming
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
 
C programming
C programmingC programming
C programming
 
C language
C languageC language
C language
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
C programming
C programmingC programming
C programming
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 

Similaire à Unit ii

Similaire à Unit ii (20)

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
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
C language unit-1
C language unit-1C language unit-1
C language unit-1
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
Basics of C Prog Lang.pdf
Basics of C Prog Lang.pdfBasics of C Prog Lang.pdf
Basics of C Prog Lang.pdf
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
 
C programming
C programmingC programming
C programming
 
c++
 c++  c++
c++
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
8844632.ppt
8844632.ppt8844632.ppt
8844632.ppt
 
Chapter 1: Introduction
Chapter 1: IntroductionChapter 1: Introduction
Chapter 1: Introduction
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C.pdf
C.pdfC.pdf
C.pdf
 
Introduction of c programming unit-ii ppt
Introduction of  c programming unit-ii pptIntroduction of  c programming unit-ii ppt
Introduction of c programming unit-ii ppt
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
SPC Unit 2
SPC Unit 2SPC Unit 2
SPC Unit 2
 

Dernier

ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxAvaniJani1
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 

Dernier (20)

Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptx
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 

Unit ii

  • 2. What is C? • Language written by Brian Kernighan and Dennis Ritchie • C has been used as a general – purpose language because of its popularity • It was written to become first “portable” language
  • 3. Why use C? • Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: • Operating Systems • Language Compilers • Assemblers • Text Editors • Print Spoolers • Network Drivers • Modern Programs • Data Bases • Language Interpreters • Utilities Mainly because of the portability that writing standard C programs can offer
  • 4. History • 1960 : - • ALGOL was found by International group of computer users. • COBOL was found for commercial application usage. • FORTRAN was found for scientific applications. • In 1967: - • Basic Combined Programming Language (BCPL) • developed by Martin Richards at Cambridge University. • a single language which can program all possible applications, • In 1970: - • a language called B was developed by Ken Thompson at AT & T’s Bell Labs.
  • 5. History • In 1972: - • Dennis Ritchie at Bell Labs developed a language with some additional features of BPCL and B called C. • In 1978: - • Publication of The C Programming Language by Kernighan & Ritchie caused a revolution in the computing world. • In 1983: - • the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late 1988.
  • 6. Why C Still Useful? • C characteristics:  Highly structured language  Handle bit-level operations  Machine independent language-highly portable  Supports variety of data types and powerful set of operators  Supports dynamic memory management by using concept of pointers • C is used to develope:  System software - Compilers, Editors, embedded systems  data compression, graphics and computational geometry, utility programs  databases, operating systems, device drivers, system level routines  there are zillions of lines of C legacy code  Also used in application programs
  • 7. Programming languages • Some understandable directly by computers • Others require “translation” steps • Various programming languages • Machine language • Assembly language • High-level language • Machine language • Natural language of a particular computer • Consists of strings of numbers(1s, 0s) • Instruct computer to perform elementary operations one at a time • Machine dependent
  • 8. Programming languages • Assembly Language • English like abbreviations • Assemblers: • Translators of programs • Convert assembly language programs to machine language. • E.g. add overtime to base pay and store result in gross pay LOAD BASEPAY ADD OVERPAY STORE GROSSPAY
  • 9. Programming languages • High-level languages • To speed up the programming process • Single statements for accomplishing substantial tasks • Compilers - convert high-level programs into machine language • E.g. add overtime to base pay and store result in gross pay grossPay = basePay + overtimePay
  • 10. Basics of C Environment • C systems consist of 3 parts • Environment • Language • C Standard Library • Development environment has 6 phases  Edit - Writing the source code by using some IDE or editor  Pre-processor - Already available routines  Compile - translates or converts source to object code for a specific platform ie., source code -> object code  Link - resolves external references and produces the executable module  Load – put the program into the memory  Execute – runs the program
  • 11. Basics of C Environment Editor DiskPhase 1 Program edited in Editor and stored on disk Preprocessor DiskPhase 2 Preprocessor program processes the code Compiler DiskPhase 3 Creates object code and stores on disk Linker DiskPhase 4 Links object code with libraries and stores on disk
  • 12. Basics of C Environment LoaderPhase 5 Puts program in memory Primary memory CPUPhase 6 Takes each instruction and executes it storing new data values Primary memory
  • 13. Executing a C Program Steps involved in execution are • Creating the program • Compiling the program • Linking the program with functions that are needed from the C library • Executing the program
  • 14. Executing a C Program Edit Program Source Code Compile Object Code Link Object Code Executable Library Files
  • 15. Basics Structure of C Program Documentation section Link section Definition section Global declaration section main() function section { Declaration part Executable part } Subprogram section (user defined function)
  • 16. Simple C Program /* A first C Program*/ #include <stdio.h> void main() { printf("Hello World n"); }
  • 17. Simple C Program • Line 1: #include <stdio.h> • As part of compilation, the C compiler runs a program called the C preprocessor. The preprocessor is able to add and remove code from your source file. • In this case, the directive #include tells the preprocessor to include code from the file stdio.h. • This file contains declarations for functions that the program needs to use. A declaration for the print function is in this file.
  • 18. Simple C Program • Line 2: void main() • This statement declares the main function. • C program can contain many functions but must always have one main function. • A function is a self-contained module of code that can accomplish some task. • Functions are examined later. • "void" specifies the return type of main. In this case, nothing is returned to the operating system.
  • 19. Simple C Program • Line 3: { • This opening bracket denotes the start of the program.
  • 20. Simple C Program • Line 4: printf("Hello Worldn"); • printf is a function from a standard C library that is used to print strings to the standard output, normally your screen. • The "n" is a special format modifier that tells the printf to put a line feed at the end of the line. • If there were another printf in this program, its string would print on the next line.
  • 21. Simple C Program • Line 5: } • This closing bracket denotes the end of the program.
  • 22. C Character Set • Characters are the basic building blocks in C program, equivalent to ‘letters’ in English language • Characters can be used to form words, numbers and expressions • Characters in C are grouped into following categories • Letters ex:a…z,A…Z • Digits ex:0…9 • Special characters ex:,,&,@,_,+,-,….. • White spaces ex:blank space horizontal tab new line…….
  • 23. C Tokens • In a passage of text, individual words and punctuation marks are called tokens • In a C source program, the basic element recognized by the compiler is the "token." • C Tokens are  Keywords - int, float, while  Identifiers - sum, main  Constants - 100, -55.5  Strings - “ABC”, “Hello”  Operators - +, -, *, /, ++  Special symbols - {, },[, ]
  • 24. Keywords • All keywords are reserved words have fixed meanings and these meanings cannot be changed • Have special meaning to the compiler, cannot be used as identifiers in our program. • Keywords serve as basic building blocks for program statement • Keywords must be written in lowercase • Displayed in BLUE color in MS Visual C++
  • 25. Some Keywords Keywords auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
  • 26. Identifiers • Refer to the names of variables, functions and arrays • User defined names and consist of a letters and digits, with a letter as a first character Rules for Identifiers • First character must be an alphabet • Must consist of only letters, digits and underscore • Only first 32 characters are significant • Cannot use a keyword • Must not contain white space • Case sensitive-Identifier Sub differ from sub
  • 27. Identifiers Examples of legal identifier: Student_age, Item10, counter, number_of_character Examples of illegal identifier Student age (embedded blank) continue (continue is a reserved word) 10thItem (the first character is a digit) Principal+interest (contain operator character +)
  • 28. 1. Avoid excessively short and cryptic names such as x or wt. Instead, use a more readable and descriptive names such as student_major and down_payment. 2. Use underscores or capital letters to separate words in identifiers that consist of two or more words. Example, student_major or studentMajor are much easier to read than studentmajor. Recommendations forConstructingIdentifiers
  • 29. Constants • Constants refers to fixed values that do not change during the execution a program Types of Constants Numeric Constants  Integer Constants - 234, 045, 0x2A, 0X3B  Real Constants - 2.345, 0.64e-2 Character Constants  Single Character Constants ‘5’, ‘A’  String Constants “Hello”
  • 30. IntegerConstant Positive or negative whole numbers with no fractional part Optional + or – sign before the digit. It can be decimal (base 10), octal (base 8) or hexadecimal (base 16) Hexadecimal is very useful when dealing with binary numbers Example: const int MAX_NUM = 10; const int MIN_NUM = -90; const int Hexadecimal_Number = 0xf87;
  • 31. RulesforDecimalIntegerConstant 1. Decimal integer constants must begin with a nonzero decimal digit, the only exception being 0, and can contain decimal digital values of 0 through 9. An integer that begins with 0 is considered an octal constant 2. If the sign is missing in an integer constant, the computer assumes a positive value. 3. Commas are not allowed in integer constants. Therefore, 1,500 is illegal; it should be 1500. Example of legal integer constants are –15, 0, +250 and 7550 Example of illegal constants 0179 is illegal since the first digit is zero 1F8 is illegal since it contains letter ‘F’ 1,700 is illegal since it contains comma
  • 32. FloatingPointConstant • Positive or negative decimal numbers with an integer part(optional), a decimal point, and a fractional part (optional) Example 2.0, 2., 0.2, .2, 0., 0.0, .0 • It can be written in conventional or scientific way • 20.35 is equivalent to 0.2035E+2 (0.2035 x 102 ) • 0.0023 is equivalent to 0.23e-2 (0.23 x 10-2) • E or e stand for “exponent” • In scientific notation, the decimal point may be omitted. Example: -8.0 can rewritten as -8e0
  • 33. Floating Point Constant • C support 3 type of Floating-point: float (4 bytes), double (8 bytes), long double (16 bytes) • By default, a constant is assumed of type double • Suffix f(F) or l(L) is used to specify float and long double respectively Example: const float balance = 0.125f; const float interest = 6.8e-2F const long double PI = 3.1412L; const long double planet_distance = 2.1632E+30l
  • 34. • A character enclosed in a single quotation mark • Example: • const char letter = ‘n’; • const char number = ‘1’; • printf(“%c”, ‘S’); • Output would be: S How to write a single quotation mark? ‘’’ is ambiguous, so escape character – back slash Example: ‘’’ Character Constants
  • 35. String Literals • A sequence of any number of characters surrounded by double quotation marks. • Example: • “Human Revolution” • How to write special double quotation mark? • “”” is ambiguous, so use escape character • Example: printf(“He shouted, “Run!””); output: He shouted, “Run!” - The escape character along with any character that follow it is called Escape Sequence
  • 36. BackslashCharacter Constants Escape Sequence Name Meaning a Alert Sounds a beep b Back space Backs up 1 character f Form feed Starts a new screen of page n New line Moves to beginning of next line r Carriage return Moves to beginning of current line t Horizontal tab Moves to next tab position v Vertical tab Moves down a fixed amount Back slash Prints a back slash ’ Single quotation Prints a single quotation ” Double quotation Prints a double quotation ? Question mark Prints a question mark
  • 37. Backslash Character Example Program #include<stdio.h> void main() { printf("nabc"); printf("rdef"); printf("bghin"); printf("HaitHello"); } Output deghi Hai Hello
  • 38. Variables • A variable is a data name used for storing a data value • The value may be changed during program execution Rules for defining variables • Must begin with a character • Should not be a C keyword • May be combination of lower and upper characters • Should not start with a digit • Maximum characters upto 31 characters Example Sum, avg_wt, item
  • 39. Declaration of Variables • Syntax for declaring a variable is as follows data-type v1,v2,….vn; Example int i,j,sum; float avg; double ratio; unsigned int fact;
  • 40. DATATYPE • Datatype is the most important attributes of an identifier. It detemines the possible values. • Classification of Datatypes -Basic Datatypes -Derived datatypes -User-defined datatypes Basic/Primitive Datatypes: Character (char) Integer (int) Single-precision floating point (float) Double-precision floating point (double) No value available (void) Derived Datatypes: Array type (char[], int[]) Pointer type (char*, int*) Functiontype (int(int,int), float(int))
  • 41. • User-defined datatypes It provides flexibility to the user to create new datatypes. Newly created called User-defined datatypes. Structure Union Enumeration Syntax: data_type variable_name Example: int age; char ch; float avg; int a,b,c;
  • 42. Data Types Initializing Variables • Variables declared can be assigned or initialized using an assignment operator ‘=‘ Syntax: variable_name=constant; or data_type variable_name=constant; Example: int age; char ch=‘A’; age=10; float avg=10.5;
  • 43. Data Types in C Type Keyword Byte s Range character char 1 -128...127 integer int 2 -32768...32767 short integer short 2 -32768...32767 long integer long 4 -2,147,483,648...2,147,438,647 long long integer long long 8 -9223372036854775808 … 9223372036854775807 unsigned character unsigned char 1 0...255 unsigned integer unsigned int 2 0...4,294,967,295 unsigned short integer unsigned short 2 0...65535 unsigned long integer unsigned long 4 0...4,294,967,295 single-precision float 4 1.2E-38...3.4E38 double- precision double 8 2.2E-308...1.8E308
  • 44. Expressions • Operands It specifies an entity on which an operation is to be performed. It may be a variable name, a constant, a function call or a macro name eg: a=printf(“Hello”)+2 • Operators It specifies the operation to be applied to its operands.
  • 45. SimpleExpressionand Compound Expression • An Expression has only one operator called Simple expression eg: a+2 • An Expression has more than one operator called Compound Expression. eg: b=2+3*5
  • 46. Properties Of Operators • Precedence • Associativity Precedence: • Priority allotted to the operator • Each operator in C has a precedence associated with it. • In compound expression, if the operator involved different precedence, the operator of highest precedence operates first. Ex: 8+9*2-10 =8+18-10 =26-10 =16
  • 47. Associativity: • Expression having operators with equal precedence • associativity property decides which operation is performed first • In compound expression, when several operators of the same precedence appear together, the operators are evaluated according to their associativity. Types: Left to Right Right to left 12*4/8%2 x=8+5%2 = 48/8%2 =8+1 = 6%2 =9 = 0
  • 48. • Operators has same precedence- same associativity • If operators are left-to-right, applied in a left-to-right order • If operators are right-to-left, applied in a right-to-left order • Multiplication and division operators are left-to-right associative
  • 49. Operators • An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations Classification of Operators: Number of operands on which an operator operates The role of an operator Classification based on Number of operands • Unary- it operates on only one operand Eg: &, sizeof operator, !, ~, ++, -- • Binary – it operates on two operands eg: *, /, <<, ==,&&, & • Ternary- it operates on three operands eg: ?:
  • 50. Classification based on Role of Operator Arithmetic Operators +, -, *, /, % Relational Operators <, <=, >, >=, ==, != Logical Operators &&, ||, ! Assignment Operators = Increment and Decrement Operators ++,-- Conditional Operators ?= Bitwise Operators &,|, ^, <<, >> Special Operators ,, sizeof, &, * ., ->
  • 51. Arithmetic Operators C Operation Algebraic C Addition (+) f + 7 f + 7 Subtraction (-) p – c p – c Multiplication (*) bm b * c Division (/) x / y x / y Modulus (%) r mod s r % s
  • 52. Arithmetic Operators Example Program #include <stdio.h> #include <conio.h> void main() { int x,y, a,s,m,d,r; clrscr(); printf(“Enter two numbers:”); scanf(“%d%d”,&x,&y); a = x + y; printf(“a = %dn",a); s = x - y; printf(“s = %dn",s); m = x * y; printf(“m = %dn",m); d = x / y; printf(“d = %dn",d); r = x % y; printf("r = %dn",r); } Output Enter two numbers:10 20 a = 30 s = -10 m = 200 d = 0 r = 10
  • 53. Binary Arithmetic operators • It is used in 3 different modes Integer mode
  • 54. Relational Operators • Greater than > • Less than < • Greater than or equal to >= • Less than or equal to <= • Equal to == • Not equal to != Condition true return 1 Condition false return 0
  • 55. Relational Operators Example Program #include<stdio.h> #include<conio.h> void main() { int x,y,r; clrscr(); printf(“Enter 2 nos. x & y:”); scanf(“%d%d”,&x,&y); r=(x==y); printf("%dn",r); r=(x!=y); printf("%dn",r); r=(x>y); printf("%dn",r); r=(x>=y); printf("%dn",r); r=(x<y); printf("%dn",r); r=(x<=y); printf("%dn",r); } Output Enter 2 nos. x & y: 10 20 0 1 0 0 1 1
  • 56. Logical Operators Operator Example Meaning && (Logical AND) (Condition1) && (Condition2) Both conditions should satisfy to proceed || (Logical OR) (Condition1) || (Condition2) Either one condition satisfied proceed to next operation ! (Logical NOT) !(Condition1) The condition not satisfied proceed to next operation
  • 57. Logical Operators Example if ((x>20) && (x<100)) printf("x is inside open interval 20- 100"); if ((x<5) || (x>20)) printf("x is not inside closed interval 5-20"); if (!(x>20)) printf("x is smaller or equal to 20");
  • 58. Logical Operators Example //Greatest of 3 numbers using logical operators #include<stdio.h> #include<conio.h> void main() { int x,y,z; clrscr(); printf(“Enter 3 nos. x ,y,z:”); scanf(“%d%d%d”,&x,&y,&z); if((x>y)&&(x>z)) printf(“x is greatest”); if((y>x)&&(y>z)) printf(“y is greatest”); if((z>x)&&(z>y)) printf(“z is greatest”); } Output Enter 3 nos. x ,y,z: 40 20 30 x is greatest Enter 3 nos. x ,y,z: 10 40 30 y is greatest Enter 3 nos. x ,y,z: 10 20 30 z is greatest
  • 59. Assignment operators Operator Example Meaning = 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
  • 60. Increment/Decrement operators Operator Example Meaning ++ a++ First does the operation and increments the value + + ++a First Increments the value and does the operation -- a-- First does the operation and decrements the value -- --a First decrements the value and does the operation
  • 61. Increment/Decrement operators Program void main() { int c; c = 5; printf(“%dn”, c); printf(“%dn”, c++); printf(“%dnn”, c); c = 5; printf(“%dn”, c); printf(“%dn”, ++c); printf(“%dn”, c); } Output 5 5 6 5 6 6 c=10 x=c++ + ++c; x=? C=?
  • 62. Conditional Operator Conditional Operator (?:) is ternary operator (demands 3 operands), and is used in certain situations, replacing if-else condition phrases. Conditional operator’s syntax is: condition?expression1:expression2; If condition is true, expression1 is executed. If condition is false, expression2 is executed. Example: int a, b, c; ... c = a > b ? a : b; // if a>b "execute" a, else b and assign the value to c
  • 63. Bitwise Operators Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise XOR ~ One‟s Complement << Left Shift >> Right Shift
  • 64. Bitwise Operators Example Let A=0x56 and B=0x32 A & B ( Bitwise AND ) 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 --------------------- 0 0 0 1 0 0 1 0 --------------------- A ^ B ( Bitwise XOR ) 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 --------------------- 0 1 1 0 0 10 0 --------------------- A | B ( Bitwise OR ) 0 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 --------------------- 0 1 1 1 0 1 1 0 --------------------- ~ A ( Complement ) 0 1 0 1 0 1 1 0 --------------------- 1 0 1 0 1 0 0 1 ---------------------
  • 65. Bitwise Operators Example Let A=0x56 A << 2 ( Left Shift ) 0 1 0 1 0 1 1 0 << 2  0 1 0 1 0 1 1 0 0 0 ( 0x158 ) A >> 2 ( Right Shift ) 0 1 0 1 0 1 1 0 >> 1  0 1 0 1 0 1 1 ( 0x2B) NOTE: For multiply given number by two, left shifted by one time, i.e., a<<1 For divide given number by two, right shifted by one time, i.e., a>>1
  • 66. Bitwise Operators Example Write a program to shift inputed data by three bits left and right Program void main() { int x,y; clrscr(); printf(“Enter value of x:”); scanf(“%d”,&x); y=x<<3; printf(“Left shifted data=%d”,y); printf(“Right shifted data=%d”,x>>3); } Output: Enter value of x:16 Left shifted data=128 Right shifted data=2
  • 67. Special Operators • C supports some special operators such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->). • The size of and the comma operators are discussed here. The remaining operators will see in pointer chapter Comma Operator • The comma operator can be used to link related expressions together. A comma-linked list of expressions are evaluated left to right and value of right most expression is the value of the combined expression. Example value = (x = 10, y = 5, x + y); for (n=1, m=10, n <=m; n++,m++) t = x, x = y, y = t;
  • 68. Special Operators Sizeof Operator • The operator sizeof gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier. • The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program. Example int sum; m = sizeof(sum);  2 n = sizeof(long int);  4 k = sizeof(235L);  4
  • 69. Expressions Arithmetic Expressions • An expression is a combination of variables constants and operators written according to the syntax of C language. Algebraic Expression C Expression a x b – c a * b – c (m + n) (x + y) (m + n) * (x + y) 3x2 +2x + 1 3*x*x+2*x+1
  • 70. Expressions Evaluation of Expressions • Expressions are evaluated using an assignment statement of the form Variable = expression; Variable is any valid C variable name. The expression is evaluated first and then replaces the previous value of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. Example x = a * b – c y = b / c * a z = a – b / c + d;
  • 71. Decision Making - Branching • Decision making statements are used to skip or to execute a group of statements based on the result of some condition. • The decision making statements are, − simple if statement − if…else statement − nested if − else … if ladder − switch statement − goto • These statements are also called branching statements
  • 73. Simple if - Example # include <stdio.h> void main () { int number; printf("Type a number:"); scanf("%d",&number); if (number < 0) number = -number; printf ("The absolute value is %d",number); } Output Type a number -50 The absolute value is 50
  • 74. if - else statement Syntax: if(condition) { True block statements; } else { False block statements; } if(condi tion) True Block Statement False True False Block Statements
  • 75. if – else Example # include <stdio.h> void main () { int num; printf ("Type a number:"); scanf ("%d", &num); if (number < 0) printf(“The number is negative”); else printf(“The number is positive”); } Output Type a number 50 The number is positive
  • 76. if – else Example #include<stdio.h> void main() { Int num; printf ("Enter a number:"); scanf ("%d",&num); if (num%2==0) printf ("The number is EVEN.n"); else printf ("The number is ODD.n"); } Output Enter a number 125 The number is ODD
  • 77. Nested if Statement • if statement may itself can contain another if statement is known as nested if statement. Syntax: if(condition1) { if(condition2) { True block statement of condition1 & 2; } else { False block statement of condition2; } } else { False block statements of condition1; }
  • 78. Nested if Statement condition1 True Block Statements of condition 1 & 2; False True False Block Statements of condition 1; if(condition2) True False Block Statements of condition 2; False
  • 79. Nested if Example # include <stdio.h> void main() { int n1,n2,n3,big; printf (“Enter 3 numbers:"); scanf ("%d %d %d", &n1,&n2,&n3); if (n1 > n2) { if(n1 > n3) big = n1; else big = n3; } if(n2 > n3) big = n2; else big = n3; printf(“The largest number is: %d”,big); } Output Enter 3 numbers:10 25 20 The largest number is: 25
  • 80. Else - if Ladder Statement Syntax if (condition1) statement block 1; else if (condition2) statement block 2; else if (condition3) statement block 3; : : else if (condition) statement block n; else default statement;
  • 81. Else - if Ladder Statement If(condition1) Default Statements; True False Statements1; Else if(condition2) True Statements2; False Else if(condition3) Statements3; False True
  • 82. Else - if Ladder Example #include <stdio.h> void main () { int mark; printf ("Enter mark:"); scanf ("%d", &mark); if (mark <= 100 && mark >= 70) printf ("n Distinction"); else if (mark >= 60) printf("n First class"); else if (mark >= 50) printf ("n Second class"); else printf ("Fail"); } Output Enter mark: 75 Distinction
  • 83. Switch Statement Syntax switch ( expression ) { case value1: program statement; ...... break; case value2: program statement; ....... break; ……. ……. case valuen: program statement; ....... break; default: program statement; ....... break; }
  • 84. Switch Statement Switch (Expression) Case 1 Statements Case 2 Statements Case 3 Statements Case 4 Statements
  • 85. Switch Statement Example #include <stdio.h> void main () { int num1, num2, result; char operator; printf ("Enter two numbers:"); scanf ("%d %d", &num1, &num2); printf ("Enter an operator:"); scanf ("%c", &operator); switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 != 0) result = num1 / num2; break; default: printf ("n unknown operator"); break; } printf (“Result=%d", result); } Output Enter two numbers:10 20 Enter an operator:+ Result=30
  • 86. Switch Statement Example #include<stdio.h> #include<conio.h> #include<string.h> void main() { char st[100]; int i,count=0; clrscr(); printf("Enter line of text:"); gets(st); for(i=0;st[i]!='0';i++) { switch(st[i]) { case 'a': count++; break; case 'e': count++; break; case 'i': count++; break; case 'o': count++; break; case 'u': count++; break; } } printf("n Number of vowels: %d",count); getch(); } Output Enter line of text: Hello World Number of vowels: 3
  • 87. goto statement •The goto statement used to transfer the program control unconditionally from one statement to another statement. •The general usage is as follows: goto label; Label: ………… ………… .............. ………… ………… ………… ………… ………… Label: Statement; goto label; ………… •The goto requires a label in order to identify the place where the branch is to be made. •A label is a valid variable name followed by a colon.
  • 88. goto statement example #include <stdio.h> void main () { int n, sum = 0, i = 0; printf ("Enter a number:"); scanf ("%d", &n); inc: i++; sum += i; if (i < n) goto inc; printf ("n 1+2+3+…+%d = %d",n,sum) } Output Enter a number:5 1+2+3+…+5=15
  • 89. Looping statements • The test may be either to determine whether the i has repeated the specified number of times or to determine whether the particular condition has been met. • Type of Looping Statements are • while statement • do-while statement • for statement
  • 90. while statement Syntax while (test condition) { body of the loop; } While (test condition) Body of the i; False True
  • 91. while statement example #include<stdio.h> void main() { int n,x,sum=0; printf("Enter a number: "); scanf("%d",&n); while(n>0) { x=n%10; sum=sum+x; n=n/10; } printf("Sum of digits of a number=%d",sum); } Output Enter a number: 275 Sum of digits of a number=14
  • 92. while statement example #include<stdio.h> void main() { int num,r,sum=0,temp; printf("Enter a number: "); scanf("%d",&num); temp=num; while(num!=0) { r=num%10; sum=sum+(r*r*r); num=num/10; } if(sum==temp) printf("%d is an Armstrong number“ ,temp); else printf("%d is not an Armstrong number“ ,temp); } Output Enter a number: 275 275 is an Armstrong number Enter a number: 153 153 is an Armstrong number
  • 93. do..while statement • Since the body of the i is executed first and then the i condition is checked we can be assured that the body of the i is executed at least once. Syntax do { body of the loop; } while (test condition);
  • 95. do..while statement example #include<stdio.h> void main() { int num=0, rev_num=0; printf(“Enter the number:”); scanf(“%d”,&num); do { ld=num%10; rev_num=rev_num*10+ld; num=num/10; } while(num>0); printf(“nReversed number is %d”,rev_num); } Output Enter the number:275 Reversed number is 572
  • 96. while and do..while comparison While Do…while 1) Syntax: while(condition) { Body of the loop } 1) Syntax: do { Body of the loop }while(condition); 2) This is decision making and looping statement 2) This is also -decision making and looping statement 3) This is the top tested loop 3) This is the bottom tested loop 4)Loop will not be executed if the condition is false in first check 4) Loop will be executed atleast once even though the condition is false in first check
  • 97. for statement ■ The for loop is most commonly and popularly used looping statement in C. The for loop allows us to specify three things about the loop control variable i in a single line. They are, ■ Initializing the value for the i ■ Condition in the i counter to determine whether the loop should continue or not ■ Incrementing or decrementing the value of i counter each time the program segment has been executed. Syntax for(initialization; test condition;increment/decrement) { body of the loop; }
  • 99. for statement example // Number 1 to 10 divisible by 2 but not divisible by 3 and 5 #include<stdio.h> void main() { int i; for(i=1;i<=10;i++) { if(i%2==0&&i%3!=0&&i%5!=0) printf("%dn",i); } } Output 2 4 8
  • 100. for statement example //12+22+32+…. n2 #include<stdio.h> //<math.h> void main() { int n, i,sum=0; printf(“Enter the number:”); scanf(“%d”, &n); for(i=1;i <= n;i++) { sum = sum + i*i; //pow(i,2) } printf(“Sum of series=%d”,sum); } Output Enter the number:5 Sum of series=55
  • 101. break statement ■ Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs. ■ For example consider searching a particular number in a set of 100 numbers. As soon as the search number is found it is desirable to terminate the loop. ■ C language permits a jump from one statement to another within a loop as well as to jump out of the loop. ■ The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. ■ A break causes the innermost enclosing loop or switch to be exited immediately.
  • 102. break statement #include<stdio.h> void main() { int mark, i=0,sum=0; float avg; printf(“Enter the marks, -1 to end:”); while(1) { scanf(“%d”, &mark); if(mark == -1) break; sum+=mark; i++; } avg=(float)sum/i; printf(“nThe average marks is: %f”, avg); } Output Enter the marks, -1 to end: 55 22 11 66 -1 The average marks is:38.500000
  • 103. continue statement ■During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. ■Like the break statement C supports similar statement called continue statement. ■The continue statement causes the loop to be continued with the next iteration after skipping any statement in between.
  • 104. continue statement #include < stdio.h > void main() { int i, num, sum=0; printf(“Enter the integer:”); for (i = 0; i < 5; i++) { scanf(“%d”, &num); if(num < 0) { printf(“You have entered a negative numbern”); continue; } sum+=num; } printf(“Sum of positive numbers entered = %d”,sum); } Output Enter the integer:11 22 33 -1 You have entered a negative number 44 Sum of positive numbers entered =110
  • 105. break and continue comparison Break Continue 1) Syntax: break; 1) Syntax: continue; 2) Takes the control to outside of the loop 2) Takes the control to beginning of the loop 3) It is used in switch statement 3) It is not used in switch statement 4) Example: for(i=0;i<n;i++) { if(i==3) break; } 4) Example: for(i=0;i<n;i++) { if(i==3) continue; }
  • 106. Input and Output Functions Input and Output Functions Unformatted Functions Formatted Functions scanf() printf() getch() getche() getchar() gets() putch() putchar() puts()
  • 107. Formatted Functions Formatted Input: • Input data is arranged in a particular format • I/P values are taken by using scanf function • Syntax: • scanf(“control string”,arg1,arg2…argn) ; control string - includes format specifications and optional number specifying field width and the conversion character % arg1,arg2,… - address of locations where the data are stored  Example: scanf(“%3d%2d”,&a,&b);
  • 108. An Example Program # include<stdio.h> #include<conio.h> void main() { int num1, num2; clrscr(); printf (“Enter two values:”) ; scanf(“%3d%4d”, &num1, &num2); printf (“nThe Entered Values are:%d %d”, num1, num2) ; getch(); } Output 1: Enter two values: 1342 2422 The Entered Values are: 134 2 Output 2: Enter two values: 134 2422 The Entered Values are: 134 2422
  • 109. An Example Program # include<stdio.h> #include<conio.h> void main ( ) { float n1, n2, n3; clrscr(); printf (“Enter three values:”) ; scanf(“%f%f%f”, &n1,&n2,&n3); printf (“nThe Entered Values are:%ft%ft%f”, n1, n2, n3) ; getch(); } Output: Enter three values: 123.44 4.7 678 The Entered Values are:123.440000 4.700000 678.000000
  • 110. An Example Program #include <stdio.h> #include <conio.h> void main() { float c, f; clrscr(); printf("Enter temp in Centigrade: "); scanf("%f",&c); f = ( 1.8 * c ) + 32; printf("Temp in Fahrenheit: %0.2f",f); getch(); } Output: Enter temp in Centigrade: 95.6 Temp in Fahrenheit: 204.08
  • 111. An Example Program # include<stdio.h> #include<conio.h> void main ( ) { char s1[10],s2[10]; clrscr(); printf (“Enter two strings:”) ; scanf(“%3s%2s”,s1,s2); printf (“nThe Entered Values are:%st%s”,s1,s2) ; getch(); } Output: Enter two strings : hello world The Entered Values are:hel lo
  • 112. Formatted Functions Formatted Output: • printf statement displays the information required to user with specified format • Syntax: printf(“control string”,arg1,arg2…argn) ; control string - field format which includes format specifications and optional number specifying field width and the conversion character %, blanks, tabs and newline. arg1,arg2,… - name of the variables Example: printf(“%dt%fn”,sum1,sum2);
  • 113. Format for various output Flag output justification + (right justification) - (left justification) Width Specifier minimum field width for an output value TYPE FORMAT EXPLANATION Integer %wd w-width Float %w.cf w-width c-no. of digits after decimal point String %w.cs w-width of total characters c-no. of characters to display
  • 114. Example • INTEGER printf(“%d”,12345); 12345 printf(“%3d”,12345); 12345 printf(“%7d”,12345); 12345 printf(“%-7d”,12345); 12345 • FLOAT printf(“%f”,123.45); 123.450000 printf(“%4.2f”,123.45); 123.45 printf(“%9.3d”,12345); 123.450 • STRING printf(“%s”,”Hello World”); Hello World printf(“%6.2s”,”Hello World”); He printf(“%1.2s”,”Hello World”); He
  • 115. Input / Output functions #include<stdio.h> void main() { int i; float f; char c; double d; printf("Enter value for i,f,c,d:"); scanf("%d %f %c %lf",&i,&f,&c,&d); printf(“i=%dnf=%fnc=%cnd=%lf",i,f,c,d); } Output Enter value for i,f,c,d: 10 2.3 A 5.6 i=10 f=2.300000 c=A D=5.600000
  • 116. Formatted & unformatted I/O Fundamental Data Type Data Type Conversion Symbol+Format Specifier Integer short integer %d or %i short unsigned %u long signed %ld long unsigned %lu unsigned hexadecimal %X or %x unsigned octal %o Real float %f or %g double %lf Character character %c string %s
  • 117. Unformatted Functions Unformatted Input getch() & getche()  read a alphanumeric characters from the standard input device such as the keyboard  The character entered is not displayed by getch() function
  • 118. Example : getch() & getche() # include<stdio.h> #include<conio.h> void main ( ) { clrscr(); printf (“Enter two alphabets:”) ; getche(); getch(); } Output:Enter two alphabets:A
  • 119. Unformatted Functions getchar() • read a character type data from the standard input device such as the keyboard • Reads one character at a time till user press the enter key
  • 120. Example : getchar() # include<stdio.h> #include<conio.h> void main ( ) { char c; clrscr(); printf (“Enter a character:”) ; c=getchar(); printf(“c=%c”,c); getch(); } Output: Enter a character :A c=A
  • 121. Unformatted Functions gets() • read a string from the standard input device such as the keyboard until user press the enter key
  • 122. Example : gets() # include<stdio.h> #include<conio.h> void main ( ) { char str[10]; clrscr(); printf (“Enter a string:”) ; gets(str); printf(“String=%s”,str); getch(); } Output: Enter a string :Hello String=Hello
  • 123. Unformatted Functions putch() & putchar() • Prints any alphanumeric character taken by the standard input device such as the keyboard Example: char ch=„X‟; putch(ch); or putchar(ch); Output: X
  • 124. Unformatted Functions puts() • prints the string or character array
  • 125. Example : puts() # include<stdio.h> #include<conio.h> void main ( ) { char str[10]; clrscr(); printf (“Enter a string:”) ; gets(str); printf (“Entered string:”) ; puts(str); getch(); } Output: Enter a string :Hello Entered string:Hello

Notes de l'éditeur

  1. Program to find average of n numbers
  2. Program to find the sum of five positive integers