Unit-3
Unit-3
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.
#include <stdio.h>
int main () {
return 0;
}
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
// Print numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
1. #include<stdio.h>
2. int main(){
3. int i=1,number;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }
#include<stdio.h>
void main ()
{
int j = 1;
while(j+=2,j<=10)
{
printf("%d ",j);
}
printf("%d",j);
}
Output
3 5 7 9 11
#include<stdio.h>
void main ()
{
while()
{
printf("hello Javatpoint");
}
}
Output
compile time error: while loop can't be empty
infinite loop
while(1){
//statement
}
#include<stdio.h>
void main ()
{
int x = 10, y = 2;
while(x+y-1)
{
printf("%d %d",x--,y--);
}
}
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
i = 1;
while (i <= n) {
sum += i;
++i;
}
Infinite Loops in C
We come across infinite loops in our code when the compiler does
not know where to stop. It does not have an exit. This means that
either there is no condition to be checked or the condition is
incorrect. This is why an iterator is very important in our loops. And
a proper condition that ends.
#include <stdio.h>
int main()
int i = 0;
while(i == 0)
printf("Infinite loop\n");
return 0;
Copy
In the code above, we are not changing the value on i, hence the
condition in the while loop will never fail.
#include<stdio.h>
int main()
{
int num,i=1,c=0;
printf("/*To Check Number Prime or Not*/\n\nEnter Number : ");
scanf("%d",&num);
while(i<=num)
{
if(num%i==0)
c++;
i++;
}
if(c==2)
printf("\n%d is Prime Number",num);
else
printf("\n%d is Not Prime Number",num);
return 0;
}
1. #include<stdio.h>
2. int main()
3. {
4. int n,sum=0,m;
5. printf("Enter a number:");
6. scanf("%d",&n);
7. while(n>0)
8. {
9. m=n%10;
10. sum=sum+m;
11. n=n/10;
12. }
13. printf("Sum is=%d",sum);
14. return 0;
15. }
Reverse of a number
1. #include<stdio.h>
2. int main()
3. {
4. int n, reverse=0, rem;
5. printf("Enter a number: ");
6. scanf("%d", &n);
7. while(n!=0)
8. {
9. rem=n%10;
10. reverse=reverse*10+rem;
11. n/=10;
12. }
13. printf("Reversed Number: %d",reverse);
14. return 0;
15. }
Armstrong Number in C
Before going to write the c program to check whether the number is Armstrong or not,
let's understand what is Armstrong number.
Armstrong number is a number that is equal to the sum of cubes of its digits. For
example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
1. 371 = (3*3*3)+(7*7*7)+(1*1*1)
2. where:
3. (3*3*3)=27
4. (7*7*7)=343
5. (1*1*1)=1
6. So:
7. 27+343+1=371
Output:
4. do while loop in C
do
.....
.....
while(condition);
Copy
Remember that the semicolon at the end of do-while loop is mandatory. It denotes end of the loop.
#include <stdio.h>
int main()
int n;
scanf("%d", &n);
char name[25];
scanf("%s", name);
do{
printf("%s\n", name);
n--;
return 0;
#include<stdio.h>
void main()
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
Copy
5 10 15 20 25 30 35 40 45 50
#include <stdio.h>
int main() {
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
#include <stdio.h>
int main()
do{
printf("Infinite loop\n");
} while(1);
return 0;
Copy
Another example, with a constant value as condition, which is
always true hence the code will keep on executing.
for loop in C
statement-block;
Copy
1. In the for loop in C language, we have exactly two mandatory
semicolons, one after initialization and second after
the condition.
2. In this loop we can have more than one initialization or
increment/decrement as well, separated using comma
operator.
3. But it can have only one condition.
#include <stdio.h>
int main()
int n;
char name[25];
scanf("%s", name);
printf("%s\n", name);
return 0;
Copy
studytonight
studytonight
Run Code →
#include<stdio.h>
void main( )
int x;
printf("%d\t", x);
Copy
1 2 3 4 5 6 7 8 9 10
3. Nested for loop in C
We can also have nested for loops, i.e one for loop inside
another for loop in C language. This type of loop is generally used
while working with multi-dimensional arrays. To learn more about
arrays and how for loops are used in arrays, check out our tutorial
on arrays in C. Basic syntax for nested for loop is,
for(initialization; condition;
increment/decrement)
for(initialization; condition;
increment/decrement)
statement ;
Copy
Factorial of a Number
Factorial Program in C: Factorial of n is the product of all positive descending integers.
Factorial of n is denoted by n!. For example:
1. 5! = 5*4*3*2*1 = 120
2. 3! = 3*2*1 = 6
1. #include<stdio.h>
2. int main()
3. {
4. int i,fact=1,number;
5. printf("Enter a number: ");
6. scanf("%d",&number);
7. for(i=1;i<=number;i++){
8. fact=fact*i;
9. }
10. printf("Factorial of %d is: %d",number,fact);
11. return 0;
12. }
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
return 0;
}
int i, n;
#include<stdio.h>
#include<math.h>
int main()
int sum,i,t,r;
sum = 0;
while(t != 0)
r = t%10;
sum += r*r*r;
t = t/10;
}
if(sum == i)
printf("\n\t\t\t%d", i);
return 0;
1. break statement in C
int i;
#include <stdio.h>
int main()
int n;
printf("Enter the number of times you want to
print your name:");
scanf("%d", &n);
char name[25];
scanf("%s", name);
if(i % 5 == 0)
break;
printf("%s\n", name);
return 0;
Copy
study
study
study
study
int i;
int main()
int n;
scanf("%d", &n);
char name[25];
scanf("%s", name);
if(i % 2 == 0)
continue;
printf("%d : %s\n",i,name);
return 0;
Copy
3 : study
5 : study
1 while loop
Repeats a statement or group of statements while a given condition is true.
It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
3 do...while loop
It is more like a while statement, except that it tests the condition at the end
of the loop body.
4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.
[Link]. Control Statement & Description
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement.
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the
for(;;) construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
C goto Statement
The goto statement allows us to transfer control of the program to the
specified label .
goto label;
... .. ...
... .. ...
label:
statement;
#include <stdio.h>
int main() {
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Run Code
Output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53
Reasons to avoid goto
The use of goto statement may lead to code that is buggy and hard to
follow. For example,
one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...
Also, the goto statement allows you to do bad stuff such as jump out of the
scope.
That being said, goto can be useful sometimes. For example: to break from
nested loops.
If you think the use of goto statement simplifies your program, you can use
it. That being said, goto is rarely useful and you can create any C
program without using goto altogether.
Here's a quote from Bjarne Stroustrup, creator of C++, "The fact that
'goto' can do anything is exactly why we don't use it."
Syntax
The syntax for a nested for loop statement in C is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do…while loop statement in C programming language is as
follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other
type of loop. For example, a ‘for’ loop can be inside a ‘while’ loop or vice versa.
#include<stdio.h>
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("*");
}
printf("\n");
}
printf("\n----------------------------\n");
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
----------------------------
*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
void main( )
int i, j;
printf("\n");
printf("%d", j);
}
}
Copy
21
321
4321
54321
*
* *
* * *
* * * *
* * * * *
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
Run Code
Example 2: Half Pyramid of Numbers N rows
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Run Code
A
B B
C C C
D D D D
E E E E E
C Program
#include <stdio.h>
int main() {
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want to print in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
for (j = 1; j <= i; ++j) {
printf("%c ", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
}
Run Code
* * * * *
* * * *
* * *
* *
*
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
Run Code
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
C Program
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Run Code
1
2 3
4 5 6
7 8 9 10
C Program
#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}
star.c
#include <stdio.h>
#include <conio.h>
void main()
{
int i, j, rows, k = 0;
printf (" Enter a number to define the rows: \n");
scanf ("%d", &rows);
Output
i->1 to n
j->1 to n-i
k-> 1 to 2*i-1
star.c
#include <stdio.h>
#include <conio.h>
void main()
{
// declare the local variables
int i, j, rows, k, m = 1;
printf (" Enter a number to define the rows: \n");
scanf ("%d", &rows);
printf("\n");
for ( i = rows; i >= 1; i--)
{
for ( j = 1; j <= m; j++)
{
printf (" "); // print the space
}
for ( k = 1; k <= ( 2 * i - 1); k++)
{
printf ("* "); // print the Star
}
m++;
printf ("\n");
}
getch();
}
Output
i->n to 1
20. WAP to convert binary number into decimal number and vice versa.
#include <stdio.h>
#include <math.h>
// function prototype
int convert(long long);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
// function definition
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n!=0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
#include <stdio.h>
#include <math.h>
int main() {
int n, bin;
printf("Enter a decimal number: ");
scanf("%d", &n);
bin = convert(n);
printf("%d in decimal = %lld in binary", n, bin);
return 0;
}
while (n!=0) {
rem = n % 2;
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
return 0;
}
All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
double balance[10];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as
follows −
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All
arrays have 0 as the index of their first element which is also called the base index
and the last index of an array will be total size of the array minus 1. Shown below is
the pictorial representation of the array we discussed above –
Manipulating array elements in C
Language
An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example −
The above statement will take the 10th element from the array and assign the value to
salary variable. The following example Shows how to use all the three above
mentioned concepts viz. declaration, assignment, and accessing arrays −
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
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’.
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 −
float x[3][4];
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it
is likely that most of the arrays you create will be of one or two dimensions.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
}
Printf(“\n”);
}
return 0;
}
The following declaration and initialization create a string consisting of the word
“Hello”. To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
“Hello.”
If you follow the rule of array initialization then you can write the above statement as
follows −
Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the ‘\0’ at the end of the string when it initializes the
array. Let us try to print the above mentioned string −
#include <stdio.h>
int main () {
Strings in C Language
Strings are actually one-dimensional array of characters terminated by
a null character ‘\0’. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word
“Hello”. To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
“Hello.”
Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the ‘\0’ at the end of the string when it initializes the
array. Let us try to print the above mentioned string −
Live Demo
#include <stdio.h>
int main () {
21. WAP that simply takes elements of the array from the user and finds the sum
of these elements.
#include <conio.h>
int main()
{
int a[25],i,n,sum=0;
sum+=a[i];
}
printf("sum of array is : %d",sum);
return 0;
}
22. WAP that inputs two arrays and saves sum of corresponding elements of these
arrays in a third array and prints them.
#include<stdio.h>
void main()
{
int i,ar1[10],ar2[10],sum[10];
printf("Enter first array:-\n");
for(i=0;i<=9;i++)
{
printf("ar1[%d]=",i);
scanf("%d",&ar1[i]);
}
printf("Enter second array:-\n");
for(i=0;i<=9;i++)
{
printf("ar2[%d]=",i);
scanf("%d",&ar2[i]);
}
for(i=0;i<=9;i++)
{
sum[i]=ar1[i]+ar2[i];
}
printf("Sum of arrays:-");
for(i=0;i<=9;i++)
{
printf("\nsum[%d]=%d",i,sum[i]);
}
23. WAP to find the minimum and maximum element of the array.
1 #include <stdio.h>
2
3 #include <conio.h>
4
5
6
7 int main()
8
9{
10 int a[1000],i,n,min,max;
11
12
13 printf("Enter size of the array : ");
14
15
scanf("%d",&n);
16
17
18
printf("Enter elements in array : ");
19 for(i=0; i<n; i++)
20 {
21
22 scanf("%d",&a[i]);
23 }
24
25
26 min=max=a[0];
27
28 for(i=1; i<n; i++)
29 {
30
31
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);
return 0;
}
Matrix addition
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,k;
int a[3][3], b[3][3],c[3][3];
clrscr();
printf("enter first matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter second matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Matrix multiplication
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,k;
int a[3][3], b[3][3],c[3][3];
clrscr();
printf("enter first matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter second matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,sum=0;
int a[3][3];
clrscr();
printf("enter values of matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
//printing matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=sum+a[i][j];
}
printf("sum of row %d is
%d\n",i,sum);
sum=0;
}
for(j=0;j<3;j++)
{
sum=sum+a[j][i];
}
printf("sum of column %d is
%d\n",j,sum);
sum=0;
}
getch();
}
Transpose of matrix
#include <stdio.h>
int main(){
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter rows and columns :
");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix
");
//enter values in matrix
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
Symmetric or not
#include<stdio.h>
#include<stdlib.h>
int main()
{
int m, n, i, j, count = 0;
if(m!=n)
{
printf("Rows not equal to
columns. Therefore Non-Symmetric
Matrix.");
exit(0);
}
return 0;
}
Define Structures
Before you can create structure variables, you need to define its data type.
To define a struct, the struct keyword is used.
Syntax of struct
struct structureName {
dataType member1;
dataType member2;
...
};
For example,
struct Person {
char name[50];
int citNo;
float salary;
};
Here, a derived type struct Person is defined. Now, you can create variables
of this type.
struct Person {
// code
};
int main() {
struct Person person1, person2, p[20];
return 0;
}
struct Person {
// code
} person1, person2, p[20];
In both cases,
1. . - Member operator
2. -> - Structure pointer operator (will be discussed in the next tutorial)
Suppose, you want to access the salary of person2 . Here's how you can do it.
[Link]
Example 1: C structs
#include <stdio.h>
#include <string.h>
int main() {
return 0;
}
Run Code
Output
This is because name is a char array (C-string) and we cannot use the
assignment operator = with it after we have declared the string.
Finally, we printed the data of person1 .
Keyword typedef
We use the typedef keyword to create an alias name for data types. It is
commonly used with structures to simplify the syntax of declaring variables.
For example, let us look at the following code:
struct Distance{
int feet;
float inch;
};
int main() {
struct Distance d1, d2;
}
int main() {
distances d1, d2;
}
Example 2: C typedef
#include <stdio.h>
#include <string.h>
int main() {
Output
Now, we can simply declare a Person variable using the person alias:
Nested Structures
You can create structures within a structure in C programming. For
example,
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integers;
} num1, num2;
Suppose, you want to set imag of num2 variable to 11. Here's how you can do
it:
[Link] = 11;
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integer;
} num1;
int main() {
return 0;
}
Run Code
Output
Imaginary Part: 11
Real Part: 5.25
Integer: 6
Why structs in C?
Suppose you want to store information about a person: his/her name,
citizenship number, and salary. You can create different
variables name , citNo and salary to store this information.
What if you need to store information of more than one person? Now, you
need to create different variables for each information per
person: name1 , citNo1 , salary1 , name2 , citNo2 , salary2 , etc.
A better approach would be to have a collection of all related information
under a single name Person structure and use it for every person.
Structure Example
#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;
#include <stdio.h>
struct address
{
int street;
char *state;
char *city;
char *country;
};
struct stu_data
{
int stu_id;
int stu_age;
char *stu_name;
struct address stu_address;
};
int main(){
struct stu_data student1;
student1.stu_id = 1001;
student1.stu_age = 30;
strcpy(student1.stu_name, "Chaitanya");
student1.stu_address.state = "UP";
student1.stu_address.street = 101;
student1.stu_address.city = "Delhi";
student1.stu_address.country = "India";
printf("Printing student Data: ");
printf("\nStudent id: %d", student1.stu_id);
printf("\nStudent age: %d", student1.stu_age);
printf("\nStudent name: %s", student1.stu_name);
printf("\nStudent street:
%d",student1.stu_address.street);
printf("\nStudent state: %s",
student1.stu_address.state);
printf("\nStudent city: %s", student1.stu_address.city);
printf("\nStudent country: %s",
student1.stu_address.country);
return 0;
}
Array of Structures in C
An array of structures is an array with structure as elements.
For example:
Here, stu[5] is an array of structures. This array has 5 elements and these
elements are structures of the same type “student”. The element s[0] will store
the values such as name, rollNum, address & marks of a student, similarly
element s[1] will store these details for another student and so on.
struct student {
char name[60];
int rollNum;
char address[60];
float marks;
} stu[5];
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
C program to read records of three different students in structure
having member name, roll and marks, and displaying it.
C Source Code:
#include<stdio.h>
/* Declaration of structure */
struct student
{
char name[30];
int roll;
float marks;
};
int main()
{
/* Declaration of array of structure */
struct student s[3];
int i;
for(i=0;i< 3;i++)
{
printf("Enter name, roll and marks of
student:\n");
scanf("%s%d%f",s[i].name, &s[i].roll,
&s[i].marks);
}
printf("Inputted details are:\n");
for(i=0;i< 3;i++)
{
printf("Name: %s\n",s[i].name);
printf("Roll: %d\n", s[i].roll);
printf("Marks: %0.2f\n\n", s[i].marks);
}
return 0;
}
1. Declaring a Structure
The general form of a structure declaration statement is given below:
Once the new structure data type has been defined one or more
variables can be declared to be of that type.
For example the variables b1, b2, b3 can be declared to be of the type
struct book,
struct book
{
char name;
float price;
int pages;
};
as,
struct book
{
char name[10];
float price;
int pages;
};
[Link]
[Link]
Note that before the dot there must always be a structure variable and
after the dot there must always be a structure element.
3. Example
The following example illustrates the use of this data type.
#include<stdio.h>
main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b1, b2, b3 ;
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Developer Insider");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( [Link], "C++ Programming");
strcpy( [Link], "Developer Insider");
strcpy( [Link], "C++ Programming Tutorial");
Book2.book_id = 6495700;
return 0;
}
5. Summary
• A structure is usually used when we wish to store dissimilar
data together.
• Structure elements can be accessed through a structure
variable using a dot (.) operator.
• Structure elements can be accessed through a pointer to a
structure using the arrow (->) operator.
• All elements of one structure variable can be assigned to
another structure variable using the assignment (=) operator.
• It is possible to pass a structure variable to a function either by
value or by address.
• It is possible to create an array of structures
#include <stdio.h>
#include <string.h>
// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};
// declaring union
union union_example
{
int integer;
float decimal;
char name[20];
};
void main()
{
// creating variable for structure
// and initializing values difference
// six
struct struct_example s={18,38,"geeksforgeeks"};
// creating variable for union
// and initializing values
union union_example u={18,38,"geeksforgeeks"};
// difference five
printf("\n Accessing all members at a time:");
[Link] = 183;
[Link] = 90;
strcpy([Link], "geeksforgeeks");
[Link] = 183;
[Link] = 90;
strcpy([Link], "geeksforgeeks");
printf("\nstructure data:");
[Link] = 240;
printf("\ninteger: %d", [Link]);
[Link] = 120;
printf("\ndecimal: %f", [Link]);
[Link] = 120;
printf("\ndecimal: %f", [Link]);
//difference four
printf("\nAltering a member value:\n");
[Link] = 1218;
printf("structure data:\n integer: %d\n "
" decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
[Link] = 1218;
printf("union data:\n integer: %d\n"
" decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
}
Output:
structure data:
integer: 18
decimal: 38.00
name: geeksforgeeks
union data:
integer: 18
decimal: 0.00
name: ?
sizeof structure: 28
sizeof union: 20
union data:
integer: 1801807207
decimal: 277322871721159510000000000.00
name: geeksforgeeks
union data:
integer: 240
decimal: 120.000000
name: C programming
Defining an Enum
enum Season{
Summer,
Spring,
Winter,
Autumn
};
Here, we have defined an enum with name 'season' and 'Summer, Spring,
Winter and Autumn' as its elements.
enum season{
Summer,
Spring,
Winter,
Autumn
};
main()
{
enum season s;
}
So, here 's' is the variable of the enum named season. This variable will
represent a season. We can also declare an enum variable as follows.
enum season{
Summer,
Spring,
Winter,
Autumn
}s;
All the elements of an enum have a value. By default, the value of the first
element is 0, that of the second element is 1 and so on.
#include <stdio.h>
enum season{ Summer, Spring, Winter, Autumn};
int main()
{
enum season s;
s = Spring;
printf("%d\n",s);
return 0;
}
Output
Here, first we defined an enum named 'season' and declared its variable 's' in
the main function as we have seen before. The values of Summer, Spring,
Winter and Autumn are 0, 1, 2 and 3 respectively. So, by writing s = Spring, we
assigned a value '1' to the variable 's' since the value of 'Spring' is 1.
We can also change the default value and assign any value of our choice to an
element of enum. Once we change the default value of any enum element, then
the values of all the elements after it will also be changed accordingly. An
example will make this point clearer.
#include <stdio.h>
enum days{ sun, mon, tue = 5, wed, thurs, fri, sat};
int main()
{
enum days day;
day = thurs;
printf("%d\n",day);
return 0;
}
Output
The default value of 'sun' will be 0, 'mon' will be 1, 'tue' will be 2 and so on. In
the above example, we defined the value of tue as 5. So the values of 'wed',
'thurs', 'fri' and 'sat' will become 6, 7, 8 and 9 respectively. There will be no
effect on the values of sun and mon which will remain 0 and 1 respectively. Thus
the value of thurs i.e. 7 will get printed.
Let's see one more example of enum.
#include <stdio.h>
enum days{ sun, mon, tue, wed, thurs, fri, sat};
int main()
{
enum days day;
day = thurs;
printf("%d\n",day+2);
return 0;
}
Output
In this example, the value of 'thurs' i.e. 4 is assigned to the variable day. Since
we are printing 'day+2' i.e. 6 (=4+2), so the output will be 6.
Overview
In computer programming enumerated data type is used to create the group of constants. This
group of named values can be identified as elements, members, enumerals, or enumerators.
This enumerators are considered very handy for designing a big scale applications.
Scope
• This article starts at very basic level by creating a problem to establish a use case for enum.
• Then it explains the enum and introduces you with different ways to declare and initialize
the enums.
• This article will help you to encounter the possible scenarios and use cases where you can
use the enums in your code.
Introduction
Imagine a scenario where we are designing a text editor and want to have a features
like bold, italic and underline.
Now what are different ways with which you can design and access them in your program?
One way is to use string literals like "BOLD", "ITALIC" or "UNDERLINE", but the problem
arises when you want to use them in a switch/case statements. It becomes complicated.
Another way is to map them with certain numbers like 0, 1 or 2, but having string "BOLD" is
more meaningful in code instead of having any random number 0.
So we want the string literals, but we want them to work as integer constants.
There is one classic way to solve this problem and achieve what we want by using using
macros in C as following.
#define BOLD 0
#define ITALIC 1
#define UNDERLINE 2
What is enum in C?
Enumerator(enum) is one of the special user-defined datatype in C programming language
which is used to create and store the integer constants.
Enum in C langauge is used to write clean, easy to read and easy to maintainable code.
The enum keyword is used to create the enumerated data type in C. Following is an syntax of
enum declaration in C:
enum textEditor {
BOLD,
ITALIC,
UNDERLINE
};
In above code the textEditor is the name for enumerator datatype and BOLD, ITALIC,
UNDERLINE are different enum names separated by a comma.
Declaration 1
enum textEditor {
BOLD,
ITALIC,
UNDERLINE
} feature;
In the above example we declared the variable feature just after the braces.
Declaration 2
enum textEditor {
BOLD,
ITALIC,
UNDERLINE
};
int main() {
enum textEditor feature;
return 0;
}
Here we declared the feature variable of type enum inside the main function.
The first enum name in the following declaration is by default assigned to value 0 if it is not
initialized and next enum names are assigned by increment of 1.
i.e. BOLD, ITALIC & UNDERLINE will have values 0, 1 & 2 respectively.
Code example
#include <stdio.h>
// declaration on enum
enum textEditor {
BOLD,
ITALIC,
UNDERLINE
};
int main() {
// Defining the variable of type enum
enum textEditor feature = BOLD;
printf("Selected feature is %d\n", feature);
feature = ITALIC;
printf("Selected feature is %d\n", feature);
return 0;
}
Output
Selected feature is 0
Selected feature is 1
Initializing the values
We can initialize the values to the enum names and then next enum names follow the same
increment pattern of 1. For eg.
enum textEditor {
BOLD = 5,
ITALIC = 9,
UNDERLINE
};
In above declaration the value of BOLD and ITALIC is 5 and 9 respectively as initialized.
The value of UNDERLINE is 10 because every element in enum takes the next integer value
of its previous if it is not initialized.
Code example
#include <stdio.h>
// declaration on enum
enum textEditor {
BOLD = 5,
ITALIC = 9,
UNDERLINE
};
int main() {
// Initializing enum variable
enum textEditor feature = ITALIC;
printf("Selected feature is %d\n", feature);
feature = UNDERLINE;
printf("Selected feature is %d\n", feature);
return 0;
}
Output
Selected feature is 9
Selected feature is 10
Defining enum variables by their integer equivalent values
We can directly define the enum variables by directly assigning the equivalent integer values
as below code.
Code example
#include <stdio.h>
// declaration on enum
enum textEditor {
BOLD = 5,
ITALIC = 9,
UNDERLINE
};
int main() {
// Initializing enum variable
enum textEditor feature = BOLD;
printf("Selected feature is %d\n", feature);
return 0;
}
output
Selected feature is 5
Selected feature is 5
In above code if we directly initialize the 5 in a feature variable then the same value gets
evaluated. i.e. BOLD.
enum car {
run = 1,
brake = 0,
stop = 0
};
All enum names must be unique
All enum names must be unique in there scope. For eg. enum bike and car should not contain
the same enum name as run.
enum bike {
run,
stop
};
enum car {
run,
brake
};
int main() {
return 0;
}
Code example 4
#include <stdio.h>
// declaration on enum
enum textEditor {
BOLD = 1,
ITALIC = 2,
UNDERLINE = 3
};
int main() {
// Initializing enum variable
enum textEditor feature = ITALIC;
switch (feature) {
case 1:
printf("It is BOLD");
break;
case 2:
printf("It is ITALIC");
break;
case 3:
printf("It is UNDERLINE");
}
return 0;
}
Output
It is ITALIC
Using enums for flags
Let's consider the same example as above where we want to design a text editor but now we
want the freedom to combine 2 or more features together.
This time we will assign the numbers in power of 2 format with the purpose so that we can
combine 2 or more features together usingbit-wise OR operator as follows.
enum textEditor{
BOLD = 1,
ITALIC = 2,
UNDERLINE = 4
};
Above numbers if converted to binary then they will look something like following and after
performing bit-wise OR (|) operation we can use 2 features combined as explained below.
0000 0001 = 1
| 0000 0100 = 4
------------
0000 0101 = 5
By doing bit-wise OR operation we got 5 as a result by which we know that both BOLD and
UNDERLINE features are used.
Enum vs Macros
The key fundamental difference between enum in C and macros in C is that macros can take
any data types even it can take loops, conditionals and function calls with them.
For eg.
#define WIDTH 80
#define LENGTH (WIDTH + 10)
#define multiply(f1, f2) (f1 * f2)
But enum in C can only take the integer constants and they provide the clean way to declare
multiple values in a single scope of braces as we discussed above.
It is a good idea to use enum over macros if we want to use the multiple well-structured
values of type integer.
Conclusion
In this article we learned about what is enum in C language.
1. We use enums in our code to make better group of constants than macros in terms
of readability and functionality.
2. In C language there are different ways provided to declare the enums and use them.
3. We saw different ways to initialize the enums and use them with various examples.
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d
Output
The value of enum week: 10111213101617
The default value of enum day: 0123181112
#include <stdio.h>
int main(){
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
}
return 0;
Output:
#include <stdio.h>
int main(){
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
return 0;
}
Output:
#include<stdio.h>
enum containers{
cont1 = 5,
cont2 = 7,
cont3 = 3,
cont4 = 8
};
int main(){
cur_cont = cont3;
cur_cont = cont1;
printf("Value of hearts is = %d \n", cur_cont);
return 0;
Output:
We have declared an enum named containers with four different containers as the
elements in the above code. We have then given custom values to the elements and
initialized the variable for the enum multiple times to print the relevant output.
We use enums for constants, i.e., when we want a variable to have only a specific set
of values. For instance, for weekdays enum, there can be only seven values as there
are only seven days in a week. However, a variable can store only one value at a
time. We can use enums in C for multiple purposes; some of the uses of enums are:
#include <stdio.h>
int main(){
enum directions d;
d=West;
switch(d){
case North:
break;
case East:
break;
case West:
break;
case South:
break;
return 0;
Output:
We can use enum in C for flags by keeping the values of integral constants a power
of 2. This will allow us to choose and combine two or more flags without overlapping
with the help of the Bitwise OR (|) operator. Let’s consider the example below where
we set three flags: Crop, Rotate, and Save to work with an image.
Example:
#include <stdio.h>
enum designFlags{
CROP = 1,
ROTATE = 2,
SAVE = 4
};
int main() {
printf("%d", myExample);
return 0;
Output:
00000010 (ROTATE = 2)
| 00000100 (SAVE = 4)
___________
00000110 (Output = 6)
As you can see, our calculation and the output given by the program are the same.
This concludes that we can use enum in C for flags. Also, we can add our custom
flags.
Interesting Points About Initialization of Enum in C
There are a few facts about the enum worth noting, such as:
1. Multiple enum names or elements can have the same value. Here’s an example of
two enum elements having a similar value.
Example:
#include <stdio.h>
int main(){
return 0;
Output:
2. If we do not assign custom values to enum elements, the compiler will assign
them default values starting from 0. For instance, the compiler will assign values to
the months in the example below, with January being 0.
Example:
#include <stdio.h>
enum Months{January, February, March, April, May, June, July, August, September,
October, November, December};
int main(){
return 0;
Output:
3. We can provide values to any elements of enum in any order. All the unassigned
elements will get the value as previous + 1. The following program demonstrates the
same.
Example:
#include <stdio.h>
return 0;
Output:
4. All the values assigned to the elements of enum must be an integral constant. For
instance, they should be within the range of minimum and maximum possible
integers.
5. All the enum elements or constants should have a unique scope. It means that an
element cannot be a part of two different enums in the same program as it will fail
during compilation. Here’s an example:
Example:
#include <stdio.h>
return 0;
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
-------------------------------------------------------------------------------------
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
---------------------------------------------------------------------------------------------------------
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
-----------------------------------------------------------------------------------------------
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
----------------------------------------------------------------------------------------------------------
The strrev(string) function returns reverse of the given string. Let's see a simple
example of strrev() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
------------------------------------------------------------------------------------
The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
-------------------------------------------------------------------------------------------
The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
------------------------------------------------------------------------------------------
C Math Functions
There are various methods in math.h header file. The commonly used functions of
math.h header file are given below.
2) floor(number) rounds down the given number. It returns the integer value
which is less than or equal to given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
4.000000
4.000000
3.000000
3.000000
4.000000
2.644.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
574.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
1251
16.000000
27.000000
12
4.0000004.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
Searching technique refers to finding a key element among the list of elements. If the
given element is present in the list, then the searching process is said to be successful. If the
given element is not present in the list, then the searching process is said to be
unsuccessful.
Recall that character strings and string literals are each terminated by NULL
byte. String literal, however, doesn’t have visible NULL terminator. Compiler
provides every string literal a NULL terminator while compiling the program.
But character arrays may or may not contain NUL terminator. Character arrays
which contain terminating NULL byte are strings. For example:
String Declaration
There are two ways to declare strings in C:
1. The following example will create a string as "Scaler" where the last character
must always be a null character. The size mentioned within the brackets is the
maximum number of characters a string could hold, and it is mandatory to give the
size of a string if we are not initializing it at the time of declaration.
2. In this method, we do not need to put the null character at the end of the string
constant. The compiler automatically inserts the null character at the end of the
string.
Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member.
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
Array Advantages:
• In an array, accessing an element is very easy by using the index
number.
• The search process can be applied to an array easily.
• 2D Array is used to represent matrices.
• For any reason a user wishes to store multiple values of similar
type then the Array can be used and utilized efficiently.
Disadvantages:
Array size is fixed: The array is static, which means its size is always fixed.
The memory which is allocated to it cannot be increased or decreased