programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 95

C Program to Display Factors of a

Number
Example to find all factors of an integer (entered by the user) using for loop
and if statement.

To understand this example, you should have the knowledge of following C


programmingtopics:

 C Programming Operators
 C if, if...else and Nested if...else Statement
 C Programming for Loop

This program takes a positive integer from the user and displays all the positive
factors of that number.

Example: Factors of a Positive Integer


#include <stdio.h>
int main()
{
int number, i;

printf("Enter a positive integer: ");


scanf("%d",&number);

printf("Factors of %d are: ", number);


for(i=1; i <= number; ++i)
{
if (number%i == 0)
{
printf("%d ",i);
}
}

return 0;
}
Output

Enter a positive integer: 60

Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

In the program, a positive integer entered by the user is stored in variable number.

The for loop is iterated until i <= number is false. In each iteration,
whether number is exactly divisible by i is checked (condition for i to be the factor
of number) and the value of i is incremented by 1.

C Program to Find Factorial of a


Number
The factorial of a positive integer n is equal to 1*2*3*...n. You will learn to
calculate the factorial of a number using for loop in this example.

To understand this example, you should have the knowledge of following C


programming topics:

The factorial of a positive number n is given by:

factorial of n (n!) = 1*2*3*4....n

The factorial of a negative number doesn't exist. And, the factorial of 0 is 1, 0! = 1

Example: Factorial of a Number

Output

Enter an integer: 10

Factorial of 10 = 3628800

This program takes a positive integer from the user and computes factorial using for
loop.
Since the factorial of a number may be very large, the type of factorial variable is
declared as unsigned long long.

If the user enters negative number, the program displays error message.

C program to print
multiplication table of a given
number
Write a C program to enter any number from user and print multiplication table of the
given number using for loop. How to print multiplication table of a given number in C
programming. Logic to print multiplication table of any given number in C program.

Example

Input

Input num: 5

Required knowledge

Basic C programming, For loop

Logic to print multiplication table

Generating multiplication table isn't complex. What will take your mind is printing in the
given format. Hence, not wasting time let us get on to the logic of this program.

1. Input a number from user whose multiplication table is to be generated. Store it in


some variable say num.
2. Run a loop from 1 to 10, incrementing 1 on each repetition. The loop structure should
look like for(i=1; i<=10; i++).
3. Inside the loop generate multiplication table using num * i and print in given format.
The sequence of printing multiplication table is num * i = (num * i)

Program to print multiplication table


/**
* C program to print multiplication table of any number
*/

#include <stdio.h>
int main()
{
int i, num;

/* Input number to print table */


printf("Enter number to print table: ");
scanf("%d", &num);

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


{
printf("%d * %d = %d\n", num, i, (num*i));
}

return 0;
}

C program to find sum of


natural numbers from 1 to n
Write a C program to find the sum of all natural numbers between 1 to n using for loop.
How to find sum of natural numbers in a given range in C programming. C program to
find sum of natural numbers in given range. Logic to find sum of all natural numbers
in a given range in C program.

Example

Input

Input upper limit: 10

Output

Sum of natural numbers 1-10: 55

Required knowledge

Logic to find sum of natural numbers

Below is the step by step descriptive logic to find sum of n natural numbers.

1. Input upper limit to find sum of natural numbers. Store it in some variable say N.
2. Initialize another variable, that will hold sum of numbers say sum = 0.
3. Initialize a loop from 1 to N, incrementing 1 on each iteration. The loop structure should
be for(i=1; i<=N; i++).
4. Inside the loop add previous sum with the current number i. Which is sum = sum + i.
5. Finally after loop print the value of sum.

Program to find sum of natural numbers


/**
* C program to find sum of natural numbers between 1 to n
*/

#include <stdio.h>

int main()
{
int i, n, sum=0;

/* Input upper limit from user */


printf("Enter upper limit: ");
scanf("%d", &n);

/*
* Find summation of all numbers
*/
for(i=1; i<=n; i++)
{
sum += i;
}

printf("Sum of first %d natural numbers = %d", n, sum);

return 0;
}

Note: sum += i is equivalent to sum = sum + i. You can use any of them depending
on your comfort.

Enter upper limit: 10


Sum of first 10 natural numbers = 55

Program to find sum of natural numbers in given range


/**
* C program to find sum of natural numbers in given range
*/

#include <stdio.h>
int main()
{
int i, start, end, sum=0;

/* Input lower and upper limit from user */


printf("Enter lower limit: ");
scanf("%d", &start);
printf("Enter upper limit: ");
scanf("%d", &end);

/*
* Find summation of all numbers
*/
for(i=start; i<=end; i++)
{
sum += i;
}

printf("Sum of natural numbers between %d-%d = %d", start, end,


sum);

return 0;
}

C program to print Equilateral


triangle (Pyramid) star pattern
Write a C program to print the equilateral triangle or Pyramid star(*) pattern series of
n rows using for loop. How to print Pyramid star pattern series using for loop in C
programming. Logic to print pyramid star pattern series in C program.

Example

Input

Input rows: 5

Output

*
***
*****
*******
*********
Required knowledge

Basic C programming, For loop

Logic to print pyramid star pattern

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

There can be many ways of thinking of the problem here I am discussing the easiest
one. We need to print two things one is the trialing spaces and other is the equilateral
triangle. As like other star pattern problems here also spaces are arranged in a special
way i.e. each row contains n - row_number spaces (where n is the total number of
rows).

When you look to the total number of stars(*) in the equilateral triangle pattern you will
notice that each row contains 2*rownumber - 1 stars.

Program to print pyramid star pattern series


/**
* C program to print equilateral triangle or pyramid star pattern
*/

#include <stdio.h>

int main()
{
int i, j, n;

// Input number of rows to print


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

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


{
// Print trailing spaces
for(j=i; j<n; j++)
{
printf(" ");
}

// Print the pyramid pattern


for(j=1; j<=(2*i-1); j++)
{
printf("*");
}

printf("\n");
}

return 0;
}

C program to print right arrow


star pattern
Write a C program to print right arrow star (*) pattern series using for loop. How to print
right arrow star pattern structure using for loop in C programming. Logic to print right
arrow star pattern in C program.

Example

Input

Input N: 5

Output

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

Required knowledge

Basic C programming, For loop


Read more - Program to print left arrow star pattern

Logic to print right arrow star pattern

This pattern is a combination of two patterns hence, let's first divide it into two parts.

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

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

If you have noticed total number of spaces in upper part is 2*rownumber - 2 per row
and bottom part contains total 2*n - 2*rownumber spaces per row (where n is the
total number of rows). If you ignore the trailing spaces, then the upper part star pattern
is similar to inverted right triangle star pattern and bottom part to simple right triangle
star pattern which I already explained how to print.

Program to print right arrow star pattern


/**
* C program to print right arrow star pattern
*/

#include <stdio.h>

int main()
{
int i, j, n;

// Input number of rows from user


printf("Enter value of n : ");
scanf("%d", &n);

// Print the upper part of the arrow


for(i=1; i<n; i++)
{
// Print trailing (2*rownumber-2) spaces
for(j=1; j<=(2*i-2); j++)
{
printf(" ");
}

// Print inverted right triangle star pattern


for(j=i; j<=n; j++)
{
printf("*");
}

printf("\n");
}

// Print lower part of the arrow


for(i=1; i<=n; i++)
{
// Print trailing (2*n - 2*rownumber) spaces
for(j=1; j<=(2*n - 2*i); j++)
{
printf(" ");
}

// Print simple right triangle star pattern


for(j=1; j<=i; j++)
{
printf("*");
}

printf("\n");
}

return 0;
}

C program to print 0 or 1
square number pattern
Write a C program to print the given 0, 1 square number pattern using loop. C program
to print binary number pattern of n rows and m columns using loop. How to print the
square number patterns using for loop in C programming. Logic to print the square
filled with 1 using for loop in C program.

Example
Input

Input rows: 5
Input columns: 5

Output

11111
11111
11111
11111
11111

Required knowledge
Basic C programming, Loop

Logic to print square number pattern


Logic to print this square number pattern of 1 is simple and similar to square start
pattern.

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

We only need to replace the stars(*) with 1 or 0 whatever you want to print. Basic logic
to print square number pattern of n rows and m columns.
Below is the step by step descriptive logic to print square number pattern.

1. Input number of rows and columns to print from user. Store it in some variable
say rows and cols.
2. To print square number pattern, we need two loops. An outer loop to iterate through rows and
second an inner loop to iterate through columns.
3. Run an outer loop from 1 to total rows. The loop structure should look like for(i=1; i<=rows;
i++).
4. Inside the outer loop run an inner loop from 1 to total columns. The loop structure should look
like for(j=1; j<=cols; j++).
5. Inside the inner loop, print whatever you want to get printed as output, in our case print 1.
6. After inner loop, advance the cursor position to next line i.e. print a dummy blank line.
Program to print square number
pattern
/**
* C program to print square number pattern
*/

#include <stdio.h>

int main()
{
int rows, cols, i, j;

/* Input rows and columns from user */


printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

/* Iterate through rows */


for(i=1; i<=rows; i++)
{
/* Iterate through columns */
for(j=1; j<=cols; j++)
{
printf("1");
}

printf("\n");
}

return 0;
}

C program to print number


pattern with 1, 0 at alternate
columns
Write a C program to print the given number pattern series of 1's and 0's at alternate
columns using loop. How to print number pattern with one's at even column and zero's
at odd column using for loop in C programming. Logic to print given number pattern of
1 and 0 at alternate columns.
Example

Input

Input rows: 5
Input columns: 5

Output

01010
01010
01010
01010
01010

Required knowledge
Basic C programming, Loop

Must know - Program to check even number

Logic to print number pattern with 1, 0


at alternate columns
In previous post I explained a similar pattern. Logic to print this is almost similar. If you
have noticed the pattern carefully, for every odd columns 0 is printed and for every
even columns 1 is printed.

Below is the step by step descriptive logic to print the given pattern.

1. Input number of rows and columns to print from user. Store it in some variable
say rows and cols.
2. To iterate through rows run an outer loop from 1 to rows. The loop structure should look
like for(i=1; i<=rows; i++).
3. To iterate through columns run an inner loop from 1 to cols. The loop structure should look
like for(j=1; j<=cols; j++).
4. Inside the inner loop print 1 if current column is even otherwise print 0.
Means if(j%2==0) then print 1 otherwise print 0.
5. Finally move to the next line after printing one column.

Program to print number pattern with


1, 0 at even/odd columns
/**
* C program to print number pattern with 1/0 at even/odd position
*/

#include <stdio.h>

int main()
{
int rows, cols, i, j;

/* Input rows and columns from user */


printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

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


{
for(j=1; j<=cols; j++)
{
// Print 1 if current column is even
if(j%2 == 1)
{
printf("0");
}
else
{
printf("1");
}
}

printf("\n");
}

return 0;
}

The above method is easy to understand and write. However, you can further optimize
the above method by removing the if else condition. The statement j%2 returns 0 if
number is even otherwise returns 1. We only need to print complement of value
returned by j%2.
Program to print number pattern at
even/odd columns
/**
* C program to print number pattern with 1/0 at even/odd position
*/

#include <stdio.h>

int main()
{
int rows, cols, i, j;

/* Input rows and columns from user */


printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

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


{
for(j=1; j<=cols; j++)
{
printf("%d", !(j%2));
}

printf("\n");
}

return 0;
}
C program to print box
number pattern with plus in
center
July 27, 2017C programmingC, Loop, Number Patterns, Program

Write a C program to print the given box number pattern of 1's and 0's with plus in
center of the box using loop. How to print box number pattern with plus in center using
for loop in C programming. Logic to print box number pattern with plus in center of the
box in C program.

Example

Input

Input rows: 5
Input columns: 5

Output

11011
11011
00000
11011
11011

Required knowledge

Logic to print box number pattern with


plus in center
Before I get to formal descriptive logic of the pattern, have a close look at the given
pattern. You will notice that 0 is printed for central columns or rows i.e. 0 is printed
for all cols / 2 and rows / 2.
Below is the step by step descriptive logic to print the given number pattern.

1. Input number of rows and columns to print from user. Store it in some variable
say rows and cols.
2. To iterate through rows run an outer loop from 1 to rows. The loop structure should look
like for(i=1; i<=rows; i++).
3. To iterate though columns run an inner loop from 1 to cols. The loop structure should look
like for(j=1; j<=cols; j++).
4. We already know that 0 is printed only for central rows and columns otherwise 1 is printed.
Hence, if(i == rows/2 || j == cols/2), then print 0 otherwise print 1.
5. Finally, move to the next line after printing all columns of a row.

Program to print box number pattern


with plus in center
/**
* C program to print box number pattern with plus in center
*/

#include <stdio.h>

int main()
{
int rows, cols, i, j;
int centerRow, centerCol;

/* Input rows and columns from user */


printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

centerRow = (rows+1) / 2;
centerCol = (cols+1) / 2;

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


{
for(j=1; j<=cols; j++)
{
// Print 0 for central rows or columns
if(centerCol == j || centerRow == i)
{
printf("0");
}
else if((cols%2 == 0 && centerCol+1 == j) || (rows%2 ==
0 && centerRow+1 == i))
{
// Print an extra 0 for even rows or columns
printf("0");
}
else
{
printf("1");
}
}

printf("\n");
}

return 0;
}

C program to find power of


a number using for loop
June 2, 2017C programmingC, Loop, Program

Write a C program to find power of any number using for loop. How to find power of
any number without using built in library functions in C programming. Logic to find
power of any number without using pow() function in C program.

Example

Input

Input base: 2
Input exponent: 5

Output

2 ^ 5 = 32

Required knowledge
Basic C programming, For loop

Logic to find power of any number


Below is the step by step descriptive logic.

1. Input base and exponents from user. Store it in two variables say base and expo.
2. Initialize a power variable with 1. Which is power = 1.
3. Run a loop from 1 to expo, increment loop counter by 1 in each iteration. The loop structure
must look similar to for(i=1; i<=expo; i++).
4. Multiply power with num i.e. power = power * num.
5. Finally after loop you are left with power in power variable.
Read more - Program to find power using inbuilt pow() function.

Program to find power of any number


/**
* C program to find power of any number using for loop
*/

#include <stdio.h>

int main()
{
int base, exponent;
long long power = 1;
int i;

/* Read base and exponent from user */


printf("Enter base: ");
scanf("%d", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);

/* Multiply base, exponent times*/


for(i=1; i<=exponent; i++)
{
power = power * base;
}

printf("%d ^ %d = %lld", base, exponent, power);

return 0;
}

C program to print rhombus


or parallelogram star
pattern
August 5, 2017C programmingC, Loop, Program, Star Patterns
Write a C program to print rhombus star(*) pattern of N rows using for loop. How to
print rhombus or parallelogram star pattern using for loop in C programming. Logic to
print rhombus or parallelogram star pattern series in C program.

Example

Input

Enter number of rows: 5

Output

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

Required knowledge
Basic C programming, For loop

Must know - Program to print square star pattern

Logic to print rhombus star pattern


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

Before I decode the logic of this pattern, have a close look of the pattern. Place your
mouse cursor on to the pattern, to count spaces. Try to decode the logic of given
pattern.

If you remove trailing spaces the pattern becomes a simple square star
pattern of N rows and columns. You only need to add logic of printing spaces with the
existing logic of square star pattern. Now, notice again the pattern carefully. You will
find that there are N - i spaces per row (where i is the current row number).

Step-by-step descriptive logic to print rhombus star pattern


1. Read number of rows from user. Store it in some variable say rows.
2. To iterate through rows, run an outer loop from 1 to rows. Define a loop with
structure for(i=1; i<=rows; i++).
3. To print spaces, run an inner loop from 1 to rows - i. Construct a loop with
structure for(j=1; j<=rows - i; j++). Inside this loop print space.
4. To iterate through columns for printing stars. Run another inner loop from 1 to rows. Define
another loop with structure for(j=1; j<=rows; j++). Inside this loop print star(*) or any
other character which you want to print as output.

Program to print rhombus star pattern


/**
* C program to print Rhombus star pattern series
*/

#include <stdio.h>

int main()
{
int i, j, rows;

// Input number of rows from user


printf("Enter rows: ");
scanf("%d", &rows);

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


{
// Print trailing spaces
for(j=1; j<=rows - i; j++)
{
printf(" ");
}

// Print stars after spaces


for(j=1; j<=rows; j++)
{
printf("*");
}

// Move to the next line/row


printf("\n");
}

return 0;
}
C program to print right
triangle star pattern
August 5, 2017C programmingC, Loop, Program, Star Patterns

Write a C program to print right triangle star(*) pattern series using for loop. How to
print right triangle star pattern series of n rows using for loop in C programming. Logic
to print right triangle star pattern in C.

Example

Input

Input number of rows: 5

Output

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

Required knowledge

Logic to print right triangle star pattern


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

Printing right triangle pattern is simple if you got the pattern. If you look to the pattern
carefully you will find that you have to print stars in increasing order of rows (i.e. 1 star
in first row, followed by 2 stars in second and so on...). To print so we will use the
concept of square star pattern with a little change in inner loop code.
In the pattern given total number of stars per column in each row is equal to the current
row number and we will use this as a termination limit in the inner for loop.
Program to print right triangle star
pattern
/*
* C program to print right triangle star pattern series
*/

#include <stdio.h>

int main()
{
int i, j, n;

// Input number of rows from user


printf("Enter value of n: ");
scanf("%d", &n);

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


{
// Print i number of stars
for(j=1; j<=i; j++)
{
printf("*");
}

// Move to next line/row


printf("\n");
}

return 0;
}

C program to print reverse


right triangle star pattern
August 5, 2017C programmingC, Loop, Program, Star Patterns

Write a C program to print reverse/inverted right triangle star(*) pattern series using
for loop. How to print reverse/inverted right triangle star pattern series of n rows using
for loop in C programming. Logic to print inverted right triangle star pattern in C
program.

Example
Input

Input rows: 5

Output

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

Required knowledge
Basic C programming, For loop

Must know - Program to print right triangle star pattern

Program to print inverted right


triangle star pattern
/**
* Reverse right triangle star pattern program in C
*/

#include <stdio.h>

int main()
{
int i, j, n;

// Input number of rows from user


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

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


{
for(j=i; j<=n; j++)
{
printf("*");
}

// Move to the next line/row


printf("\n");
}

return 0;
}

C program to print diamond


star pattern
August 5, 2017C programmingC, Loop, Program, Star Patterns

Write a C program to print the diamond star(*) pattern series using for loop. How to
print diamond star pattern structure using for loop in C programming. Logic to print
diamond star pattern series in C program.

Example

Input

Input rows: 5

Output

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

Required knowledge
Basic C programming, For loop

Logic to print diamond star pattern


At single glance the patter seems difficult to be printed so, to make the pattern easy I
have bisected the pattern in two halves.

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

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

If you notice these two patterns are simple pyramid (with n rows) and reverse pyramid
pattern (with n-1 rows). Hence, we just need to write down the codes of both pyramid
and reverse pyramid star pattern one by one to get the final pattern.

Program to print diamond star pattern


/**
* C program to print diamond star pattern
*/

#include <stdio.h>

int main()
{
int i, j, n;

printf("Enter N : ");
scanf("%d", &n);

// Print the upper pyramid


for(i=1; i<=n; i++)
{
for(j=i; j<n; j++)
{
printf(" ");
}
for(j=1; j<=(2*i-1); j++)
{
printf("*");
}
printf("\n");
}
// Print the lower triangle
for(i=n; i>=1; i--)
{
for(j=i; j<=n; j++)
{
printf(" ");
}
for(j=2; j<(2*i-1); j++)
{
printf("*");
}
printf("\n");
}

return 0;
}
C program to find fibonacci
series upto n terms
June 4, 2017C programmingC, Loop, Program

Write a C program to print Fibonacci series up to n terms using loop. How to generate
Fibonacci series up to n terms using loops in C programming. Logic to print Fibonacci
series in a given range in C program.

Example

Input

Input number of terms: 10

Output

Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Required knowledge
Basic C programming, While loop

What is Fibonacci series?


Fibonacci series is a series of numbers where the current number is the sum of
previous two terms. For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... , (n-1th + n-2th)

Logic to generate Fibonacci series


Below is the step by step descriptive logic to generate n Fibonacci terms.

1. Input number of Fibonacci terms from user. Store it in some variable say terms.
2. Initialize three variable, I call it as Fibonacci magic initialization. a=0, b=1 and c=0. Here c is
the current term, b is the n-1th term and a is n-2th term.
3. Run a loop from 1 to terms, incrementing loop counter by 1. The loop structure should look
like for(i=1; i<=term; i++). It will iterate through n terms
4. Inside the loop copy the value of n-1th to n-2th term i.e. a = b. Second copy the value of nth
to n-1th term b = c. Finally compute the new term by adding previous two terms i.e. c = a +
b.
5. Print the value of c to print the current Fibonacci term.

Program to print Fibonacci series up to


n terms
/**
* C program to print Fibonacci series up to n terms
*/

#include <stdio.h>

int main()
{
int a, b, c, i, terms;

/*
* Input a number from user
*/
printf("Enter number of terms: ");
scanf("%d", &terms);

// Fibonacci magic initialization


a = 0;
b = 1;
c = 0;

printf("Fibonacci terms: \n");

// Iterate through n terms


for(i=1; i<=terms; i++)
{
printf("%d, ", c);

a = b; // Copy n-1 to n-2


b = c; // Copy current to n-1
c = a + b; // New term
}

return 0;
}
ter number of terms: 10ibonacci terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Before you move on to next exercise or program. Let me show one more example
related to Fibonacci series. Let us code the solution to print Fibonacci series between
a given range. Below is the program to print Fibonacci series between given range.
Program to print Fibonacci series in
given range
/**
* C program to print Fibonacci series in given range
*/

#include <stdio.h>

int main()
{
int a, b, c, start, end;

/*
* Input a number from user
*/
printf("Enter starting term: ");
scanf("%d", &start);
printf("Enter end term: ");
scanf("%d", &end);

// Fibonacci magic initialization


a = 0;
b = 1;
c = 0;

printf("Fibonacci terms: \n");

// Iterate through terms


while(c <= end)
{

// If current term is greater than start term


if(c >= start)
{
printf("%d, ", c);
}

a = b; // Copy n-1 to n-2


b = c; // Copy current to n-1
c = a + b; // New term
}

return 0;
}
C program to find
Armstrong numbers
between 1 to n
June 4, 2017C programmingC, Loop, Program

Write a C program to enter any number and print all Armstrong numbers between 1 to
n. How to print Armstrong numbers between given interval using loop in C program.
Logic to generate Armstrong numbers in given range in C program.

Example

Input

Enter lower limit: 1


Enter upper limit: 1000

Output

Armstrong number between 1 to 1000 are:


1, 2, 3, 4, 5, 6, 7, 8, 9, 370, 371, 407

Required knowledge

What is Armstrong number?


An Armstrong number is an n-digit number that is equal to the sum of the nth powers
of its digits. Below are few examples of Armstrong numbers:
6 = 61 = 6
371 = 3 + 7 + 1 = 371
3 3 3

Logic to generate Armstrong number


from 1 to n
Below is the step by step descriptive logic to generate Armstrong numbers:

1. Input upper limit to generate Armstrong number from user. Store it in some variable say end.
2. Run a loop from 1 to end, incrementing 1 in each iteration. The loop structure should look
like for(i=1; i<=end; i++).
3. Inside the loop print the current number if it is Armstrong number.

Read more - Program to check Armstrong number

Program to generate Armstrong


numbers from 1 to n
/**
* C program to print Armstrong numbers from 1 to n
*/
#include <stdio.h>
#include <math.h>

int main()
{
int num, lastDigit, digits, sum, i, end;

/*
* Input upper limit from user
*/
printf("Enter upper limit: ");
scanf("%d", &end);

printf("Armstrong number between 1 to %d are: \n", end);

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


{
sum = 0;

// Copy the value of num for processing


num = i;

// Find total digits in num


digits = (int) log10(num) + 1;

/*
* Calculate sum of power of digits
*/
while(num > 0)
{
// Extract the last digit
lastDigit = num % 10;

// Find sum
sum = sum + pow(lastDigit, digits);

// Remove the last digit


num = num / 10;
}

// Check for Armstrong number


if(i == sum)
{
printf("%d, ", i);
}

return 0;
}

Once, you are done with generating Armstrong numbers from 1 to n. You can easily
modify the logic to work it for given ranges. Below program generates Armstrong
numbers in a given range.

Program to find Armstrong numbers in


given range
/**
* C program to generate Armstrong numbers in a given range
*/
#include <stdio.h>
#include <math.h>

int main()
{
int num, lastDigit, digits, sum, i;
int start, end;

/*
* Input lower and upper limit from user
*/
printf("Enter lower limit: ");
scanf("%d", &start);
printf("Enter upper limit: ");
scanf("%d", &end);

printf("Armstrong number between %d to %d are: \n", start, end);

for(i=start; i<=end; i++)


{
sum = 0;

// Copy the value of num for processing


num = i;

// Find total digits in num


digits = (int) log10(num) + 1;

/*
* Calculate sum of power of digits
*/
while(num > 0)
{
// Extract the last digit
lastDigit = num % 10;

// Find sum
sum = sum + pow(lastDigit, digits);

// Remove the last digit


num = num / 10;
}

// Check for Armstrong number


if(i == sum)
{
printf("%d, ", i);
}
}

return 0;
}

C Program to Check whether a given Number is Armstrong


This C Program checks whether a given number is armstrong number. An Armstrong number is
an n-digit base b number such that the sum of its (base b) digits raised to the power n is the number
itself. Hence 153 because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
Here is source code of the C Program to check whether a given number is armstrong
number.
The C program is successfully compiled and run on a Linux system. The program output
is also shown below.
1. /*
2. * C Program to Check whether a given Number is Armstrong
3. */
4. #include <stdio.h>
5. #include <math.h>
6.
7. void main()
8. {
9. int number, sum = 0, rem = 0, cube = 0, temp;
10.
11. printf ("enter a number");
12. scanf("%d", &number);
13. temp = number;
14. while (number != 0)
15. {
16. rem = number % 10;
17. cube = pow(rem, 3);
18. sum = sum + cube;
19. number = number / 10;
20. }
21. if (sum == temp)
22. printf ("The given no is armstrong no");
23. else
24. printf ("The given no is not a armstrong no");
25. }

C program to find perfect


numbers between 1 to n
June 4, 2017C programmingC, Loop, Program

Write a C program to print all Perfect numbers between 1 to n. C program to find all
perfect numbers between given range. How to generate all perfect numbers between
given interval using loop in C programming. Logic to find all perfect numbers in a given
range in C program.

Example

Input

Input upper limit: 100

Output

Perfect numbers between 1 to 100: 6, 28


Required knowledge
Basic C programming, For loop, Nested loop, If else

Must know –
 Program to check divisibility.
 Program to find sum of digits.

What is Perfect number?


Perfect number is a positive integer which is equal to the sum of its proper positive
divisors.

For example: 6 is the first perfect number


Proper divisors of 6 are 1, 2, 3
Sum of its proper divisors = 1 + 2 + 3 = 6.
Hence 6 is a perfect number.

Logic to find all Perfect number


between 1 to n
Below is the step by step descriptive logic to find Perfect numbers from 1 to n.

1. Input upper limit from user to print all Perfect numbers. Store it in some variable say end.
2. Run a loop from 1 to end, incrementing 1 in each iteration. The loop structure should look
like for(i=1; i<=end; i++). Inside this loop, you need to check each element for Perfect
number.
3. Inside the loop print the current number if it is a Perfect number.

Read more - Program to check Perfect number.

Program to find all perfect numbers


between 1 to n
/**
* C program to print all Perfect numbers between 1 to n
*/

#include <stdio.h>

int main()
{
int i, j, end, sum;

/* Input upper limit to print perfect number */


printf("Enter upper limit: ");
scanf("%d", &end);

printf("All Perfect numbers between 1 to %d:\n", end);

/*
* Iterate from 1 to end
*/
for(i=1; i<=end; i++)
{
sum = 0;

/*
* Check whether the current number i is Perfect number or
not
*/
for(j=1; j<i; j++)
{
if(i % j == 0)
{
sum += j;
}
}

/* If the current number i is Perfect number */


if(sum == i)
{
printf("%d, ", i);
}
}

return 0;
}

Once, you got the logic to print perfect numbers from 1 to n. You can easily modify the
logic to print perfect numbers in given range. I am writing the below program with little
modification to print perfect numbers in given range.

Program to generate perfect numbers


in given range
/**
* C program to print all Perfect numbers between 1 to n
*/

#include <stdio.h>

int main()
{
int i, j, start, end, sum;

/* Input lower and upper limit from user */


printf("Enter lower limit: ");
scanf("%d", &start);
printf("Enter upper limit: ");
scanf("%d", &end);

printf("All Perfect numbers between %d to %d:\n", start, end);

/*
* Iterate from start to end
*/
for(i=start; i<=end; i++)
{
sum = 0;

/*
* Check whether the current number i is Perfect number or
not
*/
for(j=1; j<i; j++)
{
if(i % j == 0)
{
sum += j;
}
}

/* If the current number i is Perfect number */


if(sum == i)
{
printf("%d, ", i);
}
}

return 0;
}
C program to check whether
a number is perfect number
or not
June 4, 2017C programmingC, Loop, Program

Write a C program to enter any number and check whether the number is Perfect
number or not. How to check perfect numbers in C programming using loop. Logic to
check perfect number in C program.

Example

Input

Input any number: 6

Output

6 is PERFECT NUMBER

Required knowledge
Basic C programming, For loop, If else

Must know -
 Program to check divisibility.
 Program to find sum of digits.

What is Perfect number?


Perfect number is a positive integer which is equal to the sum of its proper positive
divisors.
For example: 6 is the first perfect number
Proper divisors of 6 are 1, 2, 3
Sum of its proper divisors = 1 + 2 + 3 = 6.
Hence 6 is a perfect number.
Logic to check Perfect number
Below is the step by step descriptive logic to check Perfect number.

1. Input a number from user, which is to be checked for perfect number. Store it in some variable
say num.
2. Initialize another variable to store sum of proper positive divisors, say sum = 0.
3. Run a loop from 1 to num/2, incrementing 1 in each iteration. The loop structure is for(i=1;
i<=num/2; i++). Here a question might pop in your mind. Why running loop from 1 to num/2,
why not till num? Because a number does not have any proper positive divisor greater
than num/2.
4. Inside the loop if current number i.e. i is proper positive divisor of num, then add it to sum.
Which is if(num % i == 0) then, perform sum = sum + i.
5. Finally, if the sum of proper positive divisors equals to the original number. Which is if(sum
== num) then, the given number is Perfect number otherwise not.

Program to check perfect number


/**
* C program to check whether a number is Perfect number or not
*/

#include <stdio.h>

int main()
{
int i, num, sum = 0;

/* Input a number from user */


printf("Enter any number to check perfect number: ");
scanf("%d", &num);

/* Calculate sum of all proper divisors */


for(i=1; i<num; i++)
{
/* If i is a divisor of num */
if(num%i==0)
{
sum += i;
}
}

/* Check whether the sum of proper divisors is equal to num */


if(sum == num)
{
printf("%d is PERFECT NUMBER", num);
}
else
{
printf("%d is NOT PERFECT NUMBER", num);
}

return 0;
}

C program to print X star


pattern
August 5, 2017C programmingC, Loop, Program, Star Patterns

Write a C program to print X star pattern series using loop. How to print the X star
pattern series using for loop in C programming. Logic to print X using stars in C
program.

Example

Input

Input N: 5

Output

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

Required knowledge
Basic C programming, If else, Loop

Logic to print X star pattern


There can be many logic to solve the particular problem. Here I am adding two
methods to print the given star pattern. First I will cover the easiest method.

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

Logic to print the X star pattern can really be complex and confusing if you haven't
gone through two previous star pattern programs.

Must know -
 Program to print hollow pyramid star pattern
 Program to print hollow inverted pyramid star pattern

If you bisect the pattern horizontally you will get two pattern.

* *
* *
* *
* *
*

* *
* *
* *
* *

X star pattern is a combination of both of these patterns. Where the first one is similar
to the hollow inverted pyramid and second one to hollow pyramid star pattern.
Hence if you haven't gone through these two posts I recommend you to go through
them before continuing. As I won't be getting in detail about these two patterns here.

Program to print X star pattern


/**
* C program to print X star pattern series
*/
#include <stdio.h>

int main()
{
int i, j, N;

printf("Enter N: ");
scanf("%d", &N);

// Print first upper hollow inverted pyramid


for(i=N; i>=1; i--)
{
// Print trailing spaces
for(j=i; j<N; j++)
{
printf(" ");
}

// Print upper hollow triangular part


for(j=1; j<=(2*i-1); j++)
{
if(j==1 || j==(2*i-1))
{
printf("*");
}
else
{
printf(" ");
}
}

printf("\n");
}

// Print the lower half hollow pyramid


for(i=2; i<=N; i++)
{
//Prints trailing spaces
for(j=i; j<N; j++)
{
printf(" ");
}

//Prints lower hollow triangular part


for(j=1; j<=(2*i-1); j++)
{
if(j==1 || j==(2*i-1))
{
printf("*");
}
else
{
printf(" ");
}
}

printf("\n");
}

return 0;
}

Logic to print the X star pattern - 2


This logic was submitted by a Codeforwin lover - Md Shahbaz. Let us see the pattern
once more with different angle. Divide the given pattern logically in two different
sections as -

*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*

Here goes the descriptive logic to print the pattern :

1. The pattern consists of exactly N * 2 - 1 rows and columns. Hence run an outer loop to
iterate through rows using the loop formation for(i=1; i<= count; i++) (where count =
N * 2 - 1).
2. Since each row contains exactly N * 2 - 1 columns. Therefore, run inner loop as for(j=1;
j<=count; j++).
3. Inside this loop as you can notice that stars gets printed in two conditions i.e.
 For the first diagonal i.e. when row and column number both are equal. Means print star
whenever if(i == j).
 For the second diagonal i.e. stars gets printed if(j == count - i + 1).
4. Print spaces whenever stars doesn't gets printed.

Program to print X star pattern - 2


/**
* C program to print X star pattern series
*/

#include <stdio.h>

int main()
{
int i, j, N;
int count;

printf("Enter N: ");
scanf("%d", &N);

count = N * 2 - 1;

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


{
for(j=1; j<=count; j++)
{
if(j==i || (j==count - i + 1))
{
printf("*");
}
else
{
printf(" ");
}
}

printf("\n");
}

return 0;
}

Before you move on. You might love to check the similar number pattern program
1 1
2 2
3 3
4 4
5
4 4
3 3
2 2
1 1

Program to print "Hello C" using if and else statement both.


Well, this is not possible, Compiler either execute if or else statement, but we can make
fool to other as We are executing if and else both.

1
/*Program to print "Hello C" using if and else
2
statement both.*/
3

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

7 if(!printf("Hello "))

8 ;

else
9
printf("C\n");
10
return 0;
11
}
12

explanation:
In if(!printf("Hello ")) statement printf will print "Hello " and return 6 (number of printed
character), hence condition will be false but to !6 that is 0, then execution will jump to else
block.
C Program to Delete duplicate elements from an array
Program : To delete duplicate elements in an array

1 #include<stdio.h>
2
3 int main() {
4 int arr[20], i, j, k, size;
5
6 printf("\nEnter array size : ");
7 scanf("%d", &size);
8
9 printf("\nAccept Numbers : ");
10 for (i = 0; i < size; i++)
11 scanf("%d", &arr[i]);
12
13 printf("\nArray with Unique list : ");
14 for (i = 0; i < size; i++) {
15 for (j = i + 1; j < size;) {
16 if (arr[j] == arr[i]) {
17 for (k = j; k < size; k++) {
18 arr[k] = arr[k + 1];
19 }
20 size--;
21 } else
22 j++;
23 }
24 }
25
26 for (i = 0; i < size; i++) {
27 printf("%d ", arr[i]);
28 }
29
30 return (0);
31 }
C Program to Reversing an Array Elements in C
Programming

1 #include<stdio.h>
2
3 int main() {
4 int arr[30], i, j, num, temp;
5
6 printf("\nEnter no of elements : ");
7 scanf("%d", &num);
8
9 //Read elements in an array
10 for (i = 0; i < num; i++) {
11 scanf("%d", &arr[i]);
12 }
13
14 j = i - 1; // j will Point to last Element
15 i = 0; // i will be pointing to first element
16
17 while (i < j) {
18 temp = arr[i];
19 arr[i] = arr[j];
20 arr[j] = temp;
21 i++; // increment i
22 j--; // decrement j
23 }
24
25 //Print out the Result of Insertion
26 printf("\nResult after reversal : ");
27 for (i = 0; i < num; i++) {
28 printf("%d \t", arr[i]);
29 }
30
31 return (0);
32 }

C Program to Copy all elements of an array into


Another array

1 #include<stdio.h>
2
3 int main() {
4 int arr1[30], arr2[30], i, num;
5
6 printf("\nEnter no of elements :");
7 scanf("%d", &num);
8
9 //Accepting values into Array
10 printf("\nEnter the values :");
11 for (i = 0; i < num; i++) {
12 scanf("%d", &arr1[i]);
13 }
14
15 /* Copying data from array 'a' to array 'b */
16 for (i = 0; i < num; i++) {
17 arr2[i] = arr1[i];
18 }
19
20 //Printing of all elements of array
21 printf("The copied array is :");
22 for (i = 0; i < num; i++)
23 printf("\narr2[%d] = %d", i, arr2[i]);
24
25 return (0);
26 }
C Program to Delete an element from the specified
location from Array

Program :

1 #include<stdio.h>
2
3 int main() {
4 int arr[30], num, i, loc;
5
6 printf("\nEnter no of elements :");
7 scanf("%d", &num);
8
9 //Read elements in an array
10 printf("\nEnter %d elements :", num);
11 for (i = 0; i < num; i++) {
12 scanf("%d", &arr[i]);
13 }
14
15 //Read the location
16 printf("\n location of the element to be deleted :");
17 scanf("%d", &loc);
18
19 /* loop for the deletion */
20 while (loc < num) {
21 arr[loc - 1] = arr[loc];
22 loc++;
23 }
24 num--; // No of elements reduced by 1
25
26 //Print Array
27 for (i = 0; i < num; i++)
28 printf("\n %d", arr[i]);
29
30 return (0);
31 }

C Program to Insert an element in an Array

1 #include<stdio.h>
2
3 int main() {
4 int arr[30], element, num, i, location;
5
6 printf("\nEnter no of elements :");
7 scanf("%d", &num);
8
9 for (i = 0; i < num; i++) {
10 scanf("%d", &arr[i]);
11 }
12
13 printf("\nEnter the element to be inserted :");
14 scanf("%d", &element);
15
16 printf("\nEnter the location");
17 scanf("%d", &location);
18
19 //Create space at the specified location
20 for (i = num; i >= location; i--) {
21 arr[i] = arr[i - 1];
22 }
23
24 num++;
25 arr[location - 1] = element;
26
27 //Print out the result of insertion
28 for (i = 0; i < num; i++)
29 printf("n %d", arr[i]);
30
31 return (0);
32 }

C Program to Search an element in Array

1 #include<stdio.h>
2
3 int main() {
4 int a[30], ele, num, i;
5
6 printf("\nEnter no of elements :");
7 scanf("%d", &num);
8
9 printf("\nEnter the values :");
10 for (i = 0; i < num; i++) {
11 scanf("%d", &a[i]);
12 }
13
14 //Read the element to be searched
15 printf("\nEnter the elements to be searched :");
16 scanf("%d", &ele);
17
18 //Search starts from the zeroth location
19 i = 0;
20 while (i < num && ele != a[i]) {
21 i++;
22 }
23
24 //If i < num then Match found
25 if (i < num) {
26 printf("Number found at the location = %d", i + 1);
27 } else {
28 printf("Number not found");
29 }
30
31 return (0);
32 }

C Program to Merge Two arrays in C Programming

1 #include<stdio.h>
2
3 int main() {
4 int arr1[30], arr2[30], res[60];
5 int i, j, k, n1, n2;
6
7 printf("\nEnter no of elements in 1st array :");
8 scanf("%d", &n1);
9 for (i = 0; i < n1; i++) {
10 scanf("%d", &arr1[i]);
11 }
12
13 printf("\nEnter no of elements in 2nd array :");
14 scanf("%d", &n2);
15 for (i = 0; i < n2; i++) {
16 scanf("%d", &arr2[i]);
17 }
18
19 i = 0;
20 j = 0;
21 k = 0;
22
23 // Merging starts
24 while (i < n1 && j < n2) {
25 if (arr1[i] <= arr2[j]) {
26 res[k] = arr1[i];
27 i++;
28 k++;
29 } else {
30 res[k] = arr2[j];
31 k++;
32 j++;
33 }
34 }
35
36 /* Some elements in array 'arr1' are still remaining
37 where as the array 'arr2' is exhausted */
38
39 while (i < n1) {
40 res[k] = arr1[i];
41 i++;
42 k++;
43 }
44
45 /* Some elements in array 'arr2' are still remaining
46 where as the array 'arr1' is exhausted */
47
48 while (j < n2) {
49 res[k] = arr2[j];
50 k++;
51 j++;
52 }
53
54 //Displaying elements of array 'res'
55 printf("\nMerged array is :");
56 for (i = 0; i < n1 + n2; i++)
57 printf("%d ", res[i]);
58
59 return (0);
60
61 }
C program to print all
negative elements in an
array
June 5, 2017C programmingArray, C, Program

Write a C program to read elements in an array and print all negative elements. How
to display all negative elements in an array using loop in C programming. Logic to
display all negative elements in of a given array using loop.

Example

Input

Input array:
-1
-10
100
5
61
-2
-23
8
-90
51

Output

Output: -1, -10, -2, -23, -90

Required knowledge
Array

Must know -
 Program to read and print array elements.
 Program to check negative numbers.

Logic to display negative elements in


array
Displaying negative, positive, prime, even, odd or any special number doesn't requires
special skills. You only need to know how to display array elements and how to check
that special number.

Now, considering our case where we need to display only negative elements of array.
Below is a descriptive logic to display all negative elements of array.

1. Input elements in array.


2. Check if the current element is negative or not. If the current array element is negative then
print the current element otherwise skip. To check you simple use if(array[i] <
0) (where i is the current array index).
3. Repeat step 2 till the last element of array.

Program to print negative elements in


array
/**
* C program to print all negative elements in array
*/

#include <stdio.h>

#define MAX_SIZE 100

int main()
{
int arr[MAX_SIZE]; //Declares an array of MAX_SIZE
int i, n;

/* Input size of the array */


printf("Enter size of the array : ");
scanf("%d", &n);

/* Input elements in the array */


printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}

printf("\nAll negative elements in array are : ");


for(i=0; i<n; i++)
{
// Print current element if it is negative
if(arr[i] < 0)
{
printf("%d\t", arr[i]);
}
}

return 0;
}

C program to sort array in


ascending or descending
order
June 13, 2017C programmingArray, C, Program

Write a C program to read elements in an array and sort elements of the array in
ascending order. Read unsorted integer values in array and sort them in ascending
order. Logic to sort an array in ascending order.

Example

Input

Input size of array: 10


Input array elements: 20, 2, 10, 6, 52, 31, 0, 45, 79, 40

Output

Array sorted in ascending order: 0, 2, 6, 10, 20, 31, 40, 45, 52, 79

Required knowledge
Basic C programming, If else, For loop, Array

Read more - Program to swap two numbers

Logic to sort an array in ascending


order
There are numerous logic to sort a given set of numbers. Here I am using general
algorithm which we apply in real life for simplicity. To sort array we select an element
and place it to its correct position by comparing with subsequent elements.
Below is the step by step descriptive logic to sort array in ascending order.

1. Input size of array and elements in array. Store it in some variable say size and array[].
2. To select each element from the array, run an outer loop from 0 to size - 1. The loop
structure must look like for(i=0; i<size; i++).
3. Run another inner loop from i + 1 to size - 1 to place the currently selected element at its
correct position. The loop structure should look like for(j=i+1; j<size; j++).
4. Inside the inner loop to compare the currently selected element with subsequent elements and
perform swapping if needed. Which is if(array[i] > array[j]) then
swap array[i] and array[j].

Program to sort array in ascending


order
/**
* C program to sort elements of array in ascending order
*/

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
int array[MAX_SIZE];
int size;
int i, j, temp;

/* Input size of array */


printf("Enter size of array: ");
scanf("%d", &size);

/* Input elements in array */


printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &array[i]);
}

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


{
/*
* Place the currently selected element array[i]
* to its correct place.
*/
for(j=i+1; j<size; j++)
{
/*
* Swap if currently selected array element
* is not at its correct position.
*/
if(array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}

/* Print the sorted array */


printf("\nElements of array in sorted ascending order: ");
for(i=0; i<size; i++)
{
printf("%d\t", array[i]);
}

return 0;
}

Important note: With a small change in the program you can change the logic for
descending order. Which means replace if(array[i] > array[j]) with if(array[i]
< array[j]) to transform the logic for descending order.

C program to count
frequency of each element
in an array
July 18, 2017C programmingArray, C, Program

Write a C program to read elements in an array and find frequency of each element in
an array. C Program to count the occurrence of each element in an array. Logic to
count frequency of each element in an array.
Example

Input

Input array elements: 5, 10, 2, 5, 50, 5, 10, 1, 2, 2

Output

Frequency of 5 = 3
Frequency of 10 = 2
Frequency of 2 = 3
Frequency of 50 = 1
Frequency of 1 = 1

Required knowledge
Basic C programming, If else, For loop, Array

Logic to count frequency of each


element of array
Finding frequency of each array element is completely based on finding duplicate
elements in an array. In fact you can take this program as modified version of find
duplicate program. Here you need to find total duplicate count per element instead of
whole.
Below is the step by step descriptive logic to count frequency of each element of array.

1. Read input in all array elements from user. Store it in some variable say arr contains all array
elements.
2. Declare another array with same size as of input array size to store frequency of each array
elements. Say freq will store frequencies of all array elements.
3. To count frequency of each element we require two loops. One outer loop to select an array
element. Second inner loop to find first duplicate element of the currently selected array
element by outer loop. Run an outer loop from 0 to N. The loop structure must look
like for(i=0; i<N; i++).
4. Inside outer loop, initialize a count variable to count total frequency of the currently selected
array element. Say count = 1.
5. Run an inner loop to count total duplicates of currently selected array element. Run an inner
loop from i+1 to N. The loop structure should look like for(j=i+1; j<N; j++).
6. Inside inner loop, if a duplicate element is found increment the frequency count of current array
element. Which is if(arr[i] == arr[j]) then count++.
7. After all duplicates has been counted. Store the total duplicate count of current element in the
frequency array. Which is say freq[i] = count.
8. Finally print the freq array to get frequencies of each array element.
Read more - Program to find unique elements in array

Program to count frequency of each


element of array
/**
* C program to count frequency of each element of array
*/

#include <stdio.h>

int main()
{
int arr[100], freq[100];
int size, i, j, count;

/* Input size of array */


printf("Enter size of array: ");
scanf("%d", &size);

/* Input elements in array */


printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);

/* Initially initialize frequencies to -1 */


freq[i] = -1;
}

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


{
count = 1;
for(j=i+1; j<size; j++)
{
/* If duplicate element is found */
if(arr[i]==arr[j])
{
count++;

/* Make sure not to count frequency of same element


again */
freq[j] = 0;
}
}

/* If frequency of current element is not counted */


if(freq[i] != 0)
{
freq[i] = count;
}
}

/*
* Print frequency of each element
*/
printf("\nFrequency of all elements of array : \n");
for(i=0; i<size; i++)
{
if(freq[i] != 0)
{
printf("%d occurs %d times\n", arr[i], freq[i]);
}
}

return 0;
}
C program to add two
matrices
June 14, 2017C programmingArray, C, Matrix, Program

Write a C program to read elements in two matrices and add elements of both
matrices. C program for addition of two matrix. Matrix addition program in C. Logic to
add two matrix in C programming.

Example

Input

Input elements in 3x3 matrix1:


1 2 3
4 5 6
7 8 9
Input elements in 3x3 matrix2:
9 8 7
6 5 4
3 2 1

Output

Sum of both matrix =


10 10 10
10 10 10
10 10 10

Required knowledge
Basic C programming, For loop, Array

Matrix Addition
Matrix addition is done element wise (entry wise) i.e. Sum of two matrices A and B of
size mXn is defined by
(A + B) = Aij + Bij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n)
Program to add two matrices
/**
* C program to find sum of two matrices of size 3x3
*/

#include <stdio.h>

#define SIZE 3 // Size of the matrix

int main()
{
int A[SIZE][SIZE]; // Matrix 1
int B[SIZE][SIZE]; // Matrix 2
int C[SIZE][SIZE]; // Resultant matrix

int row, col;

/* Input elements in first matrix*/


printf("Enter elements in matrix A of size 3x3: \n");
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &A[row][col]);
}
}

/* Input elements in second matrix */


printf("\nEnter elements in matrix B of size 3x3: \n");
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &B[row][col]);
}
}

/*
* Add both matrices A and B entry wise or element wise
* and stores result in matrix C
*/
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
/* Cij = Aij + Bij */
C[row][col] = A[row][col] + B[row][col];
}
}

/* Print the value of resultant matrix C */


printf("\nSum of matrices A+B = \n");
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
printf("%d ", C[row][col]);
}
printf("\n");
}

return 0;
}

C program to put even and


odd elements of array in
two separate array
June 12, 2017C programmingArray, C, Program

Write a C program to input elements in an array and put all even and odd elements in
two separate array. How to separate even and odd elements of a given array in two
separate array containing only even or odd elements using C programming.
Example

Input

Input size of the array: 10


Input elements in array: 0 1 2 3 4 5 6 7 8 9

Output

Output even elements in array: 0 2 4 6 8


Output odd elements in array: 1 3 5 7 9

Required knowledge
Basic C programming, If else, Loop, Array, Function

Must know -
 Program to check even/odd using bitwise operator
 Program to read and print array elements

Program to put even and odd elements


in separate array
/**
* C program to put even and odd elements of an array in two
separate array
*/

#include <stdio.h>

#define MAX_SIZE 1000 // Maximum size of the array

/* Function to print array */


void printArray(int arr[], int len);

int main()
{
int arr[MAX_SIZE];
int even[MAX_SIZE], odd[MAX_SIZE];

int evenCount, oddCount;


int i, size;
/* Input size of the array */
printf("Enter size of the array: ");
scanf("%d", &size);

/* Input elements in array */


printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

evenCount = 0;
oddCount = 0;

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


{
// If arr[i] is odd
if(arr[i] & 1)
{
odd[oddCount] = arr[i];
oddCount++;
}
else
{
even[evenCount] = arr[i];
evenCount++;
}
}

printf("\nElements of even array: \n");


printArray(even, evenCount);

printf("\nElements of odd array: \n");


printArray(odd, oddCount);

return 0;
}

/**
* Print the entire integer array
* @arr Integer array to be displayed or printed on screen
* @len Length of the array
*/
void printArray(int arr[], int len)
{
int i;
printf("Elements in the array: ");
for(i=0; i<len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
Read more - Program to sort even and odd elements separately.
Enter size of the array: 10
Enter elements in the array: 0 1 2 3 4 5 6 7 8 9

C program to insert an
element in array
July 18, 2017C programmingArray, C, Program

Write a C program to insert an element in array at specified position. C program to


insert element in an array at given position. The program should also print an error
message if the insert position is invalid. Logic to insert an element in array at given
position in C program.

Example

Input

Input array elements: 10, 20, 30, 40, 50


Input element to insert: 25
Input position where to insert: 3

Output

Elements of array are: 10, 20, 25, 30, 40, 50

Required knowledge
Basic C programming, For loop, Array

Logic to insert an element in array


Below is the step by step descriptive logic to insert an element in array.

1. Input size and elements in array. Store it in some variable say size and arr.
2. Input new element and position to insert in array. Store it in some variable say num and pos.
3. To insert new element in the array, shift elements from the given insert position to one position
right. Hence, run a loop in descending order from size of array to pos to insert. The loop
structure should look like for(i=size; i>=pos; i--).

Inside the loop copy previous element to current element by arr[i] = arr[i - 1];.

Read more - C program to copy array element

4. Finally, after performing shift operation. Copy the new element at its specified position
i.e. arr[pos - 1] = num;.

Program to insert element in array


/**
* C program to insert an element in array at specified position
*/

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int i, size, num, pos;

/* Input size of the array */


printf("Enter size of the array : ");
scanf("%d", &size);

/* Input elements in array */


printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

/* Input new element and position to insert */


printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &pos);

/* If position of element is not valid */


if(pos > size+1 || pos <= 0)
{
printf("Invalid position! Please enter position between 1 to
%d", size);
}
else
{
/* Make room for new array element by shifting to right */
for(i=size; i>=pos; i--)
{
arr[i] = arr[i-1];
}

/* Insert new element at given position and increment size


*/
arr[pos-1] = num;
size++;

/* Print array after insert operation */


printf("Array elements after insertion : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
}
return 0;
}

Elements of even array:


Elements in the array: 0 2 4 6 8
Write a program in C to find the second smallest element
in an array.
Sample Solution:

C Code:

#include <stdio.h>

void main()
{
int arr1[50],n,i,j=0,sml,sml2nd;

printf("\n\nFind the second smallest element in an array :\n");


printf("--------------------------------------------------\n");

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


scanf("%d", &n);
/* Stored values into the array*/
printf("Input %d elements in the array (value must be <9999) :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/* find location of the smallest element in the array */
sml=arr1[0];
for(i=0;i<n;i++)
{
if(sml>arr1[i])
{
sml=arr1[i];
j = i;
}
}

/* ignore the smallest element and find the 2nd smallest element in the array
*/
sml2nd=99999;
for(i=0;i<n;i++)
{
if(i==j)
{
i++; /* ignoring the smallest element */
i--;
}
else
{
if(sml2nd>arr1[i])
{
sml2nd=arr1[i];
}
}
}

printf("The Second smallest element in the array is : %d \n\n", sml2nd);


}
Elements of odd array:
E

Write a program in C to merge two arrays of same


size sorted in decending order.
Sample Solution:

C Code:

#include <stdio.h>

void main()
{
int arr1[100], arr2[100], arr3[200];
int s1, s2, s3;
int i, j, k;

printf("\n\nMerge two arrays of same size sorted in decending order.\n");


printf("------------------------------------------------------------\n");

printf("Input the number of elements to be stored in the first array :");


scanf("%d",&s1);

printf("Input %d elements in the array :\n",s1);


for(i=0;i<s1;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}

printf("Input the number of elements to be stored in the second array :");


scanf("%d",&s2);

printf("Input %d elements in the array :\n",s2);


for(i=0;i<s2;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr2[i]);
}

/* size of merged array is size of first array and size of second array */
s3 = s1 + s2;
/*----------------- insert in the third array------------------------------------*/
for(i=0;i<s1; i++)
{
arr3[i] = arr1[i];
}
for(j=0;j<s2; j++)
{
arr3[i] = arr2[j];
i++;
}
/*----------------- sort the array in decending order ---------------------------*/
for(i=0;i<s3; i++)
{
for(k=0;k<s3-1;k++)
{

if(arr3[k]<=arr3[k+1])
{
j=arr3[k+1];
arr3[k+1]=arr3[k];
arr3[k]=j;
}
}
}
/*--------------- Prints the merged array ------------------------------------*/
printf("\nThe merged array in decending order is :\n");
for(i=0; i<s3; i++)
{
printf("%d ", arr3[i]);
}
printf("\n\n");
}
ments in the array: 1 3 5 7 9

Write a program in C for addition of two Matrices


of same size.
Sample Solution:

C Code:

#include <stdio.h>

void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;

printf("\n\nAddition of two Matrices :\n");


printf("------------------------------\n");
printf("Input the size of the square matrix (less than 5): ");
scanf("%d", &n);

/* Stored values into the array*/


printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("Input elements in the second matrix :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",brr1[i][j]);
}
/* calculate the sum of the matrix */
for(i=0;i<n;i++)
for(j=0;j<n;j++)
crr1[i][j]=arr1[i][j]+brr1[i][j];
printf("\nThe Addition of two matrix is : \n");
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",crr1[i][j]);
}
printf("\n\n");
}

Write a program in C for subtraction of two


Matrices.
Sample Solution:
C Code:

#include <stdio.h>

void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;

printf("\n\nSubtraction of two Matrices :\n");


printf("------------------------------\n");
printf("Input the size of the square matrix (less than 5): ");
scanf("%d", &n);

/* Stored values into the array*/


printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("Input elements in the second matrix :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",brr1[i][j]);
}
/* calculate the subtraction of the matrix */
for(i=0;i<n;i++)
for(j=0;j<n;j++)
crr1[i][j]=arr1[i][j]-brr1[i][j];
printf("\nThe Subtraction of two matrix is : \n");
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",crr1[i][j]);
}
printf("\n\n");
}

Write a program in C for multiplication of two


square Matrices.
Sample Solution:

C Code:

#include <stdio.h>

void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,k,r1,c1,r2,c2,sum=0;

printf("\n\nMultiplication of two Matrices :\n");


printf("----------------------------------\n");

printf("\nInput the rows and columns of first matrix : ");


scanf("%d %d",&r1,&c1);
printf("\nInput the rows and columns of second matrix : ");
scanf("%d %d",&r2,&c2);
if(c1!=r2){
printf("Mutiplication of Matrix is not possible.");
printf("\nColumn of first matrix and row of second matrix must be same.");
}
else
{
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Input elements in the second matrix :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<r2;i++)
{
printf("\n");
for(j=0;j<c2;j++)
printf("%d\t",brr1[i][j]);
}
//multiplication of matrix
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
crr1[i][j]=0;
for(i=0;i<r1;i++) //row of first matrix
{
for(j=0;j<c2;j++) //column of second matrix
{
sum=0;
for(k=0;k<c1;k++)
sum=sum+arr1[i][k]*brr1[k][j];
crr1[i][j]=sum;
}
}
printf("\nThe multiplication of two matrices is : \n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",crr1[i][j]);
}
}
}
printf("\n\n");
}

Write a program in C to find transpose of a


given matrix.
Sample Solution:

C Code:

#include <stdio.h>

void main()

{
int arr1[50][50],brr1[50][50],i,j,k=0,r,c;

printf("\n\nTranspose of a Matrix :\n");


printf("---------------------------\n");
printf("\nInput the rows and columns of the matrix : ");
scanf("%d %d",&r,&c);

printf("Input elements in the first matrix :\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("\nThe matrix is :\n");


for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf("%d\t",arr1[i][j]);
}

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}

printf("\n\nThe transpose of a matrix is : ");


for(i=0;i<c;i++){
printf("\n");
for(j=0;j<r;j++){
printf("%d\t",brr1[i][j]);
}
}
printf("\n\n");
}
Write a program in C to check whether a given
matrix is an identity matrix.
Sample Solution:

C Code:

#include <stdio.h>
//In a square matrix if all the main diagonal elements are 1's and
//all the remaining elements are 0's is called an Identity Matrix.

void main()
{
int arr1[10][10];
int r1,c1;
int i, j, yn =1;

printf("\n\n Check whether a given matrix is an identity matrix :\n ");


printf("-----------------------------------------------------------\n");

printf("Input number of Rows for the matrix :");


scanf("%d", &r1);
printf("Input number of Columns for the matrix :");
scanf("%d",&c1);
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("The matrix is :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}

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


{
for(j=0; j<c1; j++)
{
if(arr1[i][j] != 1 && arr1[j][i] !=0)
{
yn = 0;
break;
}
}
}

if(yn == 1 )
printf(" The matrix is an identity matrix.\n\n");
else
printf(" The matrix is not an identity matrix.\n\n");
}

Write a program in C to accept two matrices and check


whether they are equal.
Sample Solution:

C Code:

#include <stdio.h>
#include <stdlib.h>

void main()
{
int arr1[50][50], brr1[50][50];
int i, j, r1, c1, r2, c2, flag =1;

printf("\n\nAccept two matrices and check whether


they are equal :\n ");
printf("-------------------------------------------
----------------\n");

printf("Input Rows and Columns of the 1st matrix :");


scanf("%d %d", &r1, &c1);
printf("Input Rows and Columns of the 2nd matrix :");
scanf("%d %d", &r2,&c2);
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Input elements in the second matrix :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("The first matrix is :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}
printf("The second matrix is :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2 ;j++)
printf("% 4d",brr1[i][j]);
printf("\n");
}
/* Comparing two matrices for equality */

if(r1 == r2 && c1 == c2)


{
printf("The Matrices can be compared : \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
if(arr1[i][j] != brr1[i][j])
{
flag = 0;
break;
}
}
}
}
else
{ printf("The Matrices Cannot be compared :\n");
exit(1);
}
if(flag == 1 )
printf("Two matrices are equal.\n\n");
else
printf("But,two matrices are not equal\n\n");
}

Write a program in C to accept a matrix and determine


whether it is a sparse matrix.
Sample Solution:

C Code:

#include <stdio.h>

/*A sparse martix is matrix which has more zero elements


than nonzero elements */
void main ()
{
static int arr1[10][10];
int i,j,r,c;
int ctr=0;
printf("\n\nDetermine whether a matrix is a sparse
matrix :\n");
printf("---------------------------------------------
-------\n");
printf("Input the number of rows of the matrix : ");
scanf("%d", &r);
printf("Input the number of columns of the matrix :
");
scanf("%d", &c);
printf("Input elements in the first matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
if (arr1[i][j]==0)
{
++ctr;
}
}
}
if (ctr>((r*c)/2))
{
printf ("The given matrix is sparse matrix.
\n");
}
else
printf ("The given matrix is not a sparse
matrix.\n");

printf ("There are %d number of zeros in the


matrix.\n\n",ctr);
}
Write a program in C to print or display upper
triangular matrix.
Sample Solution:

C Code:

#include <stdio.h>

void main()
{
int arr1[10][10],i,j,n;
float determinant=0;

printf("\n\nDisplay the upper triangular of a given


matrix :\n");
printf("-------------------------------------------
---\n");

printf("Input the size of the square matrix : ");


scanf("%d", &n);
printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("The matrix is :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}

printf("\nSetting zero in upper triangular matrix\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
if(i>=j)
printf("% 4d",arr1[i][j]);
else
printf("% 4d",0);
}
printf("\n\n");
}
Write a program in C to find sum of right
diagonals of a matrix.
#include <stdio.h>

void main()

{
int i,j,arr1[50][50],sum=0,n;

printf("\n\nFind sum of right diagonals of a matrix


:\n");
printf("---------------------------------------
\n");

printf("Input the size of the square matrix : ");


scanf("%d", &n);
printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
if (i==j) sum= sum+arr1[i][j];
}
}

printf("The matrix is :\n");


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

printf("Addition of the right Diagonal elements is


:%d\n",sum);
}
Write a program in C to find sum of left diagonals
of a matrix.
#include <stdio.h>

void main()

{
int i,j,arr1[50][50],sum=0,n,m=0;

printf("\n\nFind sum of left diagonals of a matrix


:\n");
printf("---------------------------------------
\n");

printf("Input the size of the square matrix : ");


scanf("%d", &n);
m=n;
printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("The matrix is :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}
// calculate the sum of left diagonals
for(i=0;i<n;i++)
{
m=m-1;
for(j=0;j<n ;j++)
{
if (j==m)
{
sum= sum+arr1[i][j];
}

}
}
printf("Addition of the left Diagonal elements is
:%d\n",sum);
}

Write a program in C to find the sum of rows and


columns of a Matrix.
#include <stdio.h>

void main()
{
int i,j,k,arr1[10][10],rsum[10],csum[10],n;

printf("\n\nFind the sum of rows an columns of a


Matrix:\n");
printf("-------------------------------------------
\n");

printf("Input the size of the square matrix : ");


scanf("%d", &n);
printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("The matrix is :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}

/* Sum of rows */
for(i=0;i<n;i++)
{
rsum[i]=0;
for(j=0;j<n;j++)
rsum[i]=rsum[i]+arr1[i][j];
}

/* Sum of Column */
for(i=0;i<n;i++)
{
csum[i]=0;
for(j=0;j<n;j++)
csum[i]=csum[i]+arr1[j][i];
}

printf("The sum or rows and columns of the matrix is


:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("% 4d",arr1[i][j]);
printf("% 8d",rsum[i]);
printf("\n");
}
printf("\n");
for(j=0;j<n;j++)
{
printf("% 4d",csum[j]);
}
printf("\n\n");
}
Write a program in C to calculate determinant of a 3 x 3
matrix.
#include <stdio.h>

void main()
{
int arr1[10][10],i,j,n;
int det=0;

printf("\n\nCalculate the determinant of a 3 x 3


matrix :\n");
printf("-------------------------------------------
------\n");

printf("Input elements in the first matrix :\n");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("The matrix is :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}

for(i=0;i<3;i++)
det = det +
(arr1[0][i]*(arr1[1][(i+1)%3]*arr1[2][(i+2)%3] -
arr1[1][(i+2)%3]*arr1[2][(i+1)%3]));

printf("\nThe Determinant of the matrix is:


%d\n\n",det);
}
Write a program in C to accept two matrices and check
whether they are equal.
#include <stdio.h>
#include <stdlib.h>

void main()
{
int arr1[50][50], brr1[50][50];
int i, j, r1, c1, r2, c2, flag =1;

printf("\n\nAccept two matrices and check whether


they are equal :\n ");
printf("-------------------------------------------
----------------\n");

printf("Input Rows and Columns of the 1st matrix :");


scanf("%d %d", &r1, &c1);

printf("Input Rows and Columns of the 2nd matrix :");


scanf("%d %d", &r2,&c2);
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Input elements in the second matrix :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("The first matrix is :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1 ;j++)
printf("% 4d",arr1[i][j]);
printf("\n");
}
printf("The second matrix is :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2 ;j++)
printf("% 4d",brr1[i][j]);
printf("\n");
}
/* Comparing two matrices for equality */

if(r1 == r2 && c1 == c2)


{
printf("The Matrices can be compared : \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
if(arr1[i][j] != brr1[i][j])
{
flag = 0;
break;
}
}
}
}
else
{ printf("The Matrices Cannot be compared :\n");
exit(1);
}
if(flag == 1 )
printf("Two matrices are equal.\n\n");
else
printf("But,two matrices are not equal\n\n");
}

You might also like