Programming in “ C ” Index
Basic Concepts required for Introduction to C
2
Introduction to C
4
Operators in C
20
Decision Control Structure
23
If Statement
If-Else Statement
24
If-Else-If Statement
25
Ternary Operator (ConditionalOperator)
34
ASCII
SwitchStatement
36
Loop Control Structure
42
While loop
43
Do-While loop
50
For-loop
52
Functions
65
Storage Classes in C
79
Pointers
81
Arrays
87
Introduction to Arrays
PassingArrayelementstoFunction
91
Multidimensional Arrays
97
Two Dimensional Arrays
Three Dimensional Arrays
100
String Functions
102
Structures
110
Union
116
Basic Concepts Required for Introduction to C
User language System language
(English language) (Language of 0’s and 1’s i.e.
Binary language)
Interpreter OS
(Mediator, which converts user language Into system language)
Introduction to Number system
There are two types of number system in a computer i.e. Decimal number system and Binary number system.
Decimal Number System: The decimal number contains 10 natural numbers from 0 to 9, which are used by human being.
Binary Number System: The binary number system contains only two numbers i.e. 0 and 1 which is used by compiler, because compiler cannot understand any other language except 0 and 1 in the form of electronic signals.0 1 0 1 0 1 0 1 0 1
ASCII
ASCII ranges from 0 to 255. A – American S – Standard C – Code for I – Information I – Interchange In ASCII language, A – 65 a – 97 B – 66 b – 98 | | | | | | Z – 90 z – 122
Conversion of Decimal number in to Binary number system 2 65 1 2 32 0 2 16 0 2 8 0 2 4 0 2 2 0 1 A 1 0 0 0 0 0 1 In System language, A= 1000001
Two directories called <stdio.h> and <conio.h> are always included before starting the ‘C’ program. These are included in the given way.#include<stdio.h> #include<conio.h> void main( ) { -- -- -- }
printf – To print on screen.
scanf - To get value from keyboard/user. stdio.h – standard input/output. header
This directory is included because printf() and scanf() functions are present in this directory and if this directory is not included, printing and scanning is not possible. conio.h – console input/output. header
This directory is included because clrscr() and getch() functions are present in this directory.
In C, semicolon (;) is used to terminate the statement.
In C,= Represents assignment operator
E.g. a=10 (here 10 is assigned to variable a. = = Represents equality
Steps of C-program using flowchart Representation
Datatype
int 10,20,4,9 int a, b; %d int a; a
float 18.84,20.54 float a, b; %f float a; a
char ‘a’, ‘i’, ‘b’ char a; %c char a; a
string “chester” char a[20]; %s char a[7]; a
START
INPUT
CALCULATE
STOP
START
a, b, c
c=a+b
Print c
STOP
10
18.84
c
chester
Introduction to ‘C’
Dennis Ritchie developed the ‘C’ language at AT & T Bell’s laboratory in 1972. It was originally written for
programmes under the operating system UNIX.
The early version written by Ken Thomson adopted in the form of a language by the initials BCPL which stands for Basic Combined Programming Language. To distinguish this language from BCPL, he termed it as
‘B’, the first character.
When the language was modified and was improved to its present state, the second letter of BCPL, ‘C’ was chosen to represent new version.
There is no single compiler for ‘C’. Many different organizations have written and implemented ‘C’
compiler.
Power, Portability, Performance and flexibility are the most important results for ‘C’ popularity.
‘C’ combines the features of both high level language which is the functionality of the assembly language.
Being a middle level language, it allows the manipulation of bits, bytes and the address directly make it more suitable for system programming and hence ‘C’ is mostly used for writing interpreters, compilers, assembler editions, database management.
Advantages of ‘C’
It is a structural programming language.
‘C’ source code is portable.
Being a middle level language suitable for commercial application.
‘C’ is designed so that compiler can translate a program into efficient machine instructions.For Normal language
‘C’ consist of
Rules for C Program
C is a case sensitive.Alphabets
Words
Sentences
Paragraphs
Alphabets
Digits
Special symbols
Constants
Variables
Keywords
Instructions
Programs
All keywords have to be in lowercase.
Keywords have fixed meaning and are reserved i.e. keyword if, int, char.Instructions about C program
‘C’ always start from main() [because ‘C’ compiler starts compiling always from main()function.
There should be {(opening brace) and }(closing brace) to indicate the start and the end of C program.
For terminating the statements ;(semicolon) is used.
For inputting the data from the keyboard, scanf() function is used.
For output printf() function is used, where f is formatted input as well as for formatted output.
C has no specific rules for the position at which a statement is to be written. That’s whyit is often called a free-form language.
Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.Basic Structure of C program
DOCUMENTATION SECTION. LINK SECTION.
DEFINITION SECTION.
GLOBAL DECLARATION SECTION. main() : FUNCTION SECTION { Declaration part Executable part } Subprogram section function1 function2
(User defined functions) |
| | | function n.
Syntax of scanf() statement
scanf(“control string”,&variable1 ,&variable2 - - -);
address Syntax of printf() statement
printf(“<format string>”,<List of variables>)
where format string can be %f, %d, %c.
Format String
%f : It is used for declaring float variables. %d : It is used for declaring integer variables.
%c : It is used for declaring character variables.
General Structure of C-program main() { declaration of variables/initialization scanf(“ _____ ”); printf(“ _____ ”); _______ _______ C-instructions _______ printf(“ _____ ”); } Comments
Comments about the program should be enclosed within /* */
Any number of comments can be given at any place in the program.
Comments cannot be nested. For example, /*Cal of SI /* Author sam date 01/01/90 */*/ is invalid.
A comment can be split over more than one line, as in, /* This isa jazzy comment */
Comments should be used at any place where there is a possibility of confusion.
Any program is nothing but a combination of functions. main() is one such function. Empty parentheses after main are necessary.
The set of statements belonging to a function are enclosed within a pair of braces. For e.g. main() { statement 1; statement 2; statement 3; }
Any variable used in the program must be declared before using it.// Program to calculate simple interest. main()
{
int p,n; float r,si; p=1000;
n=3; r=8.5; si=p*n*r/100;
printf(“%f”,si);
}
In the above program we assumed the values of p,
n and r to be 1000, 3 and 8.5. If we want to make a provision for supplying the values of p, n and r through the keyboard, scanf() function should be used. This is illustrated in the program shown below: main() { int p, n; float r, si; printf(“\nEnter values of p, n, r:”); scanf(“%d %d %f”,&p,&n,&r); si=p*n*r/100; printf(“%f”,si); }
The 1st printf() statement outputs the message “Enter values of p, n, r” on the screen. Here we have
not used any variables in printf(), which means that using variables in printf() is optional. Note that the ampersand (&) before the variables in the scanf() statement is a must.
Also, note that the values for p, n and r to be supplied through the keyboard, must be separated by a blank, a tab or a newline.
E.g. The three values separated by blank. 5 15.5
E.g. The three values separated by tab. 1000 5 15.5
E.g. The three values separated by newline. 1000
5 15.5
‘C’-Character Set
C-Character Set consists of alphabets, digits and special symbols. Alphabets: A---Z
a---z Digits: 0---9
Special symbols: +, -, =, {, }, [, ], ;, :, <, >, ?, /, \, @, #, *
Constants
Constant is a quantity which does not change during the execution of program. This quantity can be stored as a location in the memory of computer.
Variables
Variable are those which can change during the execution of program (compilation of program).
Example of constants and variables:
Here a and b can vary but 2,3,23 cannot vary as those are values. Therefore, a &b are variables & 2,3,23 are constants.
//Program to convert Fahrenheit into celsius. #include<stdio.h> #include<conio.h> void main() { float f,c; clrscr();
printf("\nEnter the value of fahrenheit:"); scanf("%f",&f); c=5.0/9*(f-32); printf("%f",c); getch(); } ***************************************************************************
//Program to convert Pound into Kgs. #include<stdio.h> #include<conio.h> void main() { float pound,kg; clrscr();
printf("\nEnter the pounds:"); scanf("%f",£); kg=pound/2.204; printf("Kg=%f",kg); getch(); } *******************************************************************************
//Program to calculate the area & volume of sphere #include<stdio.h> #include<conio.h> void main() { int radius; float volume,area; clrscr();
printf("\nEnter the radius of sphere:"); scanf("%d",&radius);
area=4*3.14*radius*radius;
printf("Volume=%f Area=%f",volume,area); getch();
}
********************************************************************************
//Program to convert Km into m. #include<stdio.h> #include<conio.h> void main() { float km,m; clrscr();
printf("\nEnter the value of Km:"); scanf("%f",&km); m=(1.0/1000)*km; printf("%f",m); getch(); } *******************************************************************************
//Program to convert Byte into Bits, Kilobytes, Megabytes #include<stdio.h> #include<conio.h> void main() { float byte,bit,kb,mb; clrscr();
printf("\nEnter the bytes:"); scanf("%f",&byte);
bit=1.0/8*byte; kb=byte*1000; mb=byte*1000000;
printf("Bit=%f Kilobyte=%f Megabyte=%f",bit,kb,mb); getch();
}
********************************************************************************
//Program to calculate the sum of digits of three digit number //entered by user. #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,sum; clrscr();
scanf("%d",&num); n1=num%10; num=num/10; n2=num%10; num=num/10; sum=n1+n2+num; printf("\nSum of 3 digits=%d",sum); getch(); } ************************************************************************************
//Program to calculate the sum of 1st and last digit of four digit //number entered by user.
#include<stdio.h> #include<conio.h> void main() { int num,n1,n2,sum; clrscr();
printf("\nEnter any 4 digit number:"); scanf("%d",&num);
n1=num%10; n2=num/1000; sum=n1+n2;
printf("\nSum of 1st and last digit=%d",sum); getch();
}
************************************************************************************
//Program to find the reverse of a 3 digit number //entered by user. #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,rev; clrscr();
printf("\nEnter any 3 digit number:"); scanf("%d",&num); n1=num%10; num=num/10; n2=num%10; num=num/10; rev=n1*100+n2*10+num;
printf("\nReverse of 3 digit number=%d",rev); getch();
}
Keywords
Keywords are the words whose meaning has been already explained to the ‘C’ compiler. The
keywords cannot be used as variables. There are 32 keywords in a ‘C’ language. The keywords are also called reserve words.
E.g. if, int, else, float, goto.
The 32 keywords are as follows:
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
Data Type
Data type specifies the size and arrangement of memory storage for an object of that type.
Variable Declaration
Every variable must have a datatype. Use a type specifier, such as char, int, short or long to show the variables type.
Syntax: type name[value];
Character (char): 1 byte Integer (int): Positive 2 bytes Float (float): 4 bytes
Data Type Modifiers
Signed/Unsigned type: Signed on integer in actual is redundant as the default integer assumes signed no. Signed is used to modify character (char), as character by default is unsigned. Unsigned can be applied to float.
Long/Short type: Long or short are applied to basic types. They are used when an integer of shorter or longer length than its normal length is required. Short is 16 bits, long is 32 bits.E.g. int a, char p, float length, double area, long distance, short miles.
C-Tokens
In a passage of text, individual words and punctuation marks are called as tokens. Similarly in a C-program, the smallest individual units are known as C-Tokens. C has 6 types of tokens.
E.g. float E.g. –15.5 E.g. max E.g. “ABC” E.g. +, -, *, / E.g. { } while 100 amount(amt) “XYZ” [ ]
if “name” !
Identifier
Identifier refers to the names of variables, functions and arrays. These are user-defined names and consist of sequence of letters and digits with a letter as a first character.
Both uppercase and lowercase letters are permitted and the underscore( _ ) is also permitted while defining the identifiers.
C-Tokens
Keywords
Special
Symbol
s
Constants
Identifier
Strings
Operators
Types of C Constants
C-Constants can be divided into two major categories:
Primary Constants
Secondary ConstantsThese constants are further categorized as follows:
For constructing these different types of constants certain rules have been laid down and they are as follows:Rules for Constructing Integer Constants
An integer constant must have at least one digit.C- Constants
Primary Constants
Secondary Constants
Character
Constants
Numeric
Constants
Arrays
Pointers
Structures
Union
Real
Constants
Integer
Constants
Character
er Constants
String Constant
er Constants
It must not have a decimal point.
It could be either positive or negative.
If no sign precedes an integer constant it is assumed to be positive.
No commas or blanks are allowed within an integer constant.
The allowable range for integer constants is –32768 to +32767 for 16-bit numbers. It is defined in a program as ‘int’.
E.g. 426, +782, -8000, -7605 E.g. Invalid Valid 2_9 -15 -13m 2903 1.9 0Rules For Constructing Real Constants
Real Constants are often called Floating Point Constants. The real constants can be written in two forms, Fractional form and Exponential form.
Rules for constructing real constants expressed in Fractional form:
A real constant must have at least one digit.
It must have a decimal point.
It could be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within a real constant.E.g. +325.34, 426.0, -32.76, -48.5792
The exponential form of representation of real constant is usually used if the value of the constant is either too small or too large.
In exponential form of representation, the real constant is represented in two parts. The part
appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.
Rules for constructing real constants expressed in exponential form:
The mantissa part and the exponential part should be separated by a letter ‘e’.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit which must be a positive or negative integer. Default sign is positive.
Range of real constants expressed in exponential form is –3.4e38 to 3.4e38. E.g. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5Rules For Constructing Character Constants
Rules for Constructing Single Character Constants
A character constant is either a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example,
’A’ is a valid character constant whereas ‘A’ is not.
The maximum length of a character constant can be 1 character.E.g. ’x’, ’z’, ’9’, ’=’
String: It is a sequence of characters. Rules For Constructing String Constants
It consists of multiple characters.
It is represented in double quotation marks.E.g. “Chester”, “x=ymg”
Variable Names
Variable names are names given to locations in the memory of computer where different constants are stored. These locations can contain integer, real or character constants.
Rules For Constructing Variable Names
It must begin with a letter. Some system permits underscore ( _ ) as a first character. It is a combination of 1 to 8 characters. Some compilers allow the length of 40 characters. No commas or blanks are allowed for constructing the variables.
It should not be a keyword.
No special symbol other than underscore can be used. It is case sensitive. E.g.
Valid
Invalid
x_y
x-y
x y DatatypesIt allows the programmer to select the type appropriate to the need of the application. It supports four classes.
Primary Datatype
User-Defined Datatype
Derived Datatype
Empty data setPrimary Datatype
There are 3 types of primary datatype.
Integer (int)
Real/Float (float)
Character (char)
Integer (int) int (16-bit)short int (8-bit) long int (32-bit)
unsigned short int (32-bit) unsigned long int (64-bit)
Character (char) Signed char Unsigned char
Float/Real (float) Float Double Long doubleSize and Ranges 1 byte=8 bits
Datatype Range Size
Char -128 to +127 1 byte Int -32768 to +32767 2 bytes Float 3.4e-38 to 3.4e+38 4 bytes Double 1.7e-308 to 1.7e+308 8 bytes
Declaration of Primary Data types Syntax: datatype a1, a2, a3 - - - -an; E.g. int xyz;
float val; char name[20]; float sal; User-Defined Datatype
User-Defined type declaration Syntax: typedef type identifier;
Where, type refers to existing datatype and identifier refers to the new name given to datatype.
E.g. typedef int xyz; typedef int sal; C-Instructions
Type Declaration Instruction
Input/Output Instruction
Arithmetic Instruction
Control InstructionType Declaration Instruction
This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. It is usually written at the beginning of the C-Program.
Input/Output Instruction
This instruction is used to perform the function of supplying input data to a program and obtaining the output results from it.
E.g. printf( ), scanf( )
Arithmetic Instruction
This instruction is used to perform arithmetic operations between constants and variables.
E.g. c=a+2b;
In this instruction one arithmetic operator is used and also one assignment operator is used.
This instruction is divided into 3 types.
Integer Mode: In this mode arithmetic integer variables and arithmetic integer constants are used. E.g. int i;
i=i+2;
Real Mode: In this mode real variables and real constants are used. E.g. float b;
float c; c=3.2+b;
Mixed Mode: In this mode some operands are integer and some operands are real. E.g. float b;
int c; float a; a=b+c+3
Note: C allows the variables or constants with arithmetic operators on the left side of equation.
In C language 3+a=b is an invalid expression whereas b=3+a is a valid expression.
Control Instructions
This instruction is used to control the sequence of execution of various statements.
E.g. while, for
Integer and float conversions
The rules that are used for the implicit conversion of floating point and integer values in C are as follows:
An arithmetic operation between an integer and integer always yields an integer result.
Operation between a real and real always yields a real result.
Operation between an integer and real always yields a real result.
E.g.
Operation Result Operation Result
5.0/2 2.5 2.0/5 0.4
5/2.0 2.5 2/5.0 0.4
5.0/2.0 2.5 2.0/5.0 0.4
Type Conversion in Assignments
It may happen that the type of the expression and the type of the variable on the left side of the assignment operator may not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variables on the left side of =.
E.g. int i; float b; i=3.5; b=30;
Here in the first assignment statement though the expression’s value is a float(3.5) it cannot be stored in ‘i’ since it is an integer. In such a case the float is demoted to an integer and then its value is stored. Hence what gets stored in ‘i’ is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in ‘b’, since ‘b’ being a float
variable cannot hold anything except a float value.
Thus while storing the value the expression always takes the type of the variable into which its value is being stored.
Consider the complex expression in the given program fragment: float a, b, c;
int s;
s=a*b*c/100+32/4-3*1.1;
Here, in the assignment statement some operands are integers whereas others are floats. As we know during evaluation of the expression the integers would be promoted to floats and the
result of the expression would be a float. But when this float value is assigned to ‘s’ it is again
demoted to an integer and then stored in ‘s’.
E.g. ‘k’ is an integer variable and ‘a’ is a real variable.
Arithmetic Instruction Result Arithmetic Instruction Result k=2/9 0 a=2/9 0.0 k=2.0/9 0 a=2.0/9 0.2222 k=2/9.0 0 a=2/9.0 0.2222 k=2.0/9.0 0 a=2.0/9.0 0.2222 k=9/2 4 a=9/2 4.0 k=9.0/2 4 a=9.0/2 4.5
k=9/2.0 4 a=9/2.0 4.5 k=9.0/2.0 4 a=9.0/2.0 4.5 Hierarchy of Operations 1st priority *, /, % 2nd priority +, -3rd priority =
The priority or precedence in which the operations in an arithmetic statement are performed is called as Hierarchy of operations.
The usage of operators in general is as follows:
In case of a tie between operations of same priority preference is given to the operator, which occurs first. For example, consider the statement,z = a*b+c/d;
Here, a*b will be performed before c/d even though * and / has same or equal priority. This is because * appears prior to the / operator.
Also, if there are more than one set of parentheses, the operations within the innermost parentheses will be performed first, followed by the operations within the second innermost pair and so on.
Always, a pair of parentheses should be used. Imbalance of the right and left parentheses is a common error.Q.1 Determine the hierarchy of operations and evaluate the following expression: i = 2 * 3 / 4 + 4 / 4 + 8 – 2 + 5 / 8
Stepwise evaluation of this expression is shown below: i = 2 * 3 / 4 + 4 / 4 + 8 – 2 + 5 / 8 i = 6 / 4 + 4 / 4 + 8 – 2 + 5 / 8 Operation : * i = 1 + 4 / 4 + 8 – 2 + 5 / 8 Operation : / i = 1 + 1 + 8 – 2 + 5 / 8 Operation : / i = 1 + 1 + 8 – 2 + 0 Operation : / i = 2 + 8 – 2 + 0 Operation : + i = 10 – 2 + 0 Operation : + i = 8 + 0 Operation : -i = 8 Operat-ion : +
Q.2 Determine the hierarchy of operations and evaluate the following expression: k = 3 / 2 * 4 + 3 / 8 + 3
Stepwise evaluation of this expression is shown below: k = 3 / 2 * 4 + 3 / 8 + 3 k = 1 * 4 + 3 / 8 + 3 Operation : / k = 4 + 3 / 8 + 3 Operation : * k = 4 + 0 + 3 Operation : / k = 4 + 3 Operation : + k = 7 Operation : + 1) ab – cd = a * b – c * d
2) (m + d) (x + y) = (m * d) * (x + y) 3) 2x2 + 5x + 15 = 2 * xe2 + 5 * x + 15 4) x + y + z = ( x + y + z) / (b + c) b + c 5) 3xy - y m + 2 3(m+2) = (3* x*y)/(m+2) – (y/3* (m+2))
Q.1 WAP to calculate the area of triangle. Q.2 WAP to calculate the area of square.
Q.3 WAP to calculate the area and circumference of a circle.
Q.4 WAP to calculate the area of a triangle when three sides of a triangle are given. Q.5 WAP to interchange two integer variables.
With using 3rd variable.
Without using 3rd variable. Q.6 WAP to convert Fahrenheit into Celsius. Q.7 WAP to convert Pound into kilograms.Q.8 WAP to calculate area and volume of a sphere. Q.9 WAP to convert Kilometers into meters.
Q.10 WAP to convert Byte into bits, kilobytes, megabytes.
Q.11 WAP to calculate the sum of digits of three-digit number entered by user. Q.12 WAP to calculate the sum of 1st and last digit of four-digit number.
Q.13 WAP to find the reverse of three-digit number.
stdio.h
getchar() gets() printf() putchar() puts() scanf() (For single (multiple (multiple
character character character i/o) i/o including i/o but in
space) formatted manner without space)
**************************************************** ************************
//WAP to print a single character using getchar() and putchar() #include<stdio.h> #include<conio.h> void main() { char a; clrscr(); a=getchar(); putchar(a); getch(); } **********************************************************************
//WAP to print a string without space using printf() and scanf() #include<stdio.h> #include<conio.h> void main() { char username[20]; clrscr();
printf("\nEnter your name:"); scanf("%s",&username);
printf("\nUsername=%s",username); getch();
}
*********************************************************************************
//WAP to print a string including space using gets() and puts #include<stdio.h> #include<conio.h> void main() { char username[20]; clrscr();
printf("\nEnter your name:"); gets(username);
puts(username); getch();
}
*****************************************************************************
//WAP to print the name of the student using gets() and puts(), print //the marks of maths, science nad english and also print the total and //average of the student.
#include<stdio.h> #include<conio.h> void main()
{
int maths, sci, eng; float total, avg; char sname[20]; clrscr();
printf("\nEnter the name of a student:"); gets(sname);
printf("\nEnter the marks of maths, science and english:"); scanf("%d %d %d",&maths,&sci,&eng);
total=maths+sci+eng; avg=total/3;
clrscr();
printf("********************Student Details***********************"); printf("\nThe name of the student is:");
puts(sname);
printf("The marks of Maths is:%d",maths); printf("\nThe marks of Science is:%d",sci); printf("\nThe marks of English is:%d",eng);
printf("\nThe total marks of the student is:%f",total); printf("\nThe average of the student is:%f",avg);
printf("\n**********************************************************"); getch();
}
*********************************************************************** //WAP which prints the employee no, employee name and salary and using it //calculate its da, hra and total salary.
#include<stdio.h> #include<conio.h> void main()
int eno;
float salary,da,hra,ts; char ename[20];
clrscr();
printf("\nEnter the name of the employee:"); gets(ename);
printf("\nEnter the Employee id:"); scanf("%d",&eno);
printf("\nEnter the salary of the employee:"); scanf("%f",&salary); da=0.35*salary; hra=0.11*salary; ts=da+hra+salary; clrscr(); printf("******************Employee Details***********************"); printf("\nThe name of the employee is:");
puts(ename);
printf("The employee id is:%d",eno);
printf("\nThe salary of the employee is:%f",salary); printf("\nDA:%f",da);
printf("\nHRA:%f",hra);
printf("\nTotal Salary of the employee is:%f",ts);
printf("\n*********************************************************"); getch();
}
Operators in C
There are 8 types of operators in C and they are:
Arithmetic Operators
Relational Operators
Logical Operators
Conditional Operators
Assignment Operators
Increment and Decrement Operators
Bitwise Operators
Special type Operators.Arithmetic Operators
Arithmetic Operators are +, -, *, /, %.
OP1 OP2 RESULT
int float float
float int float
float float float
Relational Operators
Relational Operators are > (greater than)
< (less than)
>= (greater than equal to) <= (less than equal to) = = (Equal to)
!= (Not Equal to)
Assignment Operator (=) Syntax: Vop=Exp Where V: Variable,
Op: Arithmetic Operator (+, -, *, /) =: Assignment Operator
Exp: Any expression E.g. 1) a=a+2; Or a+=2 2) b=b+(89+c) Or b+=89+c 3) d=d%8+c Or d%=8+c 4) d=d/8%c Or d/=8%c Conditional Operator
It consist of ?(Question mark) and :(colon) Syntax: Exp1 ? Exp2 : Exp3
True False
E.g. a<b ? printf(“T”) : printf(“F”).
Logical Operators
1)
Logical AND (&&)2)
Logical OR ( || )3)
Logical NOT ( ! )Logical AND
Expression1(Exp1) Expression2(Exp2) Result
T T T
F F F
Logical OR
Expression1(Exp1) Expression2(Exp2) Result
T T T T F F F F F Logical NOT Expression Result T F F T
Increment and Decrement Operators
+ + : Increment Operator - - : Decrement Operator Pre Increment: E.g. m=5 y=++m Post Increment: E.g. m=5 y=m++
The Increment or Decrement Operator, increases or decreases the value by 1 only.
In Pre-Increment first the value will be incremented and then it will be assigned to variable. Therefore, y=6
m=6 In E.g. m=5
the value of m is incremented first and then it will get assigned to the variable y and hence the output will be y=6, m=6
Post Increment Operator m=5; y=m++;
Here the values of m will get assigned first to variable y and then it will be incremented by 1. Therefore, output is y=5, m=6
Similarly for Pre Decrement E.g. m=5;
y=--m; will give the output y=4
m=4
and for Post Decrement E.g. m=5;
y=m--;
will give the output y=5
m=4
Note: In this Operator, increment or decrement is by 1 only. Bitwise Operator
& - Bitwise AND | - Bitwise OR ^ - Bitwise X-OR >> - Bitwise Right Shift << - Bitwise Left Shift
Special Operator & - address of
sizeof(); . - Dot operator , - comma operator etc.
Decision Control Structure
Programming Techniques in C
Sequential Programming
Conditional Programming
Looping
Sequential ProgrammingSequence Control Structure is the one in which the various steps are executed sequentially, i.e. in the same order in which they appear in the program. By default the instructions in a program are executed sequentially.
Conditional Programming Many times, it may be required that a set of instructions to be executed in one condition and an entirely different set of instructions to be executed in another condition. This kind of condition is used in C programs using a decision control instruction.
1)
If statement.2)
If-else statement.3)
If-else-if statement.4)
Switch-case statement.For checking the conditions in C program, ‘if’ and ‘else’ statement is used.
Syntax: a) If(condition) Statement; b) If(condition) { statement 1; statement 2; statement 3; } if(condition) statement; else statement; if(condition) { statement 1; statement 2; } else { statement 1; statement 2; }
If the condition in ‘if’ statement is true then the ‘C’ statements in ‘if’ block are executed and if the condition in ‘if’ statement is false then the ‘C’ statements in ‘else’ block are executed ignoring the ‘C’ statements in ‘if’
block.
True
False
START
INPU
T
if a>b
B is greater
A is greater
STOP
False
True
#include<stdio.h> #include<conio.h> void main() { int maths,sci,eng; float total,avg; char sname[20]; clrscr();
printf("\nEnter the name of the student:"); gets(sname);
printf("\nEnter the marks of maths, science and english:"); scanf("%d %d %d",&maths,&sci,&eng);
total=maths+sci+eng; avg=total/3;
printf("\nStudent name is:"); puts(sname);
if(avg<35)
printf("\nResult is Fail"); else if(avg>=35 && avg<45)
printf("\nResult is Third division"); else if(avg>=45 && avg<60)
printf("\nResult is Second division"); else if(avg>=60 && avg<75)
printf("\nResult is first division"); else if(avg>=75 && avg<101)
printf("\nResult is Distinction"); getch(); } ********************************************************************** #include<stdio.h> #include<conio.h> void main() { int a,b,great; clrscr();
printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b); //89 78 great=a; //89 if(a<b)
great=b; //89
printf("\nThe greatest number is %d",great); getch();
}
If-else-statement:It is used to carry out a logical test and then take one of the two possible actions, depending on the outcome of the test(true or false).
Syntax: if(expression) statement; else
statement;
If the ‘if’ expression evaluates to true, the statement or block following the ‘if’ is executed,
otherwise statement block follows the else part. void main()
{
int a,b; clrscr();
printf(“\nEnter any two numbers:”); scanf(“%d %d”,&a,&b); if(a>b) printf(“\nA is greatest”); else printf(“\nB is greatest”); getch(); } Nested ifs If(exp1) { If(exp2) Statement 1; If(exp3) Statement 2; Else Statement 3; } Else Statement 4; OR If(condition) { If(condition) { _______ _______ } Else { _______ ________ } } Else { If(condition) { ______
_______ } Else { _____ _____ } }
Example of Nested if’s
********************************************************************** #include<stdio.h> #include<conio.h> void main() { int x,y; x=y=0; clrscr(); printf("\nEnter choice(1-3):"); scanf("%d",&x); if(x==1) {
printf("\nEnter value for y(1-5):"); scanf("%d",&y);
if(y<=5)
printf("\nThe value of y is %d",y); else
printf("\nThe value of y exceeds 5"); }
else
printf("\nChoice entered was not one"); getch(); } *********************************************************************** If-else-if Statement: Syntax: if(expression) statement; else if(expression) statement; else if(expression) statement; else statement;
The conditions in this case are evaluated top to bottom. As soon as a true expression is found, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is executed.
#include<stdio.h> #include<conio.h>
void main() { int x; x=0; clrscr(); printf("\nEnter choice(1-3):"); scanf("%d",&x); if(x==1) printf("\nChoice is 1"); else if(x==2) printf("\nChoice is 2"); else if(x==3) printf("\nChoice is 3"); else printf("\nInvalid Choice"); getch(); } ***********************************************************************
Switch Statement
The switch statement causes a particular group of statements to be chosen from several available groups. The selection is based upon the current value of an expression that is included within the switch statement. E.g. switch(expression)
statement;
#include<stdio.h> #include<conio.h> void main() { int num; clrscr();
printf("\nEnter the number:"); scanf("%d",&num); //12 if(num%2==0) printf("\nNumber is even"); else printf("\nNumber is odd"); getch(); } *********************************************************************** //WAP to check whether an entered number is positive, negative or zero. #include<stdio.h> #include<conio.h> void main() { int num; clrscr();
printf("\nEnter any number:"); scanf("%d",&num); //13 if(num<0) printf("\nNumber is negative"); if(num>0) printf("\nNumber is positive"); if(num==0) printf("\nNumber is zero"); getch(); } *********************************************************************** //WAP to check whether a 3 digit entered number is pallindrome or not. //Pallindrome Number:When the reverse of a number is equal to the number //itself. Eg:121 #include<stdio.h> #include<conio.h> void main() { int num,n1,n2,rev,orin; clrscr();
printf("\nEnter the number:"); scanf("%d",&num); orin=num; n1=num%10; num=num/10; n2=num%10; num=num/10; rev=n1*100+n2*10+num; if(rev==orin)
printf("\nNumber is pallindrome"); else
printf("\nNumber is not pallindrome"); getch();
}
******************************************************************** //WAP to check whether an entered 3 digit number is armstrong or not. //If the sum of cube of each digit is equal to the number itself is called //armstrong Number. Eg:153
#include<stdio.h> #include<conio.h> void main() { int num,orin,n1,n2,sum; clrscr();
printf("\nEnter a 3 digit number:"); scanf("%d",&num); orin=num; n1=num%10; num=num/10; n2=num%10; num=num/10; sum=n1*n1*n1+n2*n2*n2+num*num*num; if(sum==orin) printf("\nNumber is Armstrong"); else
printf("\nNumber is not Armstrong"); getch();
}
***********************************************************************
//WAP to calculate the roots of quadratic equation.
//x1=(-b+sqrt(b2-4ac))/2a, x2=(-b-sqrt(b2-4ac))/2a //t<0:imaginary
//t>0:real and different //t==0:real and equal #include<stdio.h> #include<conio.h>
#include<math.h> void main() { int a,b,c,t; float x1,x2; clrscr();
printf("\nEnter the values of a,b and c:"); scanf("%d %d %d",&a,&b,&c);
t=b*b-4*a*c; if(t<0)
printf("\nRoots are Imaginary"); if(t==0)
{
printf("\nRoots are real and equal"); x1=-b/(2*a); x2=x1; printf("\nRoots are %f %f",x1,x2); } if(t>0) {
printf("\nRoots are real and distinct"); x1=-b+sqrt(t)/(2*a); x2=-b-sqrt(t)/(2*a); printf("\nRoots are %f %f",x1,x2); } getch(); } ********************************************************************** //WAP to calculate whether an entered number is perfect square or not. #include<stdio.h> #include<conio.h> #include<math.h> void main() { int num,n1; clrscr();
printf("\nEnter any number:"); scanf("%d",&num);
n1=sqrt(num); if(num==n1*n1)
printf("\nNumber is a perfect square"); else
printf("\nNumber is not a perfect square"); getch();
}
*********************************************************************** //WAP to solve given 2 equations.
//ax+by=m and cx+dy=n
//where x=md-nb/ad-cd and y=na-mc/ad-cb
//Calculate the value of x and y if ad-cb!=0 and print the appropriate result //if ad-cb=0.
#include<conio.h> void main()
{
int a,x,b,y,m,c,d,n,t; clrscr();
printf("\nEnter the input:");
scanf("%d %d %d %d %d %d",&m,&n,&a,&b,&c,&d); t=a*d-c*b; if(t!=0) { x=m*d-n*b/t; y=n*a-m*c/t;
printf("\nThe values for x and y are %d %d",x,y); } if(t==0) printf("\nInfinite Result"); getch(); } *********************************************************************** //WAP to find the largest number in 3 entered number.
#include<stdio.h> #include<conio.h> void main() { int n1,n2,n3; clrscr(); printf("\nEnter 3 numbers:"); scanf("%d %d %d",&n1,&n2,&n3); if(n1>n2) { if(n1>n3) { printf("\nLargest number is n1"); } else printf("\nn3 is largest"); } else { if(n2>n3) printf("\nn2 is largest"); else printf("\nn3 is largest"); } getch();} *********************************************************************** //WAP which reads a marks of 5 subjects entered by student and check whether //the student has passed or fail. If passed calculate the percentage marks //of student and also print the division of the student.
#include<stdio.h> #include<conio.h> void main()
{
int m1,m2,m3,m4,m5,per; clrscr();
printf("\nEnter the marks of 5 subjects:"); scanf("%d %d %d %d %d",&m1,&m2,&m3,&m4,&m5);
if(m1>=40 && m2>=40 && m3>=40 && m4>=40 && m5>=40) {
printf("\nStudent is passed"); per=(m1+m2+m3+m4+m5)/5;
if(per>=75)
printf("\nCongrats, U have got distinction"); if(per>=60 && per<=74)
printf("\nFirst division"); if(per>=50 && per<=59)
printf("\nSecond division"); if(per>=40 && per<=49)
printf("\nThird division"); }
else
printf("\nSorry, U are fail"); getch();
}
********************************************************************** //WAP which reads a 4 digit number and check whether it is in the form //AABB, if found check whether it is a perfect square.
#include<stdio.h> #include<conio.h> #include<math.h> void main() { int num,orin,d1,d2,d3,d4,a; clrscr();
printf("\nEnter a 4 digit number:"); scanf("%d",&num); orin=num; d1=num%10; num=num/10; d2=num%10; num=num/10; d3=num%10; num=num/10; d4=num;
if(d1==d2 && d3==d4 && d2!=d3) {
printf("\nNumber is in the form AABB"); a=sqrt(orin);
if(a*a==orin) {
printf("\nNumber is a perfect square"); }
else
printf("\nNumber is not a perfect square"); }
else
printf("\nNumber is not in the form AABB"); getch();
}
*********************************************************************** //WAP to accept 2 integers and divide bigger by smaller number.
#include<stdio.h> #include<conio.h> void main() { float a,b,x; clrscr();
printf("\nEnter the values of a and b:"); scanf("%f %f",&a,&b); if((a>b) && (b!=0)) { x=a/b; printf("\n%f",x); } else
if((b>a) && (a!=0)) { x=b/a; printf("\n%f",x); } getch(); } *********************************************************************** //WAP to find whether the entered year is a leap year or not.
#include<stdio.h> #include<conio.h> void main() { int year; clrscr();
printf("\nEnter the year:"); scanf("%d",&year);
if((year%4==0 && year%100!=0) || (year%400==0)) {
printf("\nThe year is a leap year"); }
else
printf("\nThe year is not a leap year"); getch();
}
***********************************************************************
//WAP for function of calculator which performs addition, subtraction, //multiplication and division.
#include<conio.h> void main() { int x; float a,b,c; clrscr(); printf("\nMENU\n1.ADDITION\n2.SUBTRACTION\n3.MULTIPLICATION\n4.DIVISION \nEnter Choice"); scanf("%d",&x); printf("\nEnter 2 numbers:"); scanf("%f %f",&a,&b); if(x==1) { c=b+a;
printf("\nThe result of addition is %f",c); } else { if(x==2) { c=a-b;
printf("\nThe result of subtraction is %f",c); } else { if(x==3) { c=a*b;
printf("\nThe result of multiplication is %f",c); } else { if(x==4) { c=a/b;
printf("\nThe result of division is %f",c); } else { printf("\nInvalid Choice"); } } } } getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int age; clrscr();
scanf("%d",&age); if(age<1)
printf("\nMinor Category"); else if(age>=1 && age<18) printf("\nMedium Category"); else if(age>=18 && age<45) printf("\nMajor Category"); else if(age>=45 && age<70) printf("\nHighest Category"); else printf("\nWrong Age"); getch(); } ***********************************************************************
Ternary Operator or Conditional Operator(? :)
Syntax: e1?e2:e3
e1 is the logical expression depending on the evaluation of e1. The control will transfer to either e2 or e3. If e1 evaluates true then e2 is executed else e3.
#include<stdio.h> #include<conio.h> void main() { int a,b,big; clrscr();
printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b); big=(a>b?a:b); printf("\n%d is big",big); getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { int a,b,c,big; clrscr();
printf("\nEnter any three numbers:"); scanf("%d %d %d",&a,&b,&c); big=(a>b?(a>c?a:c):(b>c?b:c)); printf("\n%d is biggest",big); getch(); } ***********************************************************************
ASCII (American Standard Code for Information Interchange) 0 48 | | | | | | 9 57
condition
True
False
65 A | | | | | | 90 Z 97 a | | | | | | 122 z #include<stdio.h> #include<conio.h> void main() { char ch; clrscr();
printf("\nEnter any character:"); scanf("%c",&ch); printf("\n%c",ch); getch(); } *********************************************************************** #include<stdio.h> #include<conio.h> void main() { char ch; clrscr();
printf("\nEnter any character:"); scanf("%c",&ch); printf("\n%d",ch); getch(); } ********************************************************************** #include<stdio.h> #include<conio.h> void main() { char ch; clrscr();
printf("\nEnter any character:"); scanf("%c",&ch);
if(ch>=48 && ch<=57)
printf("\nThe character is a digit"); else if(ch>=65 && ch<=90)
printf("\nThe character is in uppercase"); else if(ch>=97 && ch<=122)
printf("\nThe character is in lowercase"); else
getch(); }
***********************************************************************
Switch-case Statements
In switch case statements the switch statement causes a particular group of statements to be chosen from several available groups.
Syntax: switch(choice) { case 1: statement 1; break; case 2: statement 2; break; case 3: statement 3; break; default: statement; }
Start
Case 1
Case 2
Case 3
Stop
Statement 3
Statement 1
Statement 2
Yes
Yes
Yes
No
No
No
//WAP for addition,subtraction,multiplication,division and modular division //using switch case.
#include<stdio.h> #include<conio.h> void main() { int a,b,c,d; clrscr(); printf("\nMENU\n1.ADD\n2.SUB\n3.MUL\n4.DIV\n5.MOD"); printf("\nEnter your choice:");
scanf("%d",&d);
printf("\nEnter any two numbers:"); scanf("%d %d",&a,&b);
switch(d) {
case 1: c=a+b;
printf("\nThe result for addition is:%d",c); break;
case 2: c=a-b;
printf("\nThe result for subtraction is:%d",c); break;
case 3: c=a*b;
printf("\nThe result for multiplication is:%d",c); break;
case 4: c=a/b;
printf("\nThe result for division is:%d",c); break;
case 5: c=a%b;
printf("\nThe result for modular division is:%d",c); break; default:printf("\nInvalid Choice"); } getch(); } *********************************************************************** //WAP which prints the season according to the month entered
//using switch case #include<stdio.h> #include<conio.h> void main() { int n; clrscr();
printf("\nEnter month number:"); scanf("%d",&n);
switch(n) {
case 12: case 1:
case 2: printf("\nWinter Season"); break; case 3: case 4: case 5: printf("\nSummer Season"); break; case 6: case 7: case 8: printf("\nRainy Season"); break; case 9: case 10: case 11: printf("\nSpring Season"); break;
default: printf("\nInvalid month number"); }
getch(); }
***********************************************************************
Decisions Using Switch
The control statement which allows to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They are as follows:
switch(integer expression) { case constant 1: do this; case constant 2: do this; case constant 3: do this; default: do this; }
Q. What happens when we run a program containing a switch?
First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following that case, and all subsequent case and default statements as well. If no match is found with any of the case statements, only the statements following the default are executed. E.g. main() { int i=2; clrscr(); switch(i) {
case 1: printf(“I am in case 1\n”); case 2: printf(“I am in case 2\n”); case 3: printf(“I am in case 3\n”); default: printf(“I am in default\n”); } getch(); }
Output of the program: I am in case 2
I am in case 3 I am in default
But the expected output of the above program was “I am in case 2”. This output can be achieved by getting out of the control structure then and there by using a break statement. Note that there is no need for a break statement after the default, since the control comes to the end anyway. It is as follows:
main() { int i=2; clrscr(); switch(i) { case 1: printf(“I am in case 1\n”); break; case 2: printf(“I am in case 2\n”); break; case 3: printf(“I am in case 3\n”); break; default: printf(“I am in default\n”); } getch(); } Output: I am in case 2 Usage of Switch
It is not necessary that only cases arranged in ascending order, 1, 2, 3 and default can be used. Cases can be written in any order we want.
E.g. main() { int i=22; clrscr(); switch(i)
{ case 121: printf(“I am in case 121\n”); break; case 7: printf(“I am in case 7\n”); break; case 22: printf(“I am in case 22\n”); break; default: printf(“I am in default\n”); } getch(); } Output: I am in case 22
It is also allowed to use character values in case and switch. E.g. main() { char c=’x’; clrscr(); switch(c) { case ‘v’: printf(“I am in case v\n”); break; case ‘a’:
printf(“I am in case a\n”);
break; case ‘x’: printf(“I am in case x\n”); break; default: printf(“I am in default\n”); } getch(); }
Integer and character constants can be mixed in different cases of a switch. E.g. main() { char c=3; clrscr(); switch(c) { case ‘v’: printf(“I am in case v\n”); break; case 3:
printf(“I am in case 3\n”); break; case 12: printf(“I am in case 12\n”); break; default: printf(“I am in default\n”); } getch(); }
Sometimes there may not be any statement in some of the cases in switch, but still they
might turn out to be useful. E.g.
//WAP to print the colours of the rainbow according to the alphabets entered //(uppercase or lowercase) using switch case.
#include<stdio.h> #include<conio.h> void main() { char choice; clrscr();
printf("\nSelect rainbow colour VIBGYOR:"); scanf("%c",&choice); switch(choice) { case 'v': case 'V': printf("\nViolet"); break; case 'i':
case 'I': printf("\nIndigo"); break; case 'b': case 'B': printf("\nBlue"); break; case 'g': case 'G': printf("\nGreen"); break; case 'y':
case 'Y': printf("\nYellow"); break;
case 'o':
case 'O': printf("\nOrange"); break;
case 'r':
case 'R': printf("\nRed"); break;
default: printf("\nWrong Colour Entered"); }
getch(); }