Unit 2
Unit 2
Loops Structures: For Loop, While, Do-while loop – Arrays: - One while (condition)
Dimensional Array, Two-dimensional Arrays, Character Arrays and Strings – {
Functions: Function with arrays- Function with decision and looping statements - Statement(s);
Recursion. }
Example:
Loop Structures in C #include<stdio.h>
Loop is used to execute the block of code several times according to the #include<conio.h>
condition given in the loop. void main()
The looping can be defined as repeating the same process multiple times {
until a specific condition satisfies. int num=1;
Advantage of loops in C while(num<=2)
1) It provides code reusability. {
2) Using loops, we do not need to write the same code again and again. printf("%d\n",num);
3) Using loops, we can traverse over the elements of data structures (array num++; //incrementing operation
or linked lists). }
Types of Loops in C }
1. Entry controlled loop Output:
A condition is checked before executing the body of a loop. 1
It is also called as a pre-checking loop. 2
Example: while loop, For loop. do…while loop
2. Exit controlled loop It is also called an exit-controlled loop.
A condition is checked after executing the body of a loop. In the do-while loop, the body of a loop is always executed at least once.
It is also called as a post-checking loop. After the body is executed, then it checks the condition.
Example : do...while loop If the condition is true, then it will again execute the body of a loop
While loop (Or) While statement otherwise control is transferred out of the loop.
It is an entry-controlled loop. In do-while loop, the while condition is written at the end and terminates
In while loop, a condition is evaluated before processing a body of the with a semi-colon (;)
loop. Syntax:
If a condition is true then and only then the body of a loop is executed. do
After the body of a loop is executed then control again goes back at {
the beginning ofthe program Statement(s);
The condition is checked if it is true; the same process is executed } while (condition);
until thecondition becomes false.
Once the condition becomes false, the control goes out of the loop. Example
After exiting the loop, the control goes to the statements which are #include<stdio.h>
immediatelyafter the loop. #include<conio.h>
The body of a loop can contain more than one statement. If it void main()
contains only onestatement, then the curly braces are not compulsory.
{ For Loop
int num=1; //initializing the variable The for loop is also called as a per-tested loop.
do It is better to use for loop if the number of iteration is known in advance.
{ Syntax
printf(“%d \n”, 2*num);
for (initial value; condition; increment or decrement )
num++;
{
} while (num <= 5);
Statement(s);
}
Output: }
2
Example:
4
#include<stdio.h>
6
void main()
8
{
10
int number;
Differences between while loop and do..while loop
for(number=1;number<=3;number++) //for loop to print 1-10 numbers
Parameters while do...while {
printf("%d\n",number); //to print the number
Controlling The while loop is an entry-controlled The do-while loop is an exit- }
type of loop. controlled type of loop. }
Output:
Checking of Condition is checked first then Statement(s) is executed atleast 1
Condition statement(s) is executed. once, thereafter condition is 2
checked. 3
ARRAYS
Semicolon No semicolon at the end of while. Semicolon at the end of while. It is the collection of similar type of data items stored at contiguous
memory locations.
while(condition) while(condition); An array is a group (or collection) of same data types.
Requiremen If there is a single statement, Brackets are always required. All arrays consist of contiguous memory locations. The lowest address
t of Brackets brackets are not required. corresponds to the first element and the highest address to the last
element.
Syntax while(condition) do
{
{
statement(s);
} statement(s);
} while(condition);
Properties of Array Disadvantage of Array
Each element of an array is of same data type and carries the same size, i.e., int
1) Fixed Size: Whatever size, we define at the time of declaration of the array,
= 4 bytes.
we can't exceed the limit.
Elements of the array are stored at contiguous memory locations where the
Types of Array
first element is stored at the smallest memory location.
1. One dimensional array
Elements of the array can be randomly accessed since we can calculate the
2. Two dimensional array
address of each element of the array with the given base address and the size
3. Multi-dimensional array
of the data element.
Declaration of an array:
Characteristics of Array An array must be declared before it is used.
During declaration, the size of the array has to be specified.
1. Arrays are always stored in consecutive memory locations.
The size used during declaration of the array informs the compiler to
2. An array can store multiple values of a similar type which can be referred allocate and reserve the specified memory locations.
to by a single name. Syntax
data_type array_name[n];
3. The array name is actually a pointer to the first location of the memory where,
block allocated to the name of the array. n -> number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
4. An array either an integer, character, or float data type can be initialized Example:
only during the declaration but not afterward. int a[5];
float x[10];
5. Any particular element of an array can be modified separately without ONE DIMENSIONAL ARRAY
distributing other elements. A one-dimensional array (or single dimension array) is a type of linear
6. All elements of an array said the same name and they are distinguished array.
from each other with the help of element number. Accessing its elements involves a single subscript which can either
Advantages of Array represent a row or column index.
1) Code Optimization: Less code to the access the data. Rules for Declaring One Dimensional Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily. 1. An array variable must be declared before being used in a program.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code 2. The declaration must have a data type(int, float, char, double, etc.),
only.
4) Random Access: We can access any element randomly using the array. variable name, and subscript.
3. The subscript represents the size of the array. If the size is declared as 10, #include<stdio.h>
programmers can store 10 elements. void main()
4. An array index always starts from 0. For example, if an array variable is {
declared as s[10], then it ranges from 0 to 9. int arr[3];
5. Each array element is stored in a separate memory location. int i, j;
Declaration of One Dimensional Arrays printf("Enter array element :");
To declare an array in C, a programmer specifies the type of the elements for(i = 0; i < 2; i++)
and the number of elements required by an array as follows: {
type arrayName [ arraySize ]; scanf("%d", &arr[i]); //Run time array initialization
Example: }
double balance[10]; printf("Array elements are : ");
int a[10]; for(j = 0; j < 2; j++)
Initialization of One-Dimensional Array {
An array can be initialized at the following states: printf("%d\n", arr[j]);
1. At compiling time (static initialization) }
2. At Run time Initialization (Dynamic Initialization) }
Compiling time initialization: Output:
The compile-time initialization means the array of the elements is Enter array element:
10
initialized at the time the program is written or array declaration.
20
Syntax : data_type array_name [array_size] = {list of elements of an array}; Array elements are
10
Example : int n[5]={0, 1, 2, 3, 4};
20
Run time initialization: Two-Dimensional Array
Run time initialization means the array can be initialized at runtime. Two Dimensional Array requires Two Subscript Variables
It means array elements are initialized after the compilation of the Two Dimensional Array stores the values in the form of matrix.
program. One Subscript Variable denotes the “Row” of a matrix.
Another Subscript Variable denotes the “Column” of a matrix.
Example:
Strings
String is a sequence of characters that are treated as a single data item
and terminated by a null character '\0'.
C does not support string as a data type.
It allows us to represent strings as character arrays.
In C, a string variable is any valid C variable name and is always declared
as an array of characters.
Declaration of Two-Dimensional Array Declaring Strings:-
Syntax : datatype arrayName [ rowSize ] [ columnSize ]; Syntax:- char string_name[size];
Example : int a[10] [10] The size determines the number of characters in the string name.
Initialization of Two-Dimensional Array Ex:- char city[10]; char name[30];
strcpy( ) function
It copies the second string argument to the first string argument.
Syntax : strcpy(string1,string2);
Example : char str1[]=”HOME”;
strcpy(s1, "Home");
strcpy(s2, s1);
FUNCTIONS log()
Functions are a group of statements that have been given a name. sin()
This allows you to break your program down into manageable pieces and pow() etc. are provided in the library of functions.
reuse your code. These are selective.
ADVANTAGES OF FUNCTIONS o User-defined functions
1. Using Function, large program can be sub-divided into self-contained and USER-DEFINED FUNCTION
convenient small modules having unique name. User-defined functions are those functions which are defined by the user
2. The length of source program can be reduced by using function. at the time of writing program.
3. By using function, memory space can be properly utilized. Also less In C programming user can write their own function for doing a specific
memory is required to run program if function is used. task in the program. Such type of functions in C is called user-defined
4. Function increases the execution speed of the program and makes the functions.
programming simple. ELEMENTS OF USER-DEFINED FUNCTION
5. By using the function, portability of the program is very easy. Function declaration or prototype.
6. It removes the redundancy (occurrence of duplication of programs) i.e. Function call.
avoids the repetition and saves the time and space. Function definition.
7. Debugging (removing error) becomes very easier and fast using the Return statement.
function sub-programming. (a) Function prototype
8. Functions are more flexible than library functions. A function prototype is simply the declaration of a function that specifies
9. Testing (verification and validation) is very easy by using functions. function's name, parameters and return type. It doesn't contain function
TYPES OF FUNCTIONS body.
The functions are classified into Syntax of function prototype
o Standard functions returnType functionName(type1 argument1, type2 argument2, ...);
The standard functions are also called library functions or Example:
built in functions. int addNumbers(int a, int b);
sqrt()
abs()
In the above example, the function prototype which provides the In programming, argument refers to the variable passed to the function.
following information to the compiler: In the above example, two variables n1 and n2 are passed during the
o name of the function is addNumbers() function call.
o return type of the function is int The parameters a and b accepts the passed arguments in the function
o two arguments of type int are passed to the function definition. These arguments are called formal parameters of the function.
(b) Function Call (Or) Calling a function
Control of the program is transferred to the user-defined function by
calling it.
Syntax of function call
functionName(argument1, argument2, ...);
Example: addNumbers(n1,n2)
In the above example, the function call is made using addNumbers(n1,
(d) Return Statement
n2); statement inside the main() function.
The return statement terminates the execution of a function and returns
(c) Function definition
a value to the calling function.
Function definition contains the block of code to perform a specific task.
The program control is transferred to the calling function after the return
In our example, adding two numbers and returning it.
statement.
Syntax of function definition
Syntax: return (expression);
returnType functionName(type1 argument1, type2 argument2, ...)
For example,
{ return a;
//body of the function return (a+b);
The type of value returned from the function and the return type
}
specified in the function prototype and function definition must match.
When a function is called, the control of the program is transferred to the
function definition. And, the compiler starts executing the codes inside
the body of a function.
Passing arguments to a function
return result; // return statement
}
CATEGORY OF FUNCTIONS
There can be 4 different types of user-defined functions, they are:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
5. Functions that return multiple values
1. Function with no arguments and no return value
In this category, the function has no arguments. It does not receive any
Example Program
data from the calling function. Similarly, it doesn’t return any value. The
#include <stdio.h>
calling function doesn’t receive any data from the called function. So,
int addNumbers(int a, int b); // function prototype
there is no communication between calling and called functions.
void main()
It is used to display information or they are completely dependent on
{
user inputs.
int n1,n2,sum;
Example Program
printf("Enters two numbers: ");
A function, which takes 2 numbers as input from user, and display which
scanf("%d %d",&n1,&n2);
is the greater number.
sum = addNumbers(n1, n2); // function call
#include<stdio.h>
printf("sum = %d",sum);
void greatNum(); // function declaration
}
void main()
int addNumbers(int a, int b) // function definition
{
{
greatNum(); // function call
int result;
return 0;
result = a+b;
}
void greatNum() // function definition int greatNum(); // function declaration
{ void main()
int i, j; {
printf("Enter 2 numbers that you want to compare..."); int result;
scanf("%d%d", &i, &j); result = greatNum(); // function call
if(i > j) { printf("The greater number is: %d", result);
printf("The greater number is: %d", i); }
} int greatNum() // function definition
else { {
printf("The greater number is: %d", j); int i, j, greaterNum;
} printf("Enter 2 numbers that you want to compare...");
} scanf("%d%d", &i, &j);
Output: if(i > j)
Enter 2 numbers that you want to compare.... {
4 greaterNum = i;
3 }
The greater number is: 4 else
2. Function with no arguments and no return value {
greaterNum = j;
In this category, the function has no arguments and it doesn’t receive any }
data from the calling function, but it returns a value to the calling // returning the result
function. return greaterNum;
The calling function receives data from the called function. So, it is one }
way data communication between calling and called functions. Output:
Example Program: Enter 2 numbers that you want to compare....
#include<stdio.h> 4
3 }
The greater number is: 4 }
3. Function with arguments and no return value Output:
In this category, function has some arguments. It receives data from the Enter 2 numbers that you want to compare....
calling function, but it doesn’t return a value to the calling function. 4
The calling function doesn’t receive any data from the called function. So, 3
it is one way data communication between called and calling functions. The greater number is: 4
Example Program 4. Function with arguments and a return value
#include<stdio.h> In this category, a function has some arguments and it receives data from
void greatNum(int a, int b); // function declaration the calling function.
void main() Similarly, it returns a value to the calling function. The calling function
{ receives data from the called function. So, it is two-way data
int i, j; communication between calling and called functions.
printf("Enter 2 numbers that you want to compare..."); Example Program
scanf("%d%d", &i, &j); #include<stdio.h>
greatNum(i, j); // function call int greatNum(int a, int b); // function declaration
} void main()
void greatNum(int x, int y) // function definition {
{ int i, j, result;
if(x > y) printf("Enter 2 numbers that you want to compare...");
{ scanf("%d%d", &i, &j);
printf("The greater number is: %d", x); result = greatNum(i, j); // function call
} printf("The greater number is: %d", result);
else }
{ int greatNum(int x, int y) // function definition
printf("The greater number is: %d", y); {
if(x > y) void main()
{ {
return x; int x = 10;
} calc(x);
else // this will print the value of 'x'
{ printf("\n value of x in main is %d", x);
return y; }
} void calc ( int x)
} {
Output: // changing the value of 'x'
Enter 2 numbers that you want to compare.... x = x + 10 ;
4 printf("value of x in calc function is %d ", x);
3 }
The greater number is: 4 Output
value of x in calc function is 20
Types of Function calls in C value of x in main is 10
1. Call by Value
2. Call by Reference 2. Call by Reference
1. Call by Value In call by reference we pass the address (reference) of a variable as
Calling a function by value means, we pass the values of the arguments argument to any function. When we pass the address of any variable as
which are stored or copied into the formal parameters of the function. argument, then the function will have access to our variable, as it now
Hence, the original values are unchanged only the parameters inside the knows where it is stored and hence can easily update its value.
function changes. In this case the formal parameter can be taken as a reference or a
Example Program: pointer(don't worry about pointers, we will soon learn about them), in
#include<stdio.h> both the cases they will change the values of the original variable.
void calc(int x); Example Program
#include<stdio.h> Returning an Array from a function
void calc(int *p); // function taking pointer as argument int* sum (int x[])
void main() {
{ // statements
int x = 10; return x ;
calc(&x); // passing address of 'x' as argument }
printf("value of x is %d", x); PASSING ARRAYS AS PARAMETER TO FUNCTION
return(0); Pass a single array element as argument to a function, a one dimensional
} array to a function and a multidimensional array to a function.
void calc(int *p) //receiving the address in a reference pointer variable Example:
{ #include<stdio.h>
/* changing the value directly that is stored at the address void giveMeArray(int a);
passed */ void main()
*p = *p + 10; {
} int myArray[] = { 2, 3, 4 };
Output giveMeArray(myArray[2]); //Passing array element myArray[2] only.
Value of x is 20 }
FUNCTIONS WITH ARRAYS void giveMeArray(int a)
To pass a list of elements as argument to any functions in C language, it is {
prefered to do so using an array. printf("%d", a);
Declaring Function with array as a parameter }
There are two possible ways Output: 4
o using call by value and RECURSION
o using call by reference. A function that calls itself is known as a recursive function. And, this
Example: int sum (int arr[]); technique is known as recursion.
int sum (int* ptr); Syntax
function1() int r = 1;
{ if(x == 1)
// function1 body return 1;
function1(); else
// function1 body r = x*factorial(x-1); //recursion, since the function calls itself
} return r;
}
Output:
Enter a number...
5
The factorial of given number 5 is = 120
Important Questions:
1. Discuss about for loop with example.
Example Program
2. Distinguish between while loop and do..while loop.
#include<stdio.h>
3. Describe about do...while loop in C.
int factorial(int x); //declaring the function
4. Give a note on One dimensional array with an example.
void main()
5. Write about two-dimensional array with an example.
{
6. Elaborate the character array with example.
int a, b;
7. Discuss in detail about string functions in C.
printf("Enter a number...");
8. Briefly explain the categories of Functions in C.
scanf("%d", &a);
9. What is meant by recursion? Explain with example.
b = factorial(a); //calling the function named factorial
printf("The factorial of given number %d is = %d", a,b);
}
int factorial(int x) //defining the function
{