C Programming
C Programming
variables.
UNIT-III: Operators Decision making and branching If, simple if, If else, Nesting of if - else,
Else - If ladder, Switch statement, the?: operator, Go to statement. Decision making with
looping: While, Do, for statement, Jumps in loops.
UNIT-IV: Arrays One - dimensional array, two - dimensional array, Initializing arrays, Multi -
dimensional arrays.
UNIT-V: User-Defined Function Need for User-defined function, Multi-function program, the
form of C-Function, Return Value and their types. Structures and Unions: Structure definition,
Structure initialization, Comparison of structure variables, union.
Constants
Constant is a quantity that does not change throughout the execution of a program.
o Integer constants
o Character constants
o Real/Floating point constants
o String constants
Integer Constants
An integer constant is an integer quantity which contains a sequence of digits. It should not
have a decimal point. Blanks and commas are not allowed within an integer constant .An integer
constant can be either +ve or -ve. The constant must lie within the range of the declared data type
(including qualifiers long, short etc.).
They are also known as real constants. A real constant contains a decimal point or an
exponent. It can be either +ve or -ve. Commas and blank space are not allowed within a real
constant.
String Constants
Derived data types are nothing but primary data types but a little twisted or grouped together
like array, structure, union and pointer. These are discussed in details later.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be
declared as what data-type it is.
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:
Character type
Character types are used to store characters value.
Variable
Variables are changeable, we can change value of a variable during execution of a program. A
programmer can choose a meaningful variable name. Example : average, height, age, total etc.
A variable in C language must be given a type, which defines what type of data the variable will
hold.
It can be:
extern int a;
extern float b;
extern double c, d;
Defining a variable means the compiler has to now assign a storage to the variable because it
will be used in the program. It is not necessary to declare a variable using extern keyword, if you
want to use it in your program. You can directly define a variable inside the main() function and
use it.
To define a function we must provide the data type and the variable name. We can even define
multiple variables of same data type in a single line by using comma to separate them.
int a;
float b, c;
Initializing a variable means to provide it with a value. A variable can be initialized and defined
in a single statement, like:
int a = 10;
A program in which we will use some variables.
#include <stdio.h>
// Variable declaration(optional)
extern int a, b;
extern int c;
int main () {
/* variable definition: */
int a, b;
/* actual initialization */
a = 7;
b = 14;
/* using addition operator */
c = a + b;
/* display the result */
printf("Sum is : %d \n", c);
return 0;
}
Sum is : 21
You must be thinking how does this printf() works, right? Do not worry, we will learn about it
along with other ways to input and output data in C language in the next tutorial.
Structure of c program
Link section : The link section provides instructions to the compiler to link
functions from the system library.
Operator
Operator Description
Description Example
Example
Main () function section : Every C program must have one main function section.
This section contains two parts; declaration part and executable part
Declaration part : The declaration part declares all the variables used in the
executable part.
Executable part : There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration and
executable part end with a semicolon.
Subprogram section : The subprogram section contains all the user-defined functions
that are called in the main () function. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.
Note:All section, except the main () function section may be absent when they are not
required
Unit II
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
&& Called Logical AND operator. If both the operands are non-zero, (A &&
then the condition becomes true. B) is
false.
! Called Logical NOT Operator. It is used to reverse the logical state !(A &&
of its operand. If a condition is true, then Logical NOT operator B) is
will make it false. true.
Assignment Operators
Arithmetic Operators
The following table shows all the arithmetic. Assume variable A holds 10 and variable B holds
20 then
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −
== Checks if the values of two operands are equal or not. If yes, then the (A == B) is
condition becomes true. not true.
!= Checks if the values of two operands are equal or not. If the values are (A != B) is
not equal, then the condition becomes true. true.
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand. If yes, then the condition becomes true. true.
< Checks if the value of left operand is less than the value of right operand. (A < B) is
If yes, then the condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is
right operand. If yes, then the condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand. If yes, then the condition becomes true. true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
= Simple assignment operator. Assigns values from right side operands to left side C = A + B will
operand assign the value
of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and C += A is
assign the result to the left operand. equivalent to C
=C+A
-= Subtract AND assignment operator. It subtracts the right operand from the left C -= A is
operand and assigns the result to the left operand. equivalent to C
=C-A
*= Multiply AND assignment operator. It multiplies the right operand with the left C *= A is
operand and assigns the result to the left operand. equivalent to C
=C*A
/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent to C
=C/A
%= Modulus AND assignment operator. It takes modulus using two operands and C %= A is
assigns the result to the left operand. equivalent to C
=C%A
Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
C Ternary Operator (?:)
The first expression conditional expression is evaluated first. This expression evaluates to
1 if it's true and evaluates to 0 if it's false.
If conditional Expression is true, expression1 is evaluated.
If conditional Expression is false, expression2 is evaluated.
Output
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Arithmetic Expressions
The plus sign (+) is used to add two values, the minus sign (-) to subtract one value from another,
the asterisk(*) to multiply two values, the division (/) to divide a value and the modulus (%) to
obtain the reminder of integer division. These are known as binary operators since they operate
on two values or variables.
result= x - y;
total = principle + interest;
numsquare = x * x;
celcius = (fahrenheit - 32) / 1.8
Notice the equal sign (=) in the above expressions, it is known as the assignment operator. It
assigns the value on the right hand side of the equal sign to the variable on the left hand side.
In the last expression, parentheses are used to perform a certain operation first. This is because in
C, operators follow a precedence rule. *, / and % have a higher precedence over + and -. Hence
to override the precedence, parentheses should be used. Expressions having operators of the
same precedence are generally evaluated from left to right. Another point to note is that in an
expression which involves division, care should be taken to avoid a division by zero, since this
results in infinity or an abnormal value. In Chapter 5 on control statements, we will see how a
check can be done before a division occurs and prevent such operations.
Program 4.1
#include <stdio.h>
main()
{
int var1 = 10;
int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;
C provides standard functions scanf() and printf(), for performing formatted input and
output .These functions accept, as parameters, a format specification string and a list of variables.
The format specification string is a character string that specifies the data type of each variable to
be input or output and the size or width of the input and output.
Formatted Output
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the parameters
to the printf() function.
Syntax:
In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Example:
printf (“%c”, data1);
The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.
Conversion
Meaning
Character
D The data is converted to decimal (integer)
C The data is taken as a character.
The data is a string and character from the string , are printed until a NULL,
S
character is reached.
F The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
Example
printf (“%c\n”,data1);
Example
The text "Character is:" is printed out along with the value of data1.
1. #include<stdio.h>
2. #include<conio.h>
3. Main()
4. {
5. Char alphabh="A";
6. int number1= 55;
7. float number2=22.34;
8. printf(“char= %c\n”,alphabh);
9. printf(“int= %d\n”,number1);
10. printf(“float= %f\n”,number2);
11. getch();
12. clrscr();
13. retrun 0;
14. }
15. Output Here…
16. char =A
17. int= 55
18. flaot=22.340000
Operator precedence
Example of precedence
23. then, first part of the expression (1 > 5) executes resulting into 0 (false)
25. Output
26. 0
Associativity of operators
Example of associativity
28. 1 == 2 != 3
29. Here, operators == and != have same precedence. The associativity of both == and != is left
to right, i.e, the expression on the left is executed first and moves towards the right.
31. ((1 == 2) != 3)
34. Output
35. 1
36. The table below shows all the operators in C with precedence and associativity.
37. Note: Precedence of operators decreases from top to bottom in the given table.
() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection
! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
Right to left
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply
/ Divide Left to right
% Remainder
+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)
== Equal to
Left to right
!= Not equal to
Simple assignment
=
Assign product
*=
Assign quotient
/=
Assign remainder
%=
Assign sum
-=
Assign difference Right to left
&=
Assign bitwise AND
^=
Assign bitwise XOR
|=
Assign bitwise OR
<<=
Assign left shift
>>=
Assign right shift
‘C’ language processes decision making capabilities supports the flowing statements
known as control or decision making statements
1. If statement
2. switch statement
4. Go to statement
If Statement : The if statement is powerful decision making statement and is used to control the
flow of execution of statements The If statement may be complexity of conditions to be tested
If(test expression)
{ statement block;
} statement-x ;
The statement -block may be a single statement or a group of statement if the test
expression is true the statement block will be executed. Otherwise the statement -block will be
skipped and the execution will jump to the statement –X. If the condition is true both the
statement –block sequence .
Flow chart :
Ex : If(category = sports)
} printf(“%d”,marks);
If the student belongs to the sports category then additional bonus marks are added to
his marks before they are printed. For other bonus marks are not added .
If –Else Statement : The If statement is an extension of the simple If statement the general form
is
If (test expression)
true-block statements;
else
false-block statements;
statement – x;
If the test expression is true then block statement are executed, otherwise the false –block
statement are executed. In both cases either true-block or false-block will be executed not both.
Flow chart :
Ex : If (code == 1)
boy = boy + 1;
else
girl = girl + 1;
st-x;
Here if the code is equal to ‘1’ the statement boy=boy+1; Is executed and the control is
transfered to the statement st-n, after skipping the else part. If code is not equal to ‘1’ the
statement boy =boy+1; is skipped and the statement in the else partgirl =girl+1; is executed
before the control reaches the statement st-n.
Nested If –else statement : When a series of decisions are involved we may have to use more
than one if-else statement in nested form of follows .
If(test expression)
{ if(test expression)
{ st –1;
else
{ st – 2;
}else
st – 3;
}st – x;
If the condition is false the st-3 will be executed otherwise it continues to perform the
nested If –else structure (inner part ). If the condition 2 is true the st-1 will be executed
otherwise the st-2 will be evaluated and then the control is transferred to the st-x
If ( test condition1)
{ if (test condition2)
st –1 ;
} else
if (condition 3)
{ if (condition 4)
st – 2;
}st – x;
Else-If ladder : A multi path decision is charm of its in which the statement associated with
each else is an If. It takes the following general form.
If (condition1)
St –1;
Else If (condition2)
St –2;
Else if (condition 3)
St –3;
Else
Default – st;
St –x;
This construct is known as the wise-If ladder. The conditions are evaluated from the top
of the ladder to down wards. As soon as a true condition is found the statement associated with
it is executed and the control the is transferred to the st-X (i.e.., skipping the rest of the ladder).
when all the n-conditions become false then the final else containing the default – st will be
executed.
Switch Statement : Instead of else –if ladder, ‘C’ has a built-in multi-way decision statement
known as a switch. The general form of the switch statement is as follows.
Switch (expression)
break;
break;
break;
st – x;
The expression is an integer expression or character value1, value-2---- are constants or
constant expressions and also known as case lables. Each of the values should be a unit within a
switch and may contain zero or more statements.
When the switch is executed the value of the expression is successively compared against
the values value-1,value-2------- If a case is found whose value matches with the of the
expression then the block of statements that follows the case are executed .
The break statement at the end of each block signals the end a particular case and causes
an exist from the switch statement transfering the control to the st-x following the switch. The
default is an optional case . If will be executed if the value of the expression doesn’t match with
any Of the case values then control goes to the St-x.
Ex : switch (number)
case 1 : printf(“Monday”);
break;
case 2 : printf(“Tuesday”);
break;
case 3 : printf(“Wednesday”);
break;
case 4 : printf(“Thursday”);
break;
case 5 : printf(“Friday”);
break;
default : printf(“Saturday”);
break;
The Conditional ( ? : ) Operator : These operator is a combinations of question and colon and
takes three operands this is also known as conditional operator. The general form of the
conditional operator is as follows
Conditional expression? Expression 1:expression2
Ex : flag = ( x<0) ? 0 : 1
If ( x<0)
Flag = 0;
Else
Flag = 1;
Goto Statement : The goto statement is used to transfer the control of the program from one
point to another. It is something reffered to as unconditionally branching. The goto is used in the
form
Goto label;
Label statement : The label is a valid ‘C’ identifier followed by a colon. we can precode any
statement by a label in the form
Label : statement ;
This statement immediately transfers execution to the statement labeled with the label
identifier.
Ex : i = 1;
bc : if(1>5) Output : 1
goto ab; 2
printf(“%d”,i); 3
++i; 4
goto bc; 5
ab : {
printf(“%d”,i); }
How to use Loops in C
In any programming language including C, loops are used to execute a set of statements
repeatedly until a particular condition is satisfied.
How it Works
The below diagram depicts a loop execution,
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false
then the execution breaks out of the loop. After the loop is successfully executed the execution
again starts from the Loop entry and again checks for the Test condition, and this keeps on
repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop
body. After every execution of the loop body, condition is verified, and if it is found to
be true the loop body is executed again. When the condition check returns false, the loop body is
not executed, and execution breaks out of the loop.
Types of Loop
There are 3 types of Loop in C language, namely:
while loop
1. for loop
2. do while loop
while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
1 2 3 4 5 6 7 8 9 10
for loop
forloop is used to execute a set of statements repeatedly until a particular condition is satisfied.
We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the
condition. In this loop we can have more than one initialization or increment/decrement,
separated using comma operator. But it can have only one condition.
The for loop is executed as follows:
It first evaluates the initialization code.
3. Then it evaluate the increment/decrement condition and again follows from step 2.
4. When the condition expression becomes false, it exits the loop.
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
1 2 3 4 5 6 7 8 9 10
void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}
21
321
4321
54321
do while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such
situations can be handled with the help of do-while loop. do statement evaluates the body of the
loop first and at the end, the condition is checked using while statement. It means that the body
of the loop will be executed at least once, even though the starting condition inside while is
initialized to be false. General syntax is,
do
{
.....
.....
}
while(condition)
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50
2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On
encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.