0% found this document useful (0 votes)
2 views118 pages

Unit-3

The document explains the use of loops in C programming, specifically focusing on while, do-while, and for loops. It provides syntax, examples, and properties of each loop type, along with common pitfalls like infinite loops. Additionally, it includes sample programs for various tasks such as printing numbers, calculating sums, and checking for prime and Armstrong numbers.

Uploaded by

sandhyashankar20
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)
2 views118 pages

Unit-3

The document explains the use of loops in C programming, specifically focusing on while, do-while, and for loops. It provides syntax, examples, and properties of each loop type, along with common pitfalls like infinite loops. Additionally, it includes sample programs for various tasks such as printing numbers, calculating sums, and checking for prime and Armstrong numbers.

Uploaded by

sandhyashankar20
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

Use of 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.

#include <stdio.h>

int main () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}

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

Print table of a number

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

Properties of while loop


o A conditional expression is used to check the condition. The statements defined
inside the while loop will repeatedly execute until the given condition fails.
o In while loop, the condition expression is compulsory.
o Running a while loop without a body is possible.
o We can have more than one conditional expression in while loop.
o If the loop body contains only one statement, then the braces are optional.

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

Q)WAP to print the sum of all numbers up to a given number using


while loop.

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

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


return 0;
}

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.

Let's see a few examples of infinite loops in C:

#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.

WAP to check whether the entered number is prime or not.

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

Sum of digits of a number

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.

Let's try to understand why 153 is an Armstrong number.


1. 153 = (1*1*1)+(5*5*5)+(3*3*3)
2. where:
3. (1*1*1)=1
4. (5*5*5)=125
5. (3*3*3)=27
6. So:
7. 1+125+27=153

Let's try to understand why 371 is an Armstrong number.

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

Let's see the c program to check Armstrong Number in C.


#include<stdio.h>
int main()
{
int n,r,sum=0,temp,d=0;
printf("enter the number=");
scanf("%d",&num);
n=num;
while(n!=0)
{
n=n/10;
++d;
}
n=num;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(num==sum)
printf("armstrong number ");
else
printf("not armstrong number");
return 0;
}

Output:

enter the number=153


armstrong number

enter the number=5


not armstrong number

4. do while loop in C

In some situations it is necessary to execute body of the loop once


before testing the condition. Such situations can be handled with
the help of do-while loop. The do statement evaluates the body of
the loop first and at the end, the condition is checked
using while statement. It means that the body of the loop will be
executed at least once, even though the starting condition
inside while is initialized to be false. General syntax is,

do

.....

.....

while(condition);

Copy
Remember that the semicolon at the end of do-while loop is mandatory. It denotes end of the loop.

Following is the flowchart for do-while loop:


We initialize our iterator. Then we enter body of the do-while loop.
We execute the statement and then reach the end. At the end, we
check the condition of the loop. If it is false, we exit the loop and if
it is true, we enter the loop. We keep repeating the same thing
unless the condition turns false.

Program to print your name N times using do-while loop

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

printf("\nEnter your name:");

scanf("%s", name);

do{

printf("%s\n", name);

n--;

}while(n > 0);

return 0;

Program to print first 10 multiples of 5 using do-while loop

#include<stdio.h>

void main()

int a, i;

a = 5;

i = 1;

do

{
printf("%d\t", a*i);

i++;

while(i <= 10);

Copy

5 10 15 20 25 30 35 40 45 50

// Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
double number, sum = 0;

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
Infinite loop

#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

The for loop in C is used to execute a set of statements repeatedly


until a particular condition is satisfied. We can say it is an open
ended loop. General format is,
for(initialization; condition;
increment/decrement)

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.

The for loop is executed as follows:

1. It first evaluates the initialization code.

2. Then it checks the condition expression.

3. If it is true, it executes the for-loop body.

4. Then it evaluate the increment/decrement condition and again


follows from step 2.

5. When the condition expression becomes false, it exits the


loop.

Following is a flowchart explaining how the for loop executes.


We first initialize our iterator. Then we check the condition of the
loop. If it is false, we exit the loop and if it is true, we enter the
loop. After entering the loop, we execute the statements inside
the for loop, update the iterator and then again check the condition.
We do the same thing unless the test condition returns false.

Program to print your name n times using for loop

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

printf("Enter your name:");

scanf("%s", name);

for(int i = 1; i <= n; i++) { //here we are


checking if n is non-zero

printf("%s\n", name);

return 0;

Copy

Enter the number of times you want to print your name:3

Enter your name:studytonight

studytonight

studytonight

Run Code →

Let's dry run of the above code:

Firstly, we input n = 3, then name = studytonight.

Now, we reach the for loop so we initialize i with 1. We check the


condition; 1 <= 3, so we enter the loop. We execute
the printf() statement and print name on the console. We again
reach the for loop. We increment i by 1; so now i = 2. We again
check the condition; 2 <= 3, so we enter the loop and print name.
Now i is incremented again to 3. We check the condition again; 3
<= 3, so we enter the loop and execute the statements. Now we
have i = 4. We check the condition; 4 > 3, so we don't enter the
loop. We exit the loop and start executing the statements after it.

Program to print first 10 natural numbers using for loop

#include<stdio.h>

void main( )

int x;

for(x = 1; x <= 10; 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

Here, 5! is pronounced as "5 factorial"

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

// shows error if the user enters a negative integer


if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}

return 0;
}

WAP to print sum of even and odd numbers from 1 to


N numbers.
1. #include <stdio.h>
2.
3. void main()
4. {
5. int i, num, odd_sum = 0, even_sum = 0;
6.
7. printf("Enter the value of num\n");
8. scanf("%d", &num);
9. for (i = 1; i <= num; i++)
10. {
11. if (i % 2 == 0)
12. even_sum = even_sum + i;
13. else
14. odd_sum = odd_sum + i;
15. }
16. printf("Sum of all odd numbers = %d\n",
odd_sum);
17. printf("Sum of all even numbers = %d\n",
even_sum);
18. }

WAP to print the Fibonacci series.


#include <stdio.h>
int main() {

int i, n;

// initialize first and second terms


int t1 = 0, t2 = 1;

// initialize the next term (3rd term)


int nextTerm = t1 + t2;

// get no. of terms from user


printf("Enter the number of terms: ");
scanf("%d", &n);

// print the first two terms t1 and t2


printf("Fibonacci Series: %d, %d, ", t1, t2);

// print 3rd to nth terms


for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}

Print Armstrong number from 1 to 500

#include<stdio.h>

#include<math.h>

int main()

int sum,i,t,r;

for(i = 1; i <= 500; i++)

t = i; // as we need to retain the


original number

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;

Jumping Out of Loops in C

Sometimes, while executing a loop, it becomes necessary to skip a


part of the loop or to leave the loop as soon as certain condition
becomes true. This is known as jumping out of loop.

1. break statement in C

When break statement is encountered inside a loop, the loop


is immediately exited and the program continues to execute with
the statements after the loop.
The break statement can also be used to jump out of a loop.

This example jumps out of the for loop when i is equal to 4:

int i;

for (i = 0; i < 10; i++) {


if (i == 4) {
break;
}
printf("%d\n", i);
}

Let's see a code example,

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

printf("\nEnter your name:");

scanf("%s", name);

for(int i = 1; i <= n; i++) {

if(i % 5 == 0)

break;

printf("%s\n", name);

return 0;

Copy

Enter the number of times you want to print your name:7

Enter your name:study

study

study

study

study

In the above code, as soon as we find an index which is divisible


by 5, the loop breaks and control is shifted out of the loop.
2. continue statement in C

It causes the control to go directly to the test-condition and then


continue the loop execution. On encountering continue, the
execution leaves the current cycle of loop, and starts with the next
cycle.
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

int i;

for (i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
printf("%d\n", i);
}

Let's see a code example,


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

printf("\nEnter your name:");

scanf("%s", name);

for(int i = 1; i <= n; i++) {

if(i % 2 == 0)

continue;

printf("%d : %s\n",i,name);

return 0;

Copy

Enter the number of times you want to print your name:5

Enter your name:study


1 : study

3 : study

5 : study

In the above example, whenever we come across an even index, we


move on to the next index because of the continue statement.

[Link]. Loop Type & Description

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.

Loop Control Statements


Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
C supports the following control statements.

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the
'for' loop are required, you can make an endless loop by leaving the conditional
expression empty.

#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 .

Syntax of goto Statement

goto label;
... .. ...
... .. ...
label:
statement;

The label is an identifier. When the goto statement is encountered, the


control of the program jumps to label: and starts executing the code.
Example: goto Statement
// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.

#include <stdio.h>

int main() {

const int maxInput = 100;


int i;
double number, average, sum = 0.0;

for (i = 1; i <= maxInput; ++i) {


printf("%d. Enter a number: ", i);
scanf("%lf", &number);

// go to jump if the user enters a negative number


if (number < 0.0) {
goto jump;
}
sum += number;
}

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.

Should you use goto?

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."

multiple loop variables in C Language


C programming allows to use one loop inside another loop. The following section
shows a few examples to illustrate the concept.

Syntax
The syntax for a nested for loop statement in C is as follows −

for ( init; condition; increment ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language 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;
}

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

----------------------------
*
* *
* * *
* * * *
* * * * *

Program to print half Pyramid of numbers using Nested loops

#include<stdio.h>

void main( )

int i, j;

/* first for loop */

for(i = 1; i <= 5; i++)

printf("\n");

/* second for loop inside the first */

for(j = i; j > 0; j--)

printf("%d", j);

}
}

Copy

21

321

4321

54321

Example 1: Half Pyramid of * using N number of rows

*
* *
* * *
* * * *
* * * * *

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

Example 3: Half Pyramid of Alphabets

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

Example 4: Inverted half pyramid of *

* * * * *
* * * *
* * *
* *
*

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

Example 5: Inverted half pyramid of numbers

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

Example 10: Floyd's Triangle.

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

Program to print the full Pyramid of Star


Let's consider an example to print the full Pyramid of Star using for loop.

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

for ( i =1; i <= rows; i++)


{
for ( j = 1; j <= rows-i ; j++)
{
printf (" ");
}
// use for loop where k is less than equal to (2 * i -1)
for ( k = 1; k <= ( 2 * i - 1); k++)
{
printf ("* "); // print the Star
}
printf ("\n");
}
getch();
}

Output

i->1 to n
j->1 to n-i

k-> 1 to 2*i-1

Program to print the inverted full Pyramid of Star


Let's consider an example to print the full Pyramid of Star using for loop.

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

j->1 to m print space m=1

k-> 1 to 2*i-1 {print star} m++;

20. WAP to convert binary number into decimal number and vice versa.

// convert binary to decimal

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

// convert decimal to binary

#include <stdio.h>
#include <math.h>

long long convert(int);

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

long long convert(int n) {


long long bin = 0;
int rem, i = 1;

while (n!=0) {
rem = n % 2;
n /= 2;
bin += rem * i;
i *= 10;
}

return bin;
}

Q)WAP to print square root of a quadratic equation.

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

// condition for real and different roots


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}

// condition for real and equal roots


else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}

// if roots are not real


else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart,
realPart, imagPart);
}

return 0;
}

Array Notation and Representation


Manipulating Array Elements
Using Multi Dimensional Arrays
Character Arrays and Strings

Array notation and representation in C


Language
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, …, and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and …, numbers[99] to represent individual variables. A specific element
in an array is accessed by an index.

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 −

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant


greater than zero and type can be any valid C data type. For example, to declare a
10-element array called balance of type double, use this statement −

double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays
You can initialize an array in C either one by one or using a single statement as
follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};


The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

You will create exactly the same array as you did in the previous example.

Following is an example to assign a single element of the array −

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 −

double salary = balance[9];

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

int n[ 10 ]; /* n is an array of 10 integers */


int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}

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

Multi dimensional arrays in C Language


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

In C programming, you can create an array of arrays. These arrays are


known as multidimensional arrays. For example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements.


You can think the array as a table with 3 rows and each row has 4
columns.

Accessing Two-Dimensional Array Elements


An element in a two-dimensional array is accessed by using the subscripts, i.e., row
index and column index of the array. For example −

int val = a[2][3];


The above statement will take the 4th element from the 3rd row of the array. You can
verify it in the above figure. Let us check the following program where we have used
a nested loop to handle a two-dimensional array −

Live Demo
#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

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

// C program to store temperature of two cities of a week and display it.


#include <stdio.h>
const int m = 2;
const int n = 7;
int main()
{
int p[m][n];

// Using nested loop to store values in a 2d array


for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &p[i][j]);
}
}
printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array


for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, p[i][j]);
}
}
return 0;
}

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

}
Printf(“\n”);
}
return 0;
}

Character arrays in C Language


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.”

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as
follows −

char greeting[] = "Hello";


Following is the memory presentation of the above defined string in C/C++ −

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

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello

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.”

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


If you follow the rule of array initialization then you can write the above statement as
follows −

char greeting[] = "Hello";


Following is the memory presentation of the above defined string in C/C++ −

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

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}

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;

printf("Enter size of the array : ");


scanf("%d",&n);

printf("Enter elements in array : ");


for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}

for(i=0; i<n; i++)


{

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

Matrix Row sum and column sum

#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");
}

//calculating row sum

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

//calculating column sum


sum=0;
for(i=0;i<3;i++)
{

for(j=0;j<3;j++)
{
sum=sum+a[j][i];
}
printf("sum of column %d is
%d\n",j,sum);
sum=0;
}

//sum of diagonal elements


sum=0;
for(i=0;i<3;i++)
{
sum=sum+a[i][i];
}
printf("sum of main diagonal is
%d\n",sum);

//sum of off-diagonal elements


Sum=0;
for(i=0;i<3;i++)
{
sum=sum+a[i][3-i-1];
}
printf("sum of main diagonal is
%d\n",sum);

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

//finding transpose of matrix


for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
printf("Transpose of the matrix:
");
for (i = 0; i< n; i++) {
for (j = 0; j < m; j++)
printf("%d\t", transpose[i][j]);
printf("
");
}
return 0;
}

Symmetric or not
#include<stdio.h>
#include<stdlib.h>

int main()
{
int m, n, i, j, count = 0;

printf("Please Enter Number of


rows and columns: ");
scanf("%d %d", &m, &n);

if(m!=n)
{
printf("Rows not equal to
columns. Therefore Non-Symmetric
Matrix.");
exit(0);
}

//Initialize 2d-array of size


m,n.
int a[m][n], b[m][n];

printf("\nEnter the Matrix


Elements \n");
for(i = 0; i < m; i++)
{
for(j = 0;j < n;j++)
{
scanf("%d", &a[i][j]);
}
}
//Transpose of matrix
for(i = 0; i < m; i++)
{
for(j = 0;j < n; j++)
{
b[j][i] = a[i][j];
}
}

//Check if matrix a equals to


matrix b or not.
for(i = 0; i <m ; i++)
{
for(j = 0; j < n; j++)
{
if(a[i][j] != b[i][j])
{
count++;
break;
}
}
}
if(count == 0)
{
printf("\nThe given Matrix is
a Symmetric Matrix ");
}
else
{
printf("\nThe given Matrix is
Not a Symmetric Matrix ");
}

return 0;
}

In C programming, a struct (or structure) is a collection of variables (can be


of different types) under a single name.

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.

Create struct Variables


When a struct type is declared, no storage or memory is allocated. To
allocate memory of a given structure type and work with it, we need to
create variables.
Here's how we create structure variables:

struct Person {
// code
};

int main() {
struct Person person1, person2, p[20];
return 0;
}

Another way of creating a struct variable is:

struct Person {
// code
} person1, person2, p[20];

In both cases,

• person1 and person2 are struct Person variables


• p[] is a struct Person array of size 20.

Access Members of a Structure


There are two types of operators used for accessing members of a
structure.

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>

// create struct with person1 variable


struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {

// assign value to name of person1


strcpy([Link], "George Orwell");

// assign values to other person1 variables


[Link] = 1984;
person1. salary = 2500;

// print struct variables


printf("Name: %s\n", [Link]);
printf("Citizenship No.: %d\n", [Link]);
printf("Salary: %.2f", [Link]);

return 0;
}
Run Code
Output

Name: George Orwell


Citizenship No.: 1984
Salary: 2500.00

In this program, we have created a struct named Person . We have also


created a variable of Person named person1 .

In main() , we have assigned values to the variables defined in Person for


the person1 object.

strcpy([Link], "George Orwell");


[Link] = 1984;
person1. salary = 2500;

Notice that we have used strcpy() function to assign the value


to [Link] .

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

We can use typedef to write an equivalent code with a simplified syntax:

typedef struct Distance {


int feet;
float inch;
} distances;

int main() {
distances d1, d2;
}

Example 2: C typedef
#include <stdio.h>
#include <string.h>

// struct with typedef person


typedef struct Person {
char name[50];
int citNo;
float salary;
} person;

int main() {

// create Person variable


person p1;

// assign value to name of p1


strcpy([Link], "George Orwell");

// assign values to other p1 variables


[Link] = 1984;
p1. salary = 2500;

// print struct variables


printf("Name: %s\n", [Link]);
printf("Citizenship No.: %d\n", [Link]);
printf("Salary: %.2f", [Link]);
return 0;
}
Run Code

Output

Name: George Orwell


Citizenship No.: 1984
Salary: 2500.00

Here, we have used typedef with the Person structure to create an


alias person .

// struct with typedef person


typedef struct Person {
// code
} person;

Now, we can simply declare a Person variable using the person alias:

// equivalent to struct Person p1


person p1;

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;

Example 3: C Nested Structures


#include <stdio.h>

struct complex {
int imag;
float real;
};

struct number {
struct complex comp;
int integer;
} num1;

int main() {

// initialize complex variables


[Link] = 11;
[Link] = 5.25;

// initialize number variable


[Link] = 6;

// print struct variables


printf("Imaginary Part: %d\n", [Link]);
printf("Real Part: %.2f\n", [Link]);
printf("Integer: %d", [Link]);

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;

/*Assigning the values of each struct member here*/


student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;

/* Displaying the values of struct members */


printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}

Nested structure example

#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:

struct <structure name>


{
structure element 1;
structure element 2;
structure element 3;
......
......
structure element n;
};

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 b1, b2, b3;

This statement sets aside space in memory. It makes available space to


hold all the elements in the structure—in this case, 7 bytes — one for
name, four for price and two for pages. These bytes are always in
adjacent memory locations.

Like primary variables and arrays, structure variables can also be


initialized where they are declared. The format used is quite similar to
that used to initiate arrays.

struct book
{
char name[10];
float price;
int pages;
};

struct book b1 = { "Basic", 130.00, 550 } ;


struct book b2 = { "Physics", 150.80, 800 } ;

2. Accessing Structure Elements


In arrays we can access individual elements of an array using a
subscript. Structures use a different scheme. They use a dot (.)
operator. So to refer to pages of the structure defined in book structure
we have to use,

[Link]

Similarly, to refer to price we would use,

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

printf("\nEnter names, prices & no. of pages of 3 books\n");


scanf("%c %f %d", &[Link], &[Link], &[Link]);
scanf("%c %f %d", &[Link], &[Link], &[Link]);
scanf("%c %f %d", &[Link], &[Link], &[Link]);

printf("\n\nAnd this is what you entered");


printf("\n%c %f %d", [Link], [Link], [Link]);
printf("\n%c %f %d", [Link], [Link], [Link]);
printf("\n%c %f %d", [Link], [Link], [Link]);
}

And here is the output...

Enter names, prices and no. of pages of 3 books


A 100.00 354
C 256.50 682
F 233.70 512

And this is what you entered


A 100.000000 354
C 256.500000 682
F 233.700000 512

4. Structures as Function Arguments


You can pass a structure as a function argument in the same way as you
pass any other variable.

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

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* 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;

/* print Book1 info */


printBook( Book1 );

/* Print Book2 info */


printBook( Book2 );

return 0;
}

void printBook( struct Books book ) {

printf( "Book title : %s\n", [Link]);


printf( "Book author : %s\n", [Link]);
printf( "Book subject : %s\n", [Link]);
printf( "Book book_id : %d\n", book.book_id);
}

When the above code is compiled and executed, it produces the


following result −

Book title : C Programming


Book author : Developer Insider
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : C++ Programming
Book author : Developer Insider
Book subject : C++ Programming Tutorial
Book book_id : 6495700

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

Union in C is a special data type available in C that allows storing 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 purposes.
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:

Similarities between Structure and Union


1. Both are user-defined data types used to store data of different
types as a single unit.
2. Their members can be objects of any type, including other
structures and unions or arrays. A member can also consist of a bit
field.
3. Both structures and unions support only assignment =
and sizeof operators. The two structures or unions in the
assignment must have the same members and member types.
4. A structure or a union can be passed by value to functions and
returned by value by functions. The argument must have the same
type as the function parameter. A structure or union is passed by
value just like a scalar variable as a corresponding parameter.
5. ‘.’ operator or selection operator, which has one of the highest
precedences, is used for accessing member variables inside both
the user-defined datatypes.
Differences between Structure and Union are as shown below in tabular
format as shown below as follows:
// C program to illustrate differences
// between structure and Union

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

printf("structure data:\n integer: %d\n"


"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);
printf("\nunion data:\n integer: %d\n"
"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);

// difference two and three


printf("\nsizeof structure : %d\n", sizeof(s));
printf("sizeof union : %d\n", sizeof(u));

// difference five
printf("\n Accessing all members at a time:");
[Link] = 183;
[Link] = 90;
strcpy([Link], "geeksforgeeks");

printf("structure data:\n integer: %d\n "


"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);

[Link] = 183;
[Link] = 90;
strcpy([Link], "geeksforgeeks");

printf("\nunion data:\n integer: %d\n "


"decimal: %.2f\n name: %s\n",
[Link], [Link], [Link]);

printf("\n Accessing one member at time:");

printf("\nstructure data:");
[Link] = 240;
printf("\ninteger: %d", [Link]);

[Link] = 120;
printf("\ndecimal: %f", [Link]);

strcpy([Link], "C programming");


printf("\nname: %s\n", [Link]);

printf("\n union data:");


[Link] = 240;
printf("\ninteger: %d", [Link]);

[Link] = 120;
printf("\ndecimal: %f", [Link]);

strcpy([Link], "C programming");


printf("\nname: %s\n", [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

Accessing all members at a time: structure data:


integer: 183
decimal: 90.00
name: geeksforgeeks

union data:
integer: 1801807207
decimal: 277322871721159510000000000.00
name: geeksforgeeks

Accessing one member at a time:


structure data:
integer: 240
decimal: 120.000000
name: C programming

union data:
integer: 240
decimal: 120.000000
name: C programming

Altering a member value:


structure data:
integer: 1218
decimal: 120.00
name: C programming
union data:
integer: 1218
decimal: 0.00
name: ?
Note: structures are better than unions since memory is shared in a union
which results in a bit of ambiguity. But technically speaking, unions are better
in that they help save a lot of memory, resulting in the overall advantage over
structures in the long run.
Enumeration (enum) is a user-defined datatype (same as structure). It consists
of various elements of that type. There is no such specific use of enum, we use
it just to make our codes neat and more readable. We can write C programs
without using enumerations also.
For example, Summer, Spring, Winter and Autumn are the names of four
seasons. Thus, we can say that these are of types season. Therefore, this
becomes an enumeration with name season and Summer, Spring, Winter and
Autumn as its elements.
So, you are clear with the basic idea of enum. Now let's see how to define it.

Defining an Enum

An enum is defined in the same way as structure with the


keyword struct replaced by the keyword enum and the elements separated by
'comma' as follows.
enum enum_name
{
element1,
element2,
element3,
element4,
};
Now let's define an enum of the above example of seasons.

enum Season{
Summer,
Spring,
Winter,
Autumn
};

Here, we have defined an enum with name 'season' and 'Summer, Spring,
Winter and Autumn' as its elements.

Declaration of Enum Variable


We also declare an enum variable in the same way as that of structures. We
create an enum variable as follows.

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;

Values of the Members of Enum

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.

Let's see an example.

#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

So whenever we use BOLD it represents integer constant 0 in our code and


similarly ITALIC represents 1 and UNDERLINE represents 2.
But there in one more cleaner approach to achieve this same result is by using the enum in
C.

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.

Examples of enum declaration


We can declare the variable of enumerator type in 2 different ways as follows:

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.

Initialization of Enum values


First value is by default 0

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

// Initializing enum with integer equivalent


feature = 5;
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.

Initializing the same values

We can initialize the same values to multiple enum names.


For eg. in following declaration enum names brake and stop will have the same value 0.

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

The Output of above code will generate the error as follows:

error: redeclaration of enumerator 'run'

Utilizing switch/case statements with enum


Enum in C programming can be great utilized with switch case statements. Enum provides a
great way to define the cases so that it becomes easy to modify the code later.
See following code example for implementation.

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.

BOLD = 0000 0001


ITALIC = 0000 0010
UNDERLINE = 0000 0100

// Suppose we want to combine BOLD and UNDERLINE together then:

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

",Mon , Tue, Wed, Thur, Fri, Sat, Sun);


printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues,
Wedn, Thurs, Frid, Satu, Sund);
return 0;
}

Output
The value of enum week: 10111213101617
The default value of enum day: 0123181112

Example 1: Printing the Values of Weekdays

#include <stdio.h>

enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main(){

// printing the values of weekdays

for(int i=Sunday;i<=Saturday;i++){

printf("%d, ",i);
}

return 0;

Output:

Example 1: Printing the Values of Weekdays

#include <stdio.h>

enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main(){

// printing the values of weekdays

for(int i=Sunday;i<=Saturday;i++){

printf("%d, ",i);

return 0;

}
Output:

Example 2: Assigning and Fetching Custom Values of Enum Elements

#include<stdio.h>

enum containers{

cont1 = 5,

cont2 = 7,

cont3 = 3,

cont4 = 8

};

int main(){

// Initializing a variable to hold enums

enum containers cur_cont = cont2;

printf("Value of cont2 is = %d \n", cur_cont);

cur_cont = cont3;

printf("Value of cont3 is = %d \n", cur_cont);

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.

How To Use enum in C?

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:

• To store constant values (e.g., weekdays, months, directions, colors in a rainbow)

• For using flags in C

• While using switch-case statements in C

Example of Using Enum in Switch Case Statement


In this example, we will create an enum with all the 4 directions, North, East, West,
and South as the constants. We will then use the switch case statements to switch
between the direction elements and print the output based on the value of the
variable for the enum directions.

#include <stdio.h>

enum directions{North=1, East, West, South};

int main(){

enum directions d;

d=West;

switch(d){

case North:

printf("We are headed towards North.");

break;

case East:

printf("We are headed towards East.");

break;

case West:

printf("We are headed towards West.");

break;
case South:

printf("We are headed towards South");

break;

return 0;

Output:

Example of Using Enum in C for Flags

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

int myExample = ROTATE | SAVE;

printf("%d", myExample);

return 0;

Output:

If we do the calculations for the above code, it is:

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>

enum Cars{Jeep = 1, BMW = 0, Mercedes_Benz = 0};

int main(){

printf("%d, %d, %d", Jeep, BMW, Mercedes_Benz);

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

enum Months m = May;

printf("The Value of May in Months is %d", m);

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>

enum weekdays {Sunday, Monday = 2, Tuesday, Wednesday = 6, Thursday, Friday =


9, Saturday = 12};
int main()

printf("%d %d %d %d %d %d %d", Sunday, Monday, Tuesday,

Wednesday, Thursday, Friday, Saturday);

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>

enum Cars{Mahindra, Jeep, BMW};

enum Luxury_Cars{BMW, Ferrari, Mercedes_Benz};


int main(){

return 0;

Output:

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination


string.

3) strcat(first_string, concats or joins first string with second string. The


second_string) result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both


second_string) strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

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

The strcpy(destination, source) function copies the source string in destination.

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

The strcat(first_string, second_string) function concatenates two strings and result is


returned to first_string.

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

The strcmp(first_string, second_string) function compares two string and returns 0 if


both strings are equal.

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.

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer value


which is greater than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer value
which is less than or equal to given number.

3) sqrt(number) returns the square root of given number.


4) pow(base, returns the power of given number.
exponent)

5) abs(number) returns the absolute value of 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.

Sorting is the process of arranging elements either in ascending (or) descending


order.

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:

char season[] = {'a','u','t','u','m'}; /* character array */


char country[] = {'I','n','d','i','a','\0'}; /* character string */
char *str = "Hello, how are you?";
/* string literal: No visible NULL terminator */

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.

char company[7] = {'S', 'C', 'A', 'L', 'E', 'R' , '\0'};

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.

char company[] = "SCALER";

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

Array is homogeneous:The array is homogeneous, i.e., only one type of


value can be store in the array. For example, if an array type “int“, can only
store integer elements and cannot allow the elements of other types such as
double, float, char so on.
Array is Contiguous blocks of memory: The array stores data in
contiguous(one by one) memory location.
Insertion and deletion are not easy in Array: The operation insertion and
deletion over an array are problematic as to insert or delete anywhere in the
array, it is necessary to traverse the array and then shift the remaining
elements as per the operation. This operation cost is more.

You might also like