[go: up one dir, main page]

0% found this document useful (0 votes)
13 views26 pages

UNIT3

The document provides an overview of control structures in C programming, including while loops, do while loops, for loops, break statements, goto statements, continue statements, and arrays. It explains the syntax and functionality of each control structure, along with examples and output results. Additionally, it covers the properties, advantages, and disadvantages of arrays, as well as how to declare and initialize both one-dimensional and multi-dimensional arrays.

Uploaded by

Rudraksha Shukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views26 pages

UNIT3

The document provides an overview of control structures in C programming, including while loops, do while loops, for loops, break statements, goto statements, continue statements, and arrays. It explains the syntax and functionality of each control structure, along with examples and output results. Additionally, it covers the properties, advantages, and disadvantages of arrays, as well as how to declare and initialize both one-dimensional and multi-dimensional arrays.

Uploaded by

Rudraksha Shukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-3

 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;

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when num is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

return 0;
}

Output

Enter a positive integer: 10


Sum = 55

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 () {

/* local variable definition */


int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

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;

/* for loop execution */


for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", 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:

1. With switch case


2. With loop

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

0 1 2 3 4 5 came outside of loop i = 5

 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>

// function to check even or not


void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;

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 () {

/* local variable definition */


int a = 10;

/* do loop execution */
do {

if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}

printf("value of a: %d\n", a);


a++;

} 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 declared an array, mark , of floating-point type. And its size is 5.


Meaning, it can hold 5 floating-point values.

How to initialize an array?


It is possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.

int mark[] = {19, 10, 8, 17, 9};

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];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
 Multi-dimensional Arrays in C

C programming language allows multidimensional arrays. Here is the


general form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer
array −
int threedim[5][10][4];

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 −

Thus, every element in the array a is identified by an element name of the


form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the
subscripts that uniquely identify each element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values
for each row. Following is an array with 3 rows and each row has 4
columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

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

You can initialize a three-dimensional array in a similar way to a two-


dimensional array. Here's an example,

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}}};

Example : Sum of two matrices

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0
Example : Three-dimensional array

// C Program to store and print 12 values entered by the user

#include <stdio.h>
int main()
{
int test[2][3][2];

printf("Enter 12 values: \n");

for (int i = 0; i < 2; ++i)


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with the proper index.

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

An Array of Strings in C


String is a sequence of characters that are treated as a single data
item and terminated by a null character '\0'. Remember that the C
language does not support strings as a data type. A string is
actually a one-dimensional array of characters in C language. These
are often used to create meaningful and readable programs.
For example: The string "home" contains 5 characters including
the '\0' character which is automatically added by the compiler at the
end of the string.
Declaring and Initializing a string variables:

// valid

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

// Illegal

char ch[3] = "hello";

char str[4];

str = "hello";

String Handling Functions:

C language supports a large number of string handling functions


that can be used to carry out many of the string manipulations.
These functions are packaged in the string.h library. Hence, you
must include string.h header file in your programs to use these
functions.

The following are the most commonly used string handling


functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show the length of a string

strrev() It is used to show the reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

 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];

. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand


struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.

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.

Initialize Structure Members


Structure members cannot be initialized with the declaration. For example,
the following C program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no
memory is allocated for it. Memory is allocated only when variables are
created.
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.

 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;

Now, a variable of Data type can store an integer, a floating-point


number, or a string of characters. It means a single variable, i.e., same
memory location, can be used to store multiple types of data. You can
use any built-in or user defined data types inside a union based on your
requirement.

Example-

// C Program to demonstrate how to use union

#include <stdio.h>

// union template or declaration

union un {

int member1;

char member2;

float member3;

};

// driver code

int main()
{

// defining a union variable

union un var1;

// initializing the union member

var1.member1 = 15;

printf("The value stored in member1 = %d",

var1.member1);

return 0;

Output
The value stored in member1 = 15

Enumerated Data Types-


The enumerated data type is also known as the enum in the C language. Now, enum is
not a basic, but a user-defined form of data type that consists of various integer values, and
it functions to provide these values with meaningful names. Using the enum data type in C
language makes any program much easier to maintain as well as understand. We define
enums using the keyword “enum”.

enum State {Working = 1, Failed = 0};


The keyword ‘enum’ is used to declare new enumeration types in C
Variables of type enum can also be defined. They can be defined in two
ways:
// In both of the below cases, "day" is
// defined as the variable of type week.

enum week{Mon, Tue, Wed};


enum week day;

// Or

enum week{Mon, Tue, Wed}day;

Example-

/ An example program to demonstrate working of enum in C

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

enum week day;

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.

You might also like