Programming for Problem Solving
Unit 2: Introduction to C
June 20, 2023
Contents
1 Introduction to C 3
1.1 Introduction to C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Features of C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Basic C program structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 C tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6 C Operators and precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.7 Type conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.8 Control Structures: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.9 Unconditional control statements- break\Continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
This unit covers
• Introduction to c
• Function of C
• C Program Structure
1 Introduction to C
1.1 Introduction to C
C is a general-purpose, high-level language developed by Dennis M Ritchie to develop the Unix Operating systems.
C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie
introduced the first publicly available description of C, now known as the K&R standard. C is a widely used professional
language for multiple reasons:
1. Easy to learn
2. Structured language
3. Efficient
4. Handles low-level activities
5. Compiled on a variety of computer platforms
1.2 Features of C
Figure 1: Features of C
1. Procedural Language:
In a procedural language like C step by step, predefined instructions are carried out. C program may contain more
than one function to perform a particular task. There are other programming paradigms as well in the programming
world. Most of the commonly used paradigm is an object-oriented programming language.
2. Fast and Efficient:
Newer languages like Java, python offer more features than c programming language but due to additional processing
in these languages, their performance rate gets down effectively. C programming language as the middle-level lan-
guage provides programmers access to direct manipulation with the computer hardware but higher-level languages
do not allow this.
3. Modularity:
The concept of storing C programming language code in the form of libraries for further future uses is known as
modularity. This programming language can do very little on its own most of its power is held by its libraries.
4. Statically Type:
C programming language is a statically typed language. Meaning the type of variable is checked at the time of
compilation but not at run time. This means each time a programmer types a program they have to mention the
type of variables used.
5. General-Purpose Language:
From system programming to photo editing software, the C programming language is used in various applications.
Some of the common applications where it’s used are as follows: Operating systems: Windows, Linux, iOS, Android,
OXS Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc.
6. Rich set of built-in Operators:
It is a diversified language with a rich set of built-in operators which are used in writing complex or simplified C
programs.
7. Libraries with Rich Functions:
Robust libraries and functions in C help even a beginner coder to code with ease.
8. Middle-Level Language:
As it is a middle-level language so it has the combined form of both capabilities of assembly language and features
of the high-level language.
9. Portability:
C language is lavishly portable as programs that are written in C language can run and compile on any system
with either no or small changes.
10. Easy to Extend:
Programs written in C language can be extended means when a program is already written in it then some more
features and operations can be added to it.
1.3 Basic C program structure
1. Writing a ‘C’ program
A typical ‘C program’ consists of the following:
1. Preprocessor Commands
2. Functions
3. Variables
4. Statements and Expressions
5. Comments
Let us look at a simple code that would print the words "Make in India":
Let us look at the above program:
Figure 2:
1. include <stdio.h> is a pre-processor command, which instructs the C compiler to include stdio.h file before going
to actual compilation.
2. int main() is the main function where the program is instructed to begin the execution.
3. The next line /*...*/ tells the compiler not to process what is in there as these are ‘comments’ required to understand
the program flow.
4. printf(...) is a function which causes the message "Make in India!" to be displayed on the screen.
5. The next line returns 0; terminates the main() function and returns the value 0.
1.4 C tokens
A token in C can be defined as the smallest individual element of the C programming language that is meaningful
to the compiler. It is the basic component of a C program. Types of Tokens in C The tokens of C language can be
classified into six types based on the functions they are used to perform. The types of C tokens are as follows:
Figure 3:
1. Keywords:
The keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a
specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable
names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot
redefine keywords. However, you can specify the text to be substituted for keywords before compilation by using C
Figure 17: Precedence of operators
Associativity of Operators
The associativity of operators determines the direction in which an expression is evaluated. For example,
b = a;
Here, the value of a is assigned to b, and not the other way around. It’s because the associativity of the = operator
is from right to left.
Also, if two operators of the same precedence (priority) are present, associativity determines the direction in which
they execute.
Let us consider an example:
1 == 2 != 3
Here, operators == and != have the same precedence. And, their associativity is from left to right. Hence, 1 == 2 is
executed first.
The expression above is equivalent to:
(1 == 2) != 3
Note: If a statement has multiple operators, you can use parentheses () to make the code more readable.
1.7 Type conversion
C Type Conversions:
Type conversion is performed to convert one or both the operands to an appropriate data type before evaluation.
Type conversion means converting one data type value into another data type value. There are two types of type
conversions:
• implicit conversion (also called type coercion)
In the case of implicit type conversions, the compiler automatically converts one data type value into another data
type value. It is also known as Automatic type conversion.
Implicit type conversions can occur during an assignment or while using any other operators. During the assignment,
the R-value is converted to the type of L-value.
For example, in the statement
int a = 17.35;
17.35 which is the value on the right-hand side, is automatically converted into an int type as 17.
When values of different data types are used in arithmetic, relational and logical operators, the value of the lower
size data type is converted automatically into the data type of the higher size before the evaluation.
The conversion order is:
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long
double
• explicit conversion (also called type casting)
A programmer can instruct the compiler to explicitly convert a value of one type to another using a typecast
operator.
When a typecast operator is used explicitly, the type conversion process is called explicit type conversion or type-
casting. This is user-defined.
The syntax for using a typecast operator is:
( data_type ) expression
where the expression is converted to the target data_type enclosed within the parentheses.
Here, the expression may contain constants or variables and the data_type must be a primitive data type or void.
For example, the expression
(float) 1 / 3 is evaluated as 1.0 / 3
yielding 0.333333, whereas 1 / 3 yields 0
In the expression ((int)num)%2, if num is a float variable with value 5.5, then the expression evaluates to 1.
For example, let us understand the following code:
#include <stdio.h>
void main () {
float a, b;
a = 35 / 17;
b = (float) 35 / 17;
printf("a = %f, b = %f\n", a, b);
output:
a = 2.000000, b = 2.058824
1.8 Control Structures:
Control statements control the flow of execution of the statements of a program. The various types of control
statements in C language are as under:-
. 1. Sequential control: - In sequential control, the C program statements are executed sequentially i.e., one after
another from beginning to end.
Figure 18: Sequential control
#include<Stdio.h>
#include<conio.h>
void main()
clrscr();
int x , y, sum;
printf(“enter the two numbers”);
scanf(“%d%d”,&x,&y);
sum=x+y;
printf(“the sum of the two numbers is =%d”,sum);
getch();
2.Conditional Control (Selection Control or Decision Control) - In conditional control, the execution of
statements depends upon the condition-test. If the condition evaluates to true, then a set of statements is executed
otherwise another set of statements is followed. This control is also called Decision Control because it helps in
making decision about which set of statements is to be executed.
. 3.Iteration Control (Loops) -Iterations or loops are used when we want to execute a statement or block of
statements several times. The repetition of loops is controlled with the help of a test condition. The statements in
the loop keep on executing repetitively until the test condition becomes false. There are the following three types
of loops:-
1. While loop
2. Do-while loop
3. For loop
Decision Control Statements-
In computer programming, decision control instructions are used to control the flow of program execution based on a
condition. The decision control instruction evaluates a condition and executes a set of statements based on whether the
condition is true or false.
Using decision control statements we can control the flow of program in such a way so that it executes certain
statements based on the outcome of a condition (i.e. true or false).
In decision control statements, group of statements are executed when condition is true. If condition is false, then
else part statements are executed.
Types of Decision Control Statement
We have three major types of decision control statements that we use in the C programming language. These are:
• If statements
In C programming language, the "if statement" is a decision control statement that is used to execute a block of
code if a certain condition is true.
The if statement is one of the most commonly used decision control statements in C programming, as it allows the
program to make decisions and take different actions based on user input or other factors.
Syntax:
if (condition x)
// A block of statements for the C program
// The execution of these statements will only happen when this condition turns to be true }
Figure 19: If Conditon
PROGRAM FOR IF STATEMENT:
#include<stdio.h>
#include<conio.h>
int main()
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
getch();
• If-Else Statements
– The "if-else statement" in C programming language is a decision control statement that is used to
execute a block of code if a certain condition is true and another block of code if the condition is false.
– In this decision control statement, we have two block of statements. If condition results true then if block
gets executed else statements inside else block executes. else cannot exist without if statement.
Syntax:
The syntax available for the if-else statement will be:
if (condition x)
// The statements present inside the body of if
}
else {
// The statements present inside the body of else
Various times when a user writes that if a condition/ expression is true, then the compiler must take an action. Else,
if that statement is false, then the compiler will take a different action. Thus, we can include an action for either of
the conditions or include just a single statement for the true condition and no action for any other condition. We
use the if-else statement here.
Figure 20: If-Else Statements
Example:
#include <stdio.h>
int main ()
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a < 20 )
{ /* if condition is true then print the following */
printf("a is less than 20\n" );
else
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0; }
When the above code is compiled and executed, it produces the following result
a is not less than 20;
value of a is : 100
• Nested-If Instructions
In C programming language, "nested if statements" are used when there are multiple conditions that need to be
checked in a specific order. A nested if statement is an if statement that is placed inside another if statement.
Syntax:
The syntax available for the nested if statement will be:
if(condition1)
if(condition2)
statements;
else
statements;
else
if(condition3)
Statements;
else
Statements;
}
Figure 21: Nested-If Instructions
When the condition available in the if block is true, there will be an execution of the provided statement. When it
is false, the program will check the next condition. If it is true, the execution of the statement associated with this
condition will occur. In case this one is also false, then there will be a default execution of a final statement. Here,
we may have as many types of cases as possible. However, there must be just one type of default statement.
Example: /*program to find the largest of three numbers*/
#include<stdio.h>
#include<conio.h>
void main()
int a, b,c,large;
printf(“enter the three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
if(a>c) large=a;
else
large=c;
}
else
if(b>c)
large=b;
else
large=c;
printf(“largest number is %d”,large);
getch();
• Switch case- This case statement is a multi-way decision statement which is a simpler version of the if-else block
which evaluates only one variable.
Syntax:
switch (expression)
case expression 1: statement 1;
statement 2;
............
statement n;
break;
case expression 2: statement 1;
statement 2;
..........
statement n;
break;
default: statement 1;
statement 2;
...........
statement n;
}
Figure 22: Switch case
Example: Write a program to check if the character entered is a vowel or not.
#include <stdio.h>
void main( )
char ch;
printf("Enter any character:");
scanf("%c", &ch);
switch(ch)
case ’A’:
case ’a’:
case ’E’:
case ’e’:
case ’I’:
case ’i’:
case ’O’:
case ’o’:
case ’U’:
case ’u’:
printf("%c is a vowel",ch);
break;
default:
printf("%c is not a vowel", ch);
Output:
Enter any character: c
c is not a vowel.
• While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was previously
known to us but in the While loop, the execution is terminated on the basis of the test condition. If the test
condition will become false then it will break from the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
// body of the while loop update_expression;
Figure 23: while loop
Example: C program to illustrate while loop
#include <stdio.h>
// Driver code
int main()
// Initialization expression
int i = 2;
// Test expression
while(i< 10)
// loop body
printf( "Hello World\n");
// update expression
i++;
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
• do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition which is
tested at the end of the body. In the do-while loop, the loop body will execute at least once irrespective of the test
condition.
Syntax:
initialization_expression;
do
// body of do-while loop
update_expression;
} while (test_expression);
Figure 24: do-while loop
Example- C program to illustratedo-while loop
#include <stdio.h>
// Driver code
int main()
// Initialization expression
int i = 2;
do
{ // loop body
printf( "Hello World\n");
// Update expression
i++;
// Test expression
} while (i< 1);
return 0;
Output
Hello World
Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the body will be executed
once.
• For Loop
for loop in C programming is a repetition control structure that allows programmers to write a loop that will be
executed a specific number of times. for loop enables programmers to perform n number of steps together in a
single line.
Syntax-
for (initialize expression; test expression; update expression)
//
// body of for loop //
In for loop, a loop variable is used to control the loop. Firstly, we initialize the loop variable with some value, then
check its test condition. If the statement is true then control will move to the body and the body of for loop will
be executed. Steps will be repeated till the exit condition becomes true. If the test condition will be false then it
will stop.
Initialization Expression: In this expression, we assign a loop variable or loop counter to some value. for example:
int i=1;
Test Expression: In this expression, test conditions are performed. If the condition evaluates to true then the
loop body will be executed and then an update of the loop variable is done. If the test expression becomes false
then the control will exit from the loop. for example, i<=9;
Update Expression: After execution of the loop body loop variable is updated by some value it could be incre-
mented, decremented, multiplied, or divided by any value.