programs
programs
programs
Number
Example to find all factors of an integer (entered by the user) using for loop
and if statement.
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.
return 0;
}
Output
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.
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
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.
#include <stdio.h>
int main()
{
int i, num;
return 0;
}
Example
Input
Output
Required knowledge
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.
#include <stdio.h>
int main()
{
int i, n, sum=0;
/*
* Find summation of all numbers
*/
for(i=1; i<=n; i++)
{
sum += i;
}
return 0;
}
Note: sum += i is equivalent to sum = sum + i. You can use any of them depending
on your comfort.
#include <stdio.h>
int main()
{
int i, start, end, sum=0;
/*
* Find summation of all numbers
*/
for(i=start; i<=end; i++)
{
sum += i;
}
return 0;
}
Example
Input
Input rows: 5
Output
*
***
*****
*******
*********
Required knowledge
*
***
*****
*******
*********
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.
#include <stdio.h>
int main()
{
int i, j, n;
printf("\n");
}
return 0;
}
Example
Input
Input N: 5
Output
*****
****
***
**
*
**
***
****
*****
Required knowledge
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.
#include <stdio.h>
int main()
{
int i, j, n;
printf("\n");
}
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
*****
*****
*****
*****
*****
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;
printf("\n");
}
return 0;
}
Input
Input rows: 5
Input columns: 5
Output
01010
01010
01010
01010
01010
Required knowledge
Basic C programming, Loop
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.
#include <stdio.h>
int main()
{
int rows, cols, i, j;
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;
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
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.
#include <stdio.h>
int main()
{
int rows, cols, i, j;
int centerRow, centerCol;
centerRow = (rows+1) / 2;
centerCol = (cols+1) / 2;
printf("\n");
}
return 0;
}
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
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.
#include <stdio.h>
int main()
{
int base, exponent;
long long power = 1;
int i;
return 0;
}
Example
Input
Output
*****
*****
*****
*****
*****
Required knowledge
Basic C programming, For loop
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).
#include <stdio.h>
int main()
{
int i, j, rows;
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
Output
*
**
***
****
*****
Required knowledge
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;
return 0;
}
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
#include <stdio.h>
int main()
{
int i, j, n;
return 0;
}
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
*
***
*****
*******
*********
*******
*****
***
*
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.
#include <stdio.h>
int main()
{
int i, j, n;
printf("Enter N : ");
scanf("%d", &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
Output
Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Required knowledge
Basic C programming, While loop
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.
#include <stdio.h>
int main()
{
int a, b, c, i, terms;
/*
* Input a number from user
*/
printf("Enter number of terms: ");
scanf("%d", &terms);
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);
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
Output
Required knowledge
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.
int main()
{
int num, lastDigit, digits, sum, i, end;
/*
* Input upper limit from user
*/
printf("Enter upper limit: ");
scanf("%d", &end);
/*
* Calculate sum of power of digits
*/
while(num > 0)
{
// Extract the last digit
lastDigit = num % 10;
// Find sum
sum = sum + pow(lastDigit, digits);
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.
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);
/*
* Calculate sum of power of digits
*/
while(num > 0)
{
// Extract the last digit
lastDigit = num % 10;
// Find sum
sum = sum + pow(lastDigit, digits);
return 0;
}
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
Output
Must know –
Program to check divisibility.
Program to find sum of digits.
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.
#include <stdio.h>
int main()
{
int i, j, end, sum;
/*
* 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;
}
}
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.
#include <stdio.h>
int main()
{
int i, j, start, end, sum;
/*
* 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;
}
}
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
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.
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.
#include <stdio.h>
int main()
{
int i, num, sum = 0;
return 0;
}
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 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.
int main()
{
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
printf("\n");
}
printf("\n");
}
return 0;
}
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
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.
#include <stdio.h>
int main()
{
int i, j, N;
int count;
printf("Enter N: ");
scanf("%d", &N);
count = N * 2 - 1;
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
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 }
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 }
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 }
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 }
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
Required knowledge
Array
Must know -
Program to read and print array elements.
Program to check negative numbers.
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.
#include <stdio.h>
int main()
{
int arr[MAX_SIZE]; //Declares an array of MAX_SIZE
int i, n;
return 0;
}
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
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
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].
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int array[MAX_SIZE];
int size;
int i, j, temp;
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
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
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
#include <stdio.h>
int main()
{
int arr[100], freq[100];
int size, i, j, 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
Output
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>
int main()
{
int A[SIZE][SIZE]; // Matrix 1
int B[SIZE][SIZE]; // Matrix 2
int C[SIZE][SIZE]; // Resultant matrix
/*
* 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];
}
}
return 0;
}
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
Output
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
#include <stdio.h>
int main()
{
int arr[MAX_SIZE];
int even[MAX_SIZE], odd[MAX_SIZE];
evenCount = 0;
oddCount = 0;
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
Example
Input
Output
Required knowledge
Basic C programming, For loop, 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];.
4. Finally, after performing shift operation. Copy the new element at its specified position
i.e. arr[pos - 1] = num;.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int i, size, num, pos;
C Code:
#include <stdio.h>
void main()
{
int arr1[50],n,i,j=0,sml,sml2nd;
/* 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];
}
}
}
C Code:
#include <stdio.h>
void main()
{
int arr1[100], arr2[100], arr3[200];
int s1, s2, s3;
int i, j, k;
/* 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
C Code:
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;
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;
C Code:
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],i,j,k=0,r,c;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}
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;
if(yn == 1 )
printf(" The matrix is an identity matrix.\n\n");
else
printf(" The matrix is not an identity matrix.\n\n");
}
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;
C Code:
#include <stdio.h>
C Code:
#include <stdio.h>
void main()
{
int arr1[10][10],i,j,n;
float determinant=0;
void main()
{
int i,j,arr1[50][50],sum=0,n;
void main()
{
int i,j,arr1[50][50],sum=0,n,m=0;
}
}
printf("Addition of the left Diagonal elements is
:%d\n",sum);
}
void main()
{
int i,j,k,arr1[10][10],rsum[10],csum[10],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];
}
void main()
{
int arr1[10][10],i,j,n;
int det=0;
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]));
void main()
{
int arr1[50][50], brr1[50][50];
int i, j, r1, c1, r2, c2, flag =1;