UNIT3
UNIT3
While loop
A while loop in C programming repeatedly executes a target statement as long as a
given condition is true.
Syntax
The syntax of a while loop in C programming language is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any nonzero value. The loop
iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately
following the loop.
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
return 0;
}
Output
The value entered by the user is stored in the variable num . Suppose, the
user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since the
test expression count<=num (1 less than or equal to 10) is true, the body
of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2.
Again, the test expression is evaluated. Since 2 is also less than 10, the
test expression is evaluated to true and the body of the for loop is
executed. Now, sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the
loop terminates.
Then, the value of sum is printed on the screen.
Do While-
The do while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.
syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested.
Flow Diagram
Example
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
For Loop-
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a 'for' loop −
The init step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement
here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and the flow of control jumps
to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.
The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.
Flow Diagram
Example
Live Demo
#include <stdio.h>
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
C break statement
The break is a keyword in C which is used to bring the program control out of the loop.
The break statement is used inside loops or switch statement. The break statement
breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop
first and then proceeds to outer loops. The break statement in C can be used in the
following two scenarios:
Syntax:
1. //loop or switch case
2. break;
Example
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output
Goto Statement in C
The C goto statement is a jump statement which is sometimes also
referred to as an unconditional jump statement. The goto statement
can be used to jump from anywhere to anywhere within a function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to
the statement marked as a label. Here, the label is a user-defined
identifier that indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The
‘label:’ can also appear before the ‘goto label;’ statement in the above
syntax.
FlowChart Of goto Statement
Examples:
In this case, we will see a situation similar to as shown in Syntax1 above.
Suppose we need to write a program where we need to check if a number is
even or not and print accordingly using the goto statement. The below
program explains how to do this:
// C program to check if a number is
// even or not using goto statement
#include <stdio.h>
even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}
int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}
Output:
26 is even
continue statement
The continue statement in C programming works somewhat like
the break statement. Instead of forcing termination, it forces the next iteration of the
loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For
the while and do...while loops, continue statement causes the program control to
pass to the conditional tests.
Syntax
The syntax for a continue statement in C is as follows −
continue;
Flow Diagram
Example
Live Demo
#include <stdio.h>
int main () {
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
} while( a < 20 );
return 0;
}
OUTPUT-
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
ARRAY
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array
Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will
learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
For example,
float mark[5];
Here, we haven't specified the size. However, the compiler knows its size is
5 as we are initializing it with 5 elements.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Example-
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Multi-dimensional Arrays in C
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size [x][y], you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid
C identifier. A two-dimensional array can be considered as a table which
will have x number of rows and y number of columns. A two-dimensional
array a, which contains three rows and four columns can be shown as
follows −
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Initialization of a 3d array
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Output
Sum Of Matrix:
2.2 0.5
-0.9 25.0
Example : Three-dimensional array
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Run Code
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
// valid
// Illegal
char str[4];
str = "hello";
Method Description
STRUCTURE
structure is user defined data type available in C that allows to
combine data items of different kinds.
Structures are used to represent a record. Suppose you want to
keep track of your books in a library. You might want to track the
following attributes about each book −
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member. The format of the struct statement is as
follows −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the
arrow operator to access the members.
UNION
A union is a special data type available in C that allows to store different data types
in the same memory location. You can define a union with many members, but only
one member can contain a value at any given time. Unions provide an efficient way of
using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the union's
definition, before the final semicolon, you can specify one or more union variables but
it is optional. Here is the way you would define a union type named Data having three
members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Example-
#include <stdio.h>
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
union un var1;
var1.member1 = 15;
var1.member1);
return 0;
Output
The value stored in member1 = 15
// Or
Example-
#include<stdio.h>
int main()
day = Wed;
printf("%d",day);
return 0;
}
Output: 2
In the above example, we declared “day” as the variable and the value of
“Wed” is allocated to day, which is 2. So as a result, 2 is printed.