Unit 2 - Programming in C
Unit 2 - Programming in C
Conditional Branching statements, Iterative statements, Nested loops, The Break and continue statements, Goto
statements; Introduction to Functions: Function declaration, Function definition, Function call, return statement,
passing parameters to the function, Recursive Functions; Introduction to Arrays: Declaration, Accessing the
Elements, storing values, operations on arrays, Passing Arrays to functions, two-dimensional array,
Multidimensional arrays.
Example:
#include <stdio.h>
void main() {
int num = -5;
if (num > 0) {
printf("The number is positive.\n");
}
else {
printf("The number is non-positive.\n");
}
}
Output:
The number is non-positive.
The if-else-if Statement
if else if statement in C programming is used to test a series of conditions sequentially. Furthermore, if a condition
is tested only when all previous if conditions in the if-else ladder are false. If any of the conditional expressions
evaluate to be true, the appropriate code block will be executed, and the entire if-else ladder will be terminated.
if else if expression has the following syntax:
if (condition) {
// Code to execute if condition is true
}
else if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if all the above conditions are false
}
Example:
#include <stdio.h>
void main() {
int a=5,b=10,c=8;
if (a>b && a>c) {
printf("a is greater\n");
}
else if(b>c){
printf("b is greater");
}
else {
printf("c is greater");
}
}
Output:
b is greater
The switch Statement:
Multiple actions can be taken using the "switch" statement based on the value of a variable or expression. When
managing several instances, it is especially helpful. The "switch" statement has the following syntax:
switch (expression) {
case constant1:
// Code to execute if expression matches constant1
break;
case constant2:
// Code to execute if expression matches constant2
break;
// More cases...
default:
// Code to execute if expression doesn't match any constant
}
Example:
#include <stdio.h>
void main() {
int num = 2;
switch (num) {
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break;
}
return 0;
}
Output:
Value is 2
2.1.2 Unconditional Branching Statements:
C uses unconditional branching statements to alter the typical course of program execution. These statements
give programmers the freedom to jump to a specific location in their code under any circumstance. The various
categories of unconditional branching statements in C are as follows:
i. goto Statement
ii. break Statement
iii. continue Statement
The goto Statement:
The "goto" command is used to transfer the program control to a predefined label. It is an unconditional branching
statement.
Example:
#include <stdio.h>
void main()
{
int age;
printf("Enter your age: ");
scanf("%d",&age);
vote:
printf("You are eligible to vote");
novote:
printf("You are not eligible to vote");
if(age>=18)
goto vote;
else
goto novote;
}
Output:
Enter your age: 19
You are eligible to vote
The 'break' Statement:
The "break" statement is frequently employed in switch statements as well as looping constructions like "for",
"while", and "do-while". It enables you to skip the statement that follows the loop or switch and end the execution
of the closest enclosing loop or switch statement. The "break" statement in C is written in the following syntax.
break;
Example:
#include <stdio.h>
void main() {
int i;
for (i = 1; i< =10; i++) {
if (i == 5)
break;
printf("%d\t", i);
} }
Output:
1 2 3 4
The continue Statement:
In the C programming language, the continue statement is used to go to the next iteration of a loop while skipping
the current iteration. Usually, this statement is used in loops like for or while. Syntax of continue statement in C
is as follows:
continue;
Example:
#include <stdio.h>
void main() {
int i;
for (i = 1; i< =10; i++)
{
if (i == 5)
break;
printf("%d\t", i);
}
}
Output:
1 2 3 4 6 7 8 9 10
Example:
#include <stdio.h>
void main(){
int i = 0;
do {
printf("Hello World\n");
i++;
} while (i < 3);
}
Output:
Hello World
Hello World
Hello World
The for loop in C
The for loop is used in the case where we need to execute some part of the code until the given condition is
satisfied. The for loop is also called as a pre-tested loop. The syntax of for loop in c language is given below:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
#include <stdio.h>
void main()
{
int i;
for(i=0;i<3;i++)
{
printf("Hello World\n");
}
}
Output:
Hello World
Hello World
Hello World
Nested Loops
Nesting of loops is the feature in C that allows the looping of statements inside another loop.
Syntax of Nested loop
Outer_loop {
Inner_loop {
// inner loop statements.
}
// outer loop statements.
}
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of
loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for
example, you can define 'while' loop inside a 'for' loop.
Example:
#include <stdio.h>
void main()
{
for(int i=1;i<=3;i++) // outer loop
{
for(int j=1;j<=5;j++) // inner loop
{
printf("*\t"); // printing the value.
}
printf("\n");
}
}
Output:
* * * * *
* * * * *
* * * * *
2.3 Introduction to Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the
set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection of functions creates a program.
Advantage of functions in C
There are the following advantages of C functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always an overhead in a C program.
Function Aspects
There are three aspects of a C function.
Function declaration: A function must be declared globally in a c program to tell the compiler about the
function name, function parameters, and return type.
return_type function_name (argument list);
Function call: Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in
the function declaration.
function_name (argument_list)
Function definition: It contains the actual statements which are to be executed. It is the most important
aspect to which the control comes when the function is called. Here, we must notice that only one value can
be returned from the function.
return_type function_name (argument list)
{
function body;
}
Types of Functions
There are two types of functions in C programming:
Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), getch(),
clrscr() etc.
User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.
Return Value
A C function may or may not return a value from the function. If you don't have to return any value from the
function, use void for the return type.
Example without return value:
void hello(){
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int, long, char, etc. The
return type depends on the value to be returned from the function.
Example with return value:
int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-
point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.
float get(){
return 10.2;
}
Different aspects of function calling
A function may or may not accept any argument. It may or may not return any value. Based on these facts: There
are four different aspects of function calls.
function without arguments and without return value
function without arguments and with return value
function with arguments and without return value
function with arguments and with return value
Example for Function without argument and return value
#include<stdio.h>
void add();
void main () {
add();
}
void add() {
int a=5,b=2,c;
c=a+b;
printf("Sum= %d",c); }
Output:
Sum= 7
Example for Function without argument and with return value
#include<stdio.h>
int add();
void main () {
int c=add();
printf("Sum= %d",c);
}
int add() {
int a=5,b=2,sum;
sum=a+b;
return sum;
}
Output:
Sum= 7
Example for Function with argument and return value
#include<stdio.h>
int add(int,int);
void main () {
int a=5,b=2,c;
c=add(a,b);
printf("Sum= %d",c);
}
int add(int x,int y) {
int sum=x+y;
return sum;
}
Output:
Sum= 7
Example for Function with argument and without return value
#include<stdio.h>
void add();
void main () {
int a=5,b=2;
add(a,b);
}
int add(int x,int y) {
int sum=x+y;
printf("Sum= %d",sum); }
Output:
Sum= 7
Example
#include<stdio.h>
void main()
{
int i, marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
for(i=0;i<5;i++){ //traversal of array
printf("%d \t",marks[i]);
}
}
Output
80 60 70 85 75
Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
Example
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={80,60,70,85,75};//declaration and initialization of array
for(i=0;i<5;i++){ //traversal of array
printf("%d \n",marks[i]);
}
}
Output
80 60 70 85 75
2.3.1 Operations on arrays
Traverse
Insert − at the specified index, adds an element.
Delete− the element at the specified index is deleted.
Search − Uses the provided index or the value to search for an element.
Merge – Combines two arrays.
Sort – Sort the given array in ascending or descending order
Traversal
Accessing each element in the array one by one.
Example
#include<stdio.h>
int main(){
int i=0;
int arr[5]={80,60,70,85,75};//declaration and initialization of array
for(i=0;i<5;i++){ //traversal of array
printf("Array[%d]: %d \n",i,arr[i]);
}
}
Output
Array[0]: 80
Array[1]: 60
Array[2]: 70
Array[3]: 85
Array[4]: 75
Insertion
− at the specified index, adds an element.
Let's take an array of 5 integers.
1, 20, 5, 78, 30.
If we need to insert an element 100 at position 2, the execution will be,
1. We need to insert element 100 at position 2.
2. Move all the elements from the last index(4) to the position(2) to one position right.
arr[4] (30) will be placed in arr[5].
arr[3] (78) will be placed in arr[4].
arr[2] (5) will be placed in arr[3].
2. Finally, the element 100 is placed at the position 2.
Example
#include<stdio.h>
# define size 5
void main()
{
int arr[size] = {1, 20, 5, 78, 30};
int element, pos, i;
printf("Enter position and element:");
scanf("%d%d",&pos,&element);
if(pos <= size && pos >= 0)
{
//shift all the elements from the last index to pos by 1 position to right
for(i = size; i > pos; i--)
arr[i] = arr[i-1];
//insert element at the given position
arr[pos] = element;
//print the new array
for(i = 0; i <= size; i++)
printf("%d\t", arr[i]);
}
else
printf("Invalid Position\n");
}
Output:
Enter position and element: 2 100
1 20 100 5 78 30
Searching in an Array
− Uses the provided index or the value to search for an element.
Let's take an array of 5 elements.
34, 2, 23, 100, 60.
If we search element 100, the execution will be,
1. 34 != 100. Move to the next element.
Example
#include<stdio.h>
# define size 5
void main()
{
int arr[size] = {1, 20, 5, 78, 30};
int key, i, index = 0;
printf("Enter element to search: ");
scanf("%d",&key);
for(i = 0; i < size; i++) {
if(arr[i] == key) {
index = i;
break;
}
}
if(index != 0) {
printf("Element is found at index: %d",index);
}
else
printf("Element Not Found\n");
}
Output:
Enter element to search: 5
Element is found at index: 2
Deletion
− the element at the specified index is deleted.
Let's take an array of 5 elements.
1, 20, 5, 78, 30.
If we remove element 20 from the array, the execution will be,
1. We need to remove the element 20 (index 1) from the array.
2. Shift all the elements from index + 1 (index 2 to 4) by 1 position to the left.
arr[2] (value 5) will be placed in arr[1].
arr[3] (value 78) will be placed in arr[2].
arr[4] (value 30) will be placed in arr[3].
56 10 30
34 21 34
45 56 78
2.3.3 Multi-Dimensional Array
They allow you to store data in a table-like format, where each row and column can be accessed using an index.
To create a multidimensional array in C, you need to specify the number of dimensions and the size of each
dimension. The general syntax for declaring a multidimensional array is as follows:
data_type array_name[size1][size2]...[sizeN];
Example
#include<stdio.h>
void main(){
int i, j, k;
int arr[3][3][3]= {
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
printf("Printing 3D Array Elements\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++){
for(k=0;k<3;k++){
printf("%4d",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
Output:
Printing 3D Array Elements
11 12 13
14 15 16
17 18 19
21 22 23
24 25 26
27 28 29
31 32 33
34 35 36
37 38 39