Quantcast
Channel: Codeforwin

C program to count number of digits in an integer

$
0
0
Write a C program to read an integer from user and count total number of digits the integer contains. How to find total number of digits in a given integer using loop in C programming. Logic to count number of digits in a given integer using C program.

Example:
Input num: 35419
Output digits: 5

Required knowledge

Basic C programming, Loop

Logic to count number of digits in an integer

There are plenty of ways through which you can count the number of digits in a given integer. Here we will be looking two of the methods through which we can find the number of digits in an integer.
First is the easiest method to count number of digits in an integer.
  1. Initialize a variable count to 0.
  2. Increment count by 1 if num > 0 (where num is the number whose digits count is to be found).
  3. Remove the last digit from the number as it isn't needed anymore. Hence divide the number by 10 i.e num = num / 10.
  4. If number is greater than 0 then repeat steps 2-4.


Program to count number of digits in an integer


/**
* C program to count number of digits in an integer
*/

#include <stdio.h>

int main()
{
long long num;
int count = 0;

printf("Enter any number: ");
scanf("%lld", &num);

while(num != 0)
{
count++;
num /= 10; // num = num / 10
}

printf("Total digits: %d", count);

return 0;
}


Now, lets take a look to the second method of finding total number of digits in a given integer using mathematical approach. This method is more simpler and shorter to use. Before using this method you must have a good knowledge of logarithms.


Program to find number of digits in an integer


/**
* C program to count number of digits in an integer
*/

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

int main()
{
long long num;
int count = 0;

printf("Enter any number: ");
scanf("%lld", &num);

count = log10(num) + 1;

printf("Total digits: %d", count);

return 0;
}


Output
Enter any number: 123456789
Total digits: 9


Happy coding ;)



Number pattern 46 in C

$
0
0
Write a C program to print the given number pattern using loop. How to print the given triangular number pattern series using for loop in C programming. Logic to print the given number pattern using C program.

Example:
Input any number: 22464
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

Printing these type of patterns are very simple. Logic to print the pattern is very simple, and is described below.
  1. Print the value of num (where num is the number entered by user).
  2. Trim the last digit of num by dividing it from 10 i.e. num = num / 10.
  3. Repeat step 1-3 till the number is not equal to 0.


Program to print the given number pattern


/**
* C program to print the given number pattern
*/

#include <stdio.h>

int main()
{
int num;

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

while(num != 0)
{
printf("%d\n", num);
num = num / 10;
}

return 0;
}


Output
Enter any number: 12345
12345
1234
123
12
1


Screenshot

Number pattern in C


Happy coding ;)


Number pattern 47 in C

$
0
0
Write a C program to print the given number pattern using loop. How to print the given triangular number pattern series using for loop in C programming. Logic to print the given number pattern using C program.

Example:
Input any number: 24165
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

The given number pattern is similar to the previous number pattern. Also logic of this pattern would be very much similar to the previous pattern.
Before I discuss the logic of this program you must know how to find first digits of any number and how to count digits in a given number. Logic to print the given pattern is.
  1. Print the value of num (where num is the number entered by user).
  2. Remove the first digit of the number, as it isn't needed anymore.
  3. Repeat steps 1-3 till the number is greater than 0.


Program to print the given number pattern


/**
* C program to print the given number pattern
*/

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

int main()
{
int num, firstDigit, digits, placeValue;

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

while(num > 0)
{
printf("%d\n", num);

digits = (int) log10(num); //Gets total number of digits
placeValue = (int) ceil(pow(10, digits)); //Gets the place value of first digit
firstDigit = (int)(num / placeValue); //Gets the first digit

num = num - (placeValue * firstDigit); //Remove the first digit from number
}

return 0;
}


Output
Enter any number: 24165
24165
4165
165
65
5


Screenshot

Number pattern in C


Happy coding ;)


Number pattern 48 in C

$
0
0
Write a C program to print the given triangular number pattern using for loop. How to print the given number pattern series using for loop in C programming. Logic to print the given number pattern in C program.

Example:
Input N:
Output:

Required knowledge

Basic C programming, Loop

Program to print the given number pattern


/**
* C program to print the given number pattern
*/

#include

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

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

for(i=1; i<=N; i++)
{
for(j=i; j<=(i*i); j += i)
{
printf("%-3d", j);
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1
2  4
3  6  9
4  8  12 16
5  10 15 20 25


Screenshot

Number pattern in C


Happy coding ;)


C program to print plus star pattern

$
0
0
Write a C program to print plus star pattern series using for loop. How to print plus star pattern series using loop in C programming. Logic to print plus star pattern in C program.

Example:
Input N: 5


Required knowledge

Basic C programming, If else, Loop

Logic to print plus star pattern

Before you write or think about logic of the pattern. Take a close look about the pattern and identify some noticeable things about it. Here are some.
  1. The pattern consists of N * 2 - 1 rows (where N is the value enter by user).
  2. When you look to the center horizontal plus line i.e. +++++++++ this line. It also consists of N * 2 - 1 columns.
  3. For every other row, single plus symbol gets printed after N - 1 blank spaces, for this case it is 4.
Based on the above observation we can easily code down the solution.

Program to print plus star pattern series


/**
* C program to print the plus star pattern series
*/

#include <stdio.h>

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

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

// Run an outer loop from 1 to N*2-1
for(i=1; i<=(N * 2 - 1); i++)
{
// For the center horizontal plus
if(i == N)
{
for(j=1; j<=(N * 2 - 1); j++)
{
printf("+");
}
}
else
{
// For spaces before single plus sign
for(j=1; j<=N-1; j++)
{
printf("");
}
printf("+");
}

printf("\n");
}

return 0;
}


Output
Enter N: 5

+
+
+
+
+++++++++
+
+
+
+


Snapshot

Plus star pattern in C


Happy coding ;)


C program to print X star pattern

$
0
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 N: 5
Output:

Required knowledge:

Basic C programming, If else, Loop

Logic to print X star pattern

Logic to print the X star pattern can really be complex and confusing if you haven't gone through two previous star pattern programs.
C program to print hollow pyramid star pattern.
C 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--)
{
//Prints trailing spaces
for(j=i; j<N; j++)
{
printf("");
}

//Prints upper hollow triangular part
for(j=1; j<=(2*i-1); j++)
{
if(j==1 || j==(2*i-1))
{
printf("*");
}
else
{
printf("");
}
}

printf("\n");
}

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


Output
Enter N: 5

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


Snapshot

X star pattern in C


Happy coding ;)


Number pattern 50 in C

$
0
0
Write a C program to print the given number pattern series using loop. How to print the given number pattern series using for loop in C programming. Logic to print the given number pattern series using C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print number pattern 1

The above number pattern is a result of combination of two patterns together. Where the two parts individually look as

The above two patterns are explained in one of my previous number pattern post. Please go through the link to get the detailed explanation about these two patterns individually as combination of these two yields the final pattern.

For getting the final resultant pattern we need two separate loop that will print the first and second half of the pattern individually. For print the first upper half of the pattern here goes the logic.
  1. It consists of N rows (where N is the total number of rows to be printed). Hence the loop formation to iterate through rows will be for(i=1; i<=N; i++).
  2. Each row contains exactly i * 2 - 1 columns (where i is the current row number). Loop formation to iterate through each column will be for(j=1; j<=(i * 2 - 1); j++). For each column the current value of j is printed.
Once you coded that, you need to code another loop to print the second lower half of the pattern. Logic to print the other half of the pattern is.
  1. The second half pattern consists of N - 1 rows. Since the pattern goes in descending order hence the loop formation to iterate through rows will also go in descending order for(i=N-1; i>=1; i--).
  2. Here each row exactly contains i * 2 - 1 columns. Hence, the loop formation for iterating over columns is for(j=1; j<=(i * 2 - 1); j++). Inside the inner loop print the value of j.
Lets, write it down in a C program.

Program to print number pattern 1


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

// Iterate through upper half triangle of the pattern
for(i=1; i<=N; i++)
{
for(j=1; j<=(i * 2 - 1); j++)
{
printf("%d", j);
}

printf("\n");
}

// Iterate through lower half triangle of the pattern
for(i=N-1; i>=1; i--)
{
for(j=1; j<=(i * 2 - 1); j++)
{
printf("%d", j);
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1
123
12345
1234567
123456789
1234567
12345
123
1


Screenshot 1

Number pattern in C


Logic to print the number pattern 2

Once you printed the above pattern you can easily print the second number pattern. It is exactly similar to the first pattern we just printed. The only thing we need to add here is the trailing spaces. To print trailing spaces you need the following loop formation for(j=(i * 2); j<(N * 2); j++).

Program to print the given number pattern 1


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

// Iterate through upper half triangle of the pattern
for(i=1; i<=N; i++)
{
// Print trailing spaces
for(j=(i * 2); j<(N * 2); j++)
{
printf("");
}

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

printf("\n");
}

// Iterate through lower half triangle of the pattern
for(i=N-1; i>=1; i--)
{
// Print trailing spaces
for(j=(i * 2); j<(N * 2); j++)
{
printf("");
}

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

printf("\n");
}

return 0;
}


Screenshot

Number pattern in C


Happy coding ;)


Number pattern 49 in C

$
0
0
Write a C program to print the given number pattern using loop. How to print the given number pattern using for loop in C programming. Logic to print the given number pattern using C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern 1

These types of patterns are basically a combination of two or more number patterns. Here if you look carefully then you can easily notice that the given pattern is a combination of two patterns. Hence we can divide the pattern in two parts to make our task easier. Now if you are following my previous posts, you might have noticed that these two patterns are explained in my previous post - Ascending order number pattern and descending order number pattern.
I recommend you to go though these two post before you get into this pattern.

Printing these two parts are really simple. Logic to print the first part.
  1. First upper part of the patter consists of N rows (where N is the total number of rows to be printed). Since the pattern is in ascending order hence the outer loop formation to iterate through rows will also be in ascending order i.e. for(i=1; i<=N; i++).
  2. Here each row contains exactly i columns (where i is the current row number). Inner loop formation to iterate through each columns is for(j=1; j<=i; j++). Print the current value of j inside this loop, to get the first part of the pattern.

Logic to print the second part of the pattern.
  1. Second lower part of the pattern consists of N - 1 rows. Run an outer loop to iterate through rows. Since the pattern is in descending order hence we need to run the loop in descending order. Therefore the outer loop formation will be for(i=N-1; j>=1; i--).
  2. Each row contains exactly i number of columns. Hence the inner loop formation to print columns will be for(j=1; j<=i; j++). To get the desired pattern print the current value of j inside this loop.
Lets, now combine the logic of both the parts in a single program.

Program to print the given number pattern 1


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

// Prints upper part of the pattern
for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
printf("%d", j);
}

printf("\n");
}

// Print lower part of the pattern
for(i=N-1; i>=1; i--)
{
for(j=1; j<=i; j++)
{
printf("%d", j);
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1
12
123
1234
12345
1234
123
12
1


Screenshot

Number pattern in C


Logic to print the given number pattern 2

This pattern is exactly similar to the above pattern we just need to add spaces before the number gets printed. Here I am not getting into detailed explanation about the logic of this pattern. As we only need to add the code to print spaces.

Program to print the given number pattern 2


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

// Prints upper part of the pattern
for(i=1; i<=N; i++)
{
// Prints trailing spaces
for(j=N-1; j>=i; j--)
{
printf("");
}

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

printf("\n");
}

// Prints lower part of the pattern
for(i=N-1; i>=1; i--)
{
// Prints trailing spaces
for(j=i; j<N; j++)
{
printf("");
}

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

printf("\n");
}

return 0;
}


Screenshot 2

Number pattern program in C


If you really love programming, try these interesting pattern of your own, based on the logic of above pattern. You just need to play with the spaces.
And many more...

Happy coding ;)



Triangle number pattern using 0, 1 in C - 1

$
0
0
Write a C program to print the given triangle number pattern using 0, 1. How to print triangle number pattern with 0, 1 using for loop in C programming. Logic to print the given triangular number pattern using 0, 1 in C programming.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, If else, Loop, Even odd logic

Logic to print the given number pattern

To print these type of patterns, the main thing you need to get is the loop formation to iterate over rows and columns. Before I discuss the logic to print the given number pattern. Have a close eye to the pattern. Below is the logic to print the given number pattern.
  1. The pattern consists of total N number of rows (where N is the total number of rows to be printed). Therefore the loop formation to iterate through rows will be for(i=1; i<=N; i++).
  2. Here each row contains exactly i number of columns (where i is the current row number). Hence the inner loop formation to iterate through each columns will be for(j=1; j<=i; j++).
  3. Once you are done with the loop formation to iterate through rows and columns. You need to print the 0's and 1's. Notice that here for each odd columns 1 gets printed and for every even columns 0 gets printed. Hence you need to check a simple condition if(j % 2 == 1) before printing 1s or 0s.
Lets, now code it down.

Program to print the given number pattern


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
// For every odd column print 1
if(j % 2 == 1)
{
printf("1");
}
else
{
printf("0");
}
}

printf("\n");
}

return 0;

}


Output
Enter N: 5
1
10
101
1010
10101


Instead of using if else you can also print the pattern using a simple but tricky method. Below is a tricky approach to print the given number pattern without using if else. Below program uses bitwise operator to check even odd, learn how to check even odd using bitwise operator.



/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
printf("%d", (j & 1));
}

printf("\n");
}

return 0;
}


Screenshot

Triangle number pattern in C


NOTE: You can also get the below pattern with the same logic What you need to do is. Swap the two print() statements. Replace the printf("1"); with printf("0"); and vice versa.


Happy coding ;)


Triangle number pattern using 0, 1 in C - 2

$
0
0
Write a C program to print the given triangle number pattern using 0, 1. How to print the given triangle number pattern with 0, 1 using for loop in C programming. Logic to print the given triangle number pattern with 0, 1 in C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, If else, Loop, Even odd logic

Logic to print the given triangle number pattern

  1. The pattern consists of N rows (where N is the total number of rows to be printed). Hence the outer loop formation to iterate through rows will be for(i=1; i<=N; i++).
  2. Each row contains exactly i number of columns (where i is the current row number) i.e. first row contains 1 column, 2 row contains 2 column and so on.
    Hence the inner loop formation to iterate through columns will be for(j=1; j<=i; j++).
  3. Once you are done with the loop semantics, you just need to print the number. If you notice the numbers are in special order. For each odd rows 1 gets printed and for each even rows 0 gets printed. Now to implement this we need to check a simple condition if(i % 2 == 1) before printing 1s or 0s.
Lets, now implement this in C program.

Program to print given triangle number pattern


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
// Print 1s for every odd rows
if(i % 2 == 1)
{
printf("1");
}
else
{
printf("0");
}
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1
00
111
0000
11111


You can also print this pattern without using if else. Below is a tricky approach to print the given number pattern without using if else. It uses bitwise operator to check even odd.



/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
printf("%d", (i & 1));
}

printf("\n");
}

return 0;
}


Screenshot

Triangle number pattern in c


NOTE: You can also get the below pattern with the same logic What you need to do is. Swap the two print() statements. Replace the printf("1"); with printf("0"); and vice versa.


Happy coding ;)


Triangle number pattern using 0, 1 in C - 3

$
0
0
Write a C program to print the given triangle number pattern using 0, 1. How to print the given triangle number pattern with 0, 1 using for loop in C programming. Logic to print the given triangle number pattern using C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, If else, Loop, Even odd logic

Logic to print the given triangle number pattern

  1. The pattern consists of N rows (where N is the total number of rows to be printed). Hence the outer loop formation to iterate through rows will be for(i=1; i<=N; i++).
  2. Here each row contains exactly i number of columns (where i is the current row number). Loop formation to iterate through columns will be for(j=1; j<=i; j++).

  3. Once you are done with the loop formation. Have a closer look to the pattern. If you view the pattern as you can easily print the final pattern. Where for each odd integers 1 gets printed and for each even integers 0 gets printed. Therefore to get such pattern we need to check a simple condition if(k % 2 == 1) before printing 1s or 0s (where k represents the current integer.
Lets, code down the solution in C program.

Program to print the given triangle number pattern


/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

// k represents the current integer
k = 1;

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
// Print 1 if current integer k is odd
if(k % 2 == 1)
{
printf("1");
}
else
{
printf("0");
}

k++;
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1
01
010
1010
10101


You can also print the given number pattern without using if else. Below is a simple but tricky program to print the same number pattern. It uses bitwise operator to check even odd.



/**
* C program to print the given number pattern
*/

#include <stdio.h>

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

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

// k represents the current integer
k = 1;

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
printf("%d", (k & 1));

k++;
}

printf("\n");
}

return 0;
}


Screenshot

Triangle number pattern in C


NOTE: You can also obtain the reverse of the given pattern You just need to swap the two printf() statements. Means just replace the printf("1"); with printf("0");.


Happy coding ;)


Triangle number pattern using 0,1 in C - 4

$
0
0
Write a C program to print the given triangle number pattern using 0, 1. How to print the given triangle number pattern with 0, 1 using for loop in C programming. Logic to print the given triangle number pattern using C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, If else, Loop

Logic to print the given number pattern

If you are going through my previous number pattern posts, then I hope that logic of this wouldn't be difficult. If still its difficult for you to get the logic. Then, read it below else continue to the program.
  1. The pattern consists of N rows (where N is the number of rows to be printed). Outer loop formation to iterate through the rows will be for(i=1; i<=N; i++).
  2. Each row contains exactly i columns (where i is the current row number). Hence the loop formation to iterate though individual columns will be for(j=1; j<=i; j++).
  3. Now comes the logic to print 0 or 1. You can see that 1 only gets printed for first and last column or first and last row otherwise 0 gets printed. Therefore you must check a condition that if(i==1 || i==N || j==1 || j==i) then print 1 otherwise print 0.


Program to print the given number pattern


/**
* C program to print triangle 0, 1 number pattern
*/

#include <stdio.h>

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

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

for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
if(i==1 || i==N || j==1 || j==i)
{
printf("1");
}
else
{
printf("0");
}
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1
11
101
1001
11111


Screenshot

Number pattern program in C


Happy coding ;)


C program to count frequency of digits in an integer

$
0
0
Write a C program to count frequency of digits in an integer. How to find frequency of digits in a given number using loop in C programming. Logic to find total occurrences of each digits in a given number in C program.

Example:
Input num: 116540
Output:
Frequency of 0 = 1
Frequency of 1 = 2
Frequency of 2 = 0
Frequency of 3 = 0
Frequency of 4 = 1
Frequency of 5 = 1
Frequency of 6 = 1
Frequency of 7 = 0
Frequency of 8 = 0
Frequency of 9 = 0

Required knowledge

Basic C programming, Loop, Array

Logic to find frequency of digits in a number

Before I begin to explain the logic of counting frequency of digits in a given integer. You must have a good understanding of below three concepts -
How to find last digit of any number in C
How to reverse numbers in C
How to store and retrieve elements from an array in C

Here goes the step-by-step detailed explantion about how you gonna find the frequency of digits in an integer.
  1. First of all we need a storage where we can store frequencies of each digits. For that we will be using an integer array of size 10 call it as freq[10]. We have used an array of size 10 because decimal has base 10. There are only 10 digits that makes up any decimal number.
  2. Next, we need to initialize every element of the array with 0. Assuming that every digit has occurred 0 times.

  3. Now comes the main logic. Find the last digit of the given number. For that we need to perform modular division by 10 i.e. lastDigit = num % 10 (where num is the number whose frequency of digits is to be found).
  4. Increment the freq[ lastDigit ]++ by one.
  5. Now remove the last digit from the num as it isn't needed anymore. Perform num = num / 10.
  6. Repeat steps 3-5 till num != 0. Finally you will be left with an array freq having the frequency of each digits in that number.
Lets, now implement this on code.

Program to count frequency of digits in an integer


/**
* C program to count frequency of digits in a given number
*/

#include <stdio.h>
#define BASE 10

int main()
{
long long num, n;
int i, lastDigit;
int freq[BASE];

printf("Enter any number: ");
scanf("%lld", &num);

// Initializes frequency array with 0
for(i=0; i<BASE; i++)
{
freq[i] = 0;
}

n = num; //Copies the value of num to n

while(n != 0)
{
// Gets the last digit
lastDigit = n % 10;

// Increments the frequency array
freq[lastDigit]++;

// Removes the last digit from n
n /= 10;
}

printf("Frequency of each digit in %lld is: \n", num);
for(i=0; i<BASE; i++)
{
printf("Frequency of %d = %d\n", i, freq[i]);
}

return 0;
}


Do not confuse with n /= 10. It is same as n = n / 10.


Output
Enter any number: 11203458760011
Frequency of each digit in 11203458760011 is:
Frequency of 0 = 3
Frequency of 1 = 4
Frequency of 2 = 1
Frequency of 3 = 1
Frequency of 4 = 1
Frequency of 5 = 1
Frequency of 6 = 1
Frequency of 7 = 1
Frequency of 8 = 1
Frequency of 9 = 0

Happy coding ;)


C program to reverse order of words in a string

$
0
0
Write a C program to input any string from user and reverse the order of words. How to reverse the order of words in a given string using C programming. Logic to reverse the order of words in a sentence using C program.

Example:
Input string : I love programming and learning at Codeforwin.
Output string: Codeforwin. at learning and programming love I

Required knowledge

Basic C programming, If else, Loop, String

Logic to reverse the order of words in a given string

There are many logic's to reverse the order of words. Below is the simplest approach I am using to reverse the order.
  1. Read a sentence from user in any variable say in string.
  2. Find a word from the end of string. Learn how to find words in a string.
  3. Append this word to reverseString (where reverseString holds the reverse order of words of the original string).
  4. Repeat step 2-3 till the beginning of string.


Program to reverse the order of words in a given string


/**
* C program to reverse order of words in a string
*/

#include <stdio.h>
#include <string.h>

int main()
{
char string[100], reverse[100];
int len, i, index, wordStart, wordEnd;

printf("Enter any string: ");
gets(string);

len = strlen(string);
index = 0;

// Start checking of words from the end of string
wordStart = len - 1;
wordEnd = len - 1;

while(wordStart > 0)
{
// If a word is found
if(string[wordStart] == '')
{
// Add the word to the reverse string
i = wordStart + 1;
while(i <= wordEnd)
{
reverse[index] = string[i];

i++;
index++;
}
reverse[index++] = '';

wordEnd = wordStart - 1;
}

wordStart--;
}

// Finally add the last word
for(i=0; i<=wordEnd; i++)
{
reverse[index] = string[i];
index++;
}
reverse[index] = '\0'; // Adds a NULL character at the end of string

printf("Original string \n%s\n\n", string);
printf("Reverse ordered words \n%s", reverse);


return 0;
}


Output
Enter any string: I love programming and learning at Codeforwin.
Original string
I love programming and learning at Codeforwin.

Reverse ordered words
Codeforwin. at learning and programming love I

Happy coding ;)


Square number pattern 2 in C

$
0
0
Write a C program to print the given square number pattern using loop. How to print the given square number pattern of n rows using for loop in C programming. Logic to print the given number pattern in C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given square number pattern

Before you learn the logic of the given pattern, you must first learn some basic number pattern.

Now, once you get acquainted with the basic number patterns. Give a close look to the given number pattern. On first look the pattern may seem difficult to print. To make things easier lets divide the pattern into similar patterns.
Now logic to print these two patterns separately is comparatively easier. These two patterns are also discussed separately my previous posts - Pattern part 1 - Pattern part 2.

Logic to print both of these pattern as a whole:
  1. The pattern consists of N rows (where N is the number of rows to be printed). Hence the outer loop formation is for(i=1; i<=N; i++).
  2. To print the first part of the pattern run an inner loop from i to N (where i is the current row number). Hence the loop formation will be for(j=i; j<=N; j++). Inside this loop print the current value j.
  3. To print the second part of the pattern. Initialize a variable k = j - 2. After that run another inner loop from 1 to i-1. Loop formation for this will be for(j=1; j<i; j++, k--). Inside this loop print the current value of k.
And you are done. Lets now, code it down.

Program to print the given square number pattern


/**
* C program to print given number pattern
*/

#include <stdio.h>

int main()
{
int i, j, N;
int k = 1;

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

for(i=1; i<=N; i++)
{
// Prints first part of the pattern
for(j=i; j<=N; j++)
{
printf("%d ", j);
}

// Prints second part of the pattern
k = j - 2;
for(j=1; j<i; j++, k--)
{
printf("%d ", k);
}

printf("\n");
}

return 0;
}


Output
Enter N: 5
1 2 3 4 5
2 3 4 5 4
3 4 5 4 3
4 5 4 3 2
5 4 3 2 1


Screenshot

Square number pattern in C


Happy coding ;)



Hollow square number pattern 1 in C

$
0
0
Write a C program to print the given number pattern using for loop. How to print the given hollow square number pattern using loop in C programming. Logic to print the given number pattern using loop in C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

Before you continue to this pattern, I recommend you to learn some basic number pattern. As it will help you grasp the logic quicker.

Once you get familiar with some basic number patterns. Lets learn logic to print the given pattern. If you are following my previous posts then you might have noticed that this pattern is almost similar to the previous number pattern. I recommend you to go through the previous number pattern before you move on to this pattern. As logic of this pattern is same as previous pattern.

There can be many logic to print the given pattern. Here I am discussing the easiest way to print the given pattern. First to make things easier lets divide the pattern in two parts.

Logic to print the given number pattern is:
  1. The pattern consists of N rows (where N is the number of rows to be printed). Hence the outer loop formation is for(i=1; i<=N; i++).
  2. To print the first part of the pattern run an inner loop from i to N (where i is the current row number). Hence the loop formation will be for(j=i; j<=N; j++). Inside this loop print the current value j.
  3. To print the second part of the pattern. Initialize a variable k = j - 2. After that run another inner loop from 1 to i-1. Loop formation for this will be for(j=1; j<i; j++, k--). Inside this loop print the current value of k.
  4. NOTE: Numbers only gets printed for first and last row or column otherwise spaces gets printed.
Lets not implement this on code.

Program to print hollow square number pattern


/**
* C program to print given number pattern
*/

#include <stdio.h>

int main()
{
int i, j, N;
int k = 1;

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

for(i=1; i<=N; i++)
{
// Prints first part of the pattern
for(j=i; j<=N; j++)
{
if(i==1 || i==N || j==i)
printf("%d", j);
else
printf("");
}

// Prints second part of the pattern
k = j - 2;
for(j=1; j<i; j++, k--)
{
if(i==1 || i==N || j==i-1)
printf("%d", k);
else
printf("");
}

printf("\n");
}

return 0;
}


Output
Enter N: 5

12345
2 4
3 3
4 2
54321


Screenshot

C program to print hollow square number pattern


Happy coding ;)


C program to print X number pattern

$
0
0
Write a C program to print the given X number pattern series using for loop. How to print the given X number pattern series using for loop in C programming. Logic to print the given X number pattern using loop.

Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print X number pattern

Before you move on to this number pattern I highly recommend you to practice some basic number patterns.

If you are a lover of Codeforwin. You might have already noticed that the logic to print the pattern is exactly similar to the X star pattern.

Lets move on to the logic to print the given pattern. To make things little easier divide the pattern in two parts.

We will print both of these parts separately. We will use separate outer for loops for both the parts. Logic to print the first part of the pattern.
  1. The pattern consists of total N rows (where N is the total number of rows * 2 - 1). Hence the first outer loop formation to iterate through rows will be for(i=1; i<=N; i++)
  2. Now notice each row in the first part of the pattern. First spaces gets printed then an integer then some more spaces finally the integer. Hence we will use two inner loops to print spaces. You can hover on the above pattern to count the total number of spaces gets printed.
  3. Notice the trailing spaces in the first part of pattern. You might have noticed that for each row total number of trailing spaces is i - 1 (Where i is the current row number). Hence to iterate through the trailing spaces the loop formation will be for(j=1; j<i; j++). Inside this loop print a single space.
  4. After printing the trailing space an integer which is the current row number gets printed. Hence print the current value of i.
  5. Now the center spaces. Center spaces are arranged in tricky fashion. Each row contains exactly (N - i) * 2 - 1 spaces. Hence the second inner loop formation to iterate through spaces is for(j=1; j<= (N - i) * 2 - 1; j++). Inside this loop print single spaces.
  6. After the above loop print the value of i.


You are done with the first part of the pattern. Lets now see the logic to print the second part of the pattern. For printing second part we will use another outer loop.
  1. The second part of the pattern consists of N - 1 rows. Hence the outer loop formation to iterate through rows is for(i=N-1; i>=1; i--). Now, I have used a descending order loop, since the numbers printed are in descending order.
  2. Like first part of the pattern. Here also first trailing spaces gets printed then an integer then the central spaces and finally the same integer gets printed.
  3. Have a close look to the trailing spaces. Each row contains exactly i - 1 spaces i.e. the first row contains 4 - 1 => 3 spaces, second contains 3 - 1 => 2 spaces and so on. Hence the first inner loop formation will be for(j=1; j<i; j++). Inside this loop print the single space.
  4. After printing tailing spaces print the current value of i.
  5. Now notice the central spaces carefully. Each row contains exactly (N - i) * 2 - 1 central spaces. Hence the loop formation for central spaces will be for(j=1; j<=((N - i) * 2 - 1); j++). Inside this loop print single space.
  6. Again after central loop print the current value of i.
Finally you are done with the logic section. Embed the logic of each part of the pattern in a program. Below is the program to print the given pattern as a whole.

Program to print X number pattern


/**
* C program to print X number pattern
*/

#include <stdio.h>

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

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

//First part of the pattern
for(i=1; i<=N; i++)
{
//Prints trailing spaces
for(j=1; j<i; j++)
{
printf("");
}

printf("%d", i);

//Prints central spacces
for(j=1; j<=((N - i) * 2 - 1); j++)
{
printf("");
}

//Don't print for last row
if(i != N)
printf("%d", i);

//Moves on to the next row
printf("\n");
}

//Second part of the pattern
for(i=N-1; i>=1; i--)
{
//Prints trailing spaces
for(j=1; j<i; j++)
{
printf("");
}

printf("%d", i);

//Prints central spaces
for(j=1; j<=((N - i ) * 2 - 1); j++)
{
printf("");
}

printf("%d", i);

//Moves on to the next line
printf("\n");
}

return 0;
}


Output
Enter N: 5
1       1
2 2
3 3
4 4
5
4 4
3 3
2 2
1 1


Screenshot

C program to print X number pattern


Happy coding ;)


Half diamond number pattern program in C - 3

$
0
0
Write a C program to print the given half diamond number pattern series using loop. How to print the given number pattern series using for loop in C programming. Logic to print the given half diamond number pattern series using for loop.

Example:
Input N: 5


Required knowledge

Basic C programming, Loop

Logic to print the given half diamond number pattern

Getting the logic of this number pattern may seem difficult. Therefore, I recommend you to go through some of my previous posts to learn some basic number patterns. Once you get familiar with some of the number pattern read below to get the logic of given half diamond number pattern. Without wasting time let's get on to the logic to print the pattern. To make things easier let's divide the given half diamond shape in half. Where the upper and lower part is shown below.

If you are a lover of Codeforwin, then you have noticed that I have already explained the first upper half of the pattern here. If you haven't gone through, read the logic to print both of the pattern below.

First of all to get the resultant pattern, we need to print both the parts separately in two separate outer loop. Let's first learn the logic to print the first upper part of the pattern.
  1. The given pattern consists of total N rows. Hence the outer loop formation to iterate through rows will be for(i=0; i<=N; i++).
  2. Now, when you look carefully at the series in which each row gets printed. You will find that it contains two series. We will print these two pattern in two separate inner loops. These patterns are also explained separately in my two earlier posts
    1. The first part contains total i number of columns (where i is the current row number). Hence the first inner loop formation will be for(j=1; j<=i; j++). Inside this loop print the current value of j.
    2. The second part contains total i-1 number of columns each row. Hence the second inner loop formation will be for(j=i; j>=1; j--). Inside this loop print the current value of j.
    And you are done with the first upper half of the half diamond number pattern.


Moving on to the second lower half pattern. Logic to print the given second lower half pattern is explained below.
  1. The given pattern consists of total N - 1 number of rows. Hence the outer loop formation to iterate through rows will be for(i=N-1; i>=1; i--). I have used a decreasing order loop as the pattern is in decreasing order.
  2. Now, as the upper part of the pattern. This can also be divided again in two parts. We need two separate inner loops to print these.
    1. The first part contains total i columns (where i is the current row number). Hence the first inner loop formation will be for(j=1; j&lt=i; j++). Inside this loop print the current value of j. This part is also explained separately in my previous post.
    2. The second part contains total i - 1 columns. Hence the second inner loop formation will be for(j=i; j>=i; j--). Inside this loop print the current value of j. This pattern is also explained in detail in my previous number pattern post.
And we are done with the logic section. We need to combine all that in single program.

Program to print the given half diamond number pattern


/**
* C program to print half diamond number pattern series
*/

#include <stdio.h>

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

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

// Print the first upper half
for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
printf("%d", j);
}
for(j=i-1; j>=1; j--)
{
printf("%d", j);
}

printf("\n");
}

// Print the lower half of the pattern
for(i=N-1; i>=1; i--)
{
for(j=1; j<=i; j++)
{
printf("%d", j);
}
for(j=i-1; j>=1; j--)
{
printf("%d", j);
}

printf("\n");
}

return 0;
}


Output
Enter rows: 5
1
121
12321
1234321
123454321
1234321
12321
121
1


Screenshot of half diamond number pattern

half diamond number pattern in C

Happy coding ;)


Half diamond number pattern with star border program in C - 1

$
0
0
Write a C program to print the given half diamond star number pattern series using for loop. How to print the given half diamond star number pattern series using loop in C programming. Logic to print the given star number pattern series using for loop.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given half diamond number pattern with star border

Let's first remove the border of the given pattern. After removing border the pattern look like. I have already explained the logic to print the above pattern in detail in my previous post. I highly recommend you to go through the pattern before moving on to this. As this entire pattern is fully based on my previous number pattern.

Now, once you got the logic of half diamond number pattern without star border. Let's move on to the pattern with star border. Here in this pattern we only need to add the logic to print borders. Printing star (*) as border is simple. We only need to add an extra printf("*"); statement before and/or after every loop as needed.

Program to print the given half diamond number pattern with star border


/**
* C program to print the half diamond number pattern with star border
*/

#include <stdio.h>

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

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

printf("*\n");
// Print the first upper half
for(i=1; i<=N; i++)
{
printf("*");
for(j=1; j<=i; j++)
{
printf("%d", j);
}

for(j=i-1; j>=1; j--)
{
printf("%d", j);
}
printf("*");

printf("\n");
}

// Print the lower half of the pattern
for(i=N-1; i>=1; i--)
{
printf("*");
for(j=1; j<=i; j++)
{
printf("%d", j);
}

for(j=i-1; j>=1; j--)
{
printf("%d", j);
}
printf("*");

printf("\n");
}
printf("*");

return 0;
}
Output
Enter rows: 5
*
*1*
*121*
*12321*
*1234321*
*123454321*
*1234321*
*12321*
*121*
*1*
*


Screenshot to print half diamond number pattern series with star border

C program to print half diamond number pattern with star border


Happy coding ;)


C program to demonstrate the use of pointers

$
0
0
Previous ExerciseNext Program

Write a C program to create, initialize and demonstrate the use of a pointer variable. How to access values and addresses using a pointer variable in C programming.

Required knowledge

Basic C programming, Pointers

Basic of pointers

C programming is extremely powerful at low level. Pointer is one of its tool that provide such low level memory handling. Data in memory is organized as a sequence of bytes. Where each byte is accessed through its unique address. These addresses ranges from zero (0) to some positive integer. Pointers in C programming provides an efficient way to handle the low level memory activities.

Like other variables, pointers also allows to declare variables of pointer types. Now, what does that mean? Like other variables we can declare a pointer variable. But what type of data does pointer variable contains? Unlike other variables pointer holds memory address of some other variable. We will later see the use of these memory addresses and how pointers are a magic wand to the C programmers. Let us now get familiar with some pointer concepts.

Reading memory address of any variable

We know that each and every declared variable has a name, memory location and value. Name is the identifier name which we give during declaration of the variable. Values are the constants that the variable contains. For example - int num = 10;num is the variable name and 10 is the value stored in that variable. But what about the memory address?

In C programming the unary & (Address of) operator is used to get memory address of any variable. Address of operator when prefixed with any variable returns the actual memory address of that variable. Let us see a program to get actual memory address of variables.

Program to get memory address using address of operator


/**
* C program to get memory address using address of operator
*/

#include <stdio.h>

int main()
{
/* Simple declarations */
char character = 'C';
int integer = 1;
float real = 10.4f;
long long biginteger = 989898989ll;

/* Print variable value with their memory address */
printf("Value of character = %c, Address of character = %u\n", character, &character);
printf("Value of integer = %d, Address of integer = %u\n", integer, &integer);
printf("Value of real = %f, Address of real = %u\n", real, &real);
printf("Value of biginteger = %lld, Address of biginteger = %u", biginteger, &biginteger);

return 0;
}
NOTE The above program will produce different result on different systems. Also you can use any other format specifier other than %u to print memory addresses. You can use any format specifier that prints an integer. Try using %x %d %i %ld etc.
Output

Value of character = C, Address of character = 6356751
Value of integer = 1, Address of integer = 6356744
Value of real = 10.400000, Address of real = 6356740
Value of biginteger = 989898989, Address of biginteger = 6356728

Creating, initializing and using pointer variables

Pointers can handle many low level memory operations (including dynamic memory allocation). But before we get in deep of pointers let us first learn to declare a pointer variable. Like other variable declarations pointer also follow the same syntax -

Syntax to declare pointer variable

<data-type> * <variable-name>

Example of pointer declaration


int * integer_pointer;
float * float_ptr
char * charPtr;
long * lptr;

Program to create, initialize and use pointer variable


/**
* C program to create, initialize and use pointers
*/

#include <stdio.h>

int main()
{
int num = 10;
int * ptr;

/* Stores the address of num to pointer type */
ptr = &num;

printf("Address of num = %d\n", &num);
printf("Value of num = %d\n", num);

printf("Address of ptr = %d\n", &ptr);
printf("Value of ptr = %d\n", ptr);
printf("Value pointed by ptr = %d\n", *ptr);

return 0;
}
Output

Address of num = 6356748.
Value of num = 10
Address of ptr = 6356744
Value of ptr = 6356748
Value pointed by ptr = 10

Happy coding ;)

Recommended post

Previous ExerciseNext Program

C program to add two numbers using pointers

$
0
0
Previous ProgramNext Program

Write a C program to read two numbers from user and add them using pointers. How to find sum of two number using pointers in C programming. Program to perform arithmetic operations on number using pointers.

Example

Input


Input num1: 10
Input num2: 20

Output


Sum = 30
Difference = -10
Product = 200
Quotient = 0

Required knowledge

Basic C programming, Pointers

Since the first days of writing programs in C. We have performed arithmetic operations so many times. In case you want a quick recap check out these links without pointers -

In previous post I explained how to store address of a variable in pointer variable. Let us now learn to work with the value stored in the pointer variable.

There are two common operators used with pointers -

  1. & (Address of) operator - When prefixed with any variable returns the actual memory address of that variable.
  2. * (Dereference) operator - When prefixed with any pointer variable it evaluates to the value stored at the address of a pointer variable.

Program to add two numbers using pointers


/**
* C program to add two number using pointers
*/

#include <stdio.h>

int main()
{
int num1, num2, sum;
int *ptr1, *ptr2;

ptr1 = &num1; // ptr1 stores the address of num1
ptr2 = &num2; // ptr2 stores the address of num2

printf("Enter any two numbers: ");
scanf("%d%d", ptr1, ptr2);

sum = *ptr1 + *ptr2;

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

return 0;
}

You have noticed that, I haven't used any & (address of) operator in the scanf() function. scanf() takes the actual memory address where the user input is to be stored. The pointer variable ptr1 and ptr2 contains the actual memory addresses of num1 and num2. Therefore we need not to prefix the & operator in scanf() function in case of pointers.

Now using this, it should be an easy workaround to compute all arithmetic operations using pointers. Let us write another program that performs all arithmetic operations using pointers.

Program to perform all arithmetic operations using pointers


/**
* C program to perform all arithmetic operations using pointers
*/

#include <stdio.h>

int main()
{
float num1, num2; // Normal variables
float *ptr1, *ptr2; // Pointer variables

float sum, diff, mult, div;

ptr1 = &num1; // ptr1 stores the address of num1
ptr2 = &num2; // ptr2 stores the address of num2

/* User input through pointer */
printf("Enter any two real numbers: ");
scanf("%f%f", ptr1, ptr2);

/* Perform arithmetic operation */
sum = (*ptr1) + (*ptr2);
diff = (*ptr1) - (*ptr2);
mult = (*ptr1) * (*ptr2);
div = (*ptr1) / (*ptr2);

/* Print the results */
printf("Sum = %.2f\n", sum);
printf("Difference = %.2f\n", diff);
printf("Product = %.2f\n", mult);
printf("Quotient = %.2f\n", div);

return 0;
}
Note Always use proper spaces and separators between two different programming elements. As *ptr1 /*ptr2 will generate a compile time error. Find out why?
Output

Enter any two real numbers: 20
5
Sum = 25.00
Difference = 15.00
Product = 100.00
Quotient = 4.00

Happy coding ;)

Recommended posts

Previous ProgramNext Program

C program to swap two numbers using call by reference

$
0
0
Previous ProgramNext Program

Write a C program to swap two numbers using pointers and functions. How to swap two numbers using call by reference method. Logic to swap two number using pointers in C program.

Example

Input


Input num1: 10
Input num2: 20

Output after swapping


Num1 = 20
Num2 = 10

Required knowledge

Basic C programming, Functions, Pointers

Logic to swap two numbers using call by reference

Swapping two numbers is simple and a fundamental thing. You need not to know any rocket science for swapping two numbers. Simple swapping can be achieved in three steps -

  1. Copy the value of first number say num1 to some temporary variable say temp.
  2. Copy the value of second number say num2 to the first number. Which is num1 = num2.
  3. Copy back the value of first number stored in temp to second number. Which is num2 = temp.

Let us implement this logic using call by reference concept in functions.

Program to swap two numbers using call by reference


/**
* C program to swap two number using call by reference
*/

#include <stdio.h>

/* Swap function declaration */
void swap(int * num1, int * num2);

int main()
{
int num1, num2;

/* Input numbers */
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);

/* Print original values of num1 and num2 */
printf("Before swapping in main \n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);

/* Pass the addresses of num1 and num2 */
swap(&num1, &num2);

/* Print the swapped values of num1 and num2 */
printf("After swapping in main \n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);

return 0;
}


/**
* Function to swap two numbers
*/
void swap(int * num1, int * num2)
{
int temp;

// Copy the value of num1 to some temp variable
temp = *num1;

// Copy the value of num2 to num1
*num1= *num2;

// Copy the value of num1 stored in temp to num2
*num2= temp;

printf("After swapping in swap function \n");
printf("Value of num1 = %d \n", *num1);
printf("Value of num2 = %d \n\n", *num2);
}

Before moving on to other post, learn more ways to play with swapping numbers.

Output

Enter two numbers: 10 20
Before swapping in main
Value of num1 = 10
Value of num2 = 20

After swapping in swap function
Value of num1 = 20
Value of num2 = 10

After swapping in main
Value of num1 = 20
Value of num2 = 10

Happy coding ;)

Recommended posts

Previous ProgramNext Program

C program to print 8 star pattern

$
0
0

Write a C program to print 8 star pattern series using loop. How to print 8 star pattern series using for loop in C programming. Logic to print 8 star pattern series of N columns in C program.

Example

Input

Input N: 5

Output

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

Required knowledge

Basic C programming, If else, Loop

Must have programming knowledge for this program.

Logic to print 8 star pattern

To simply things for beginners I have divided entire logic in three main sub tasks.

  • Print a hollow square star pattern with N columns and (N*2) - 1 rows.
  • Modify above hollow square pattern logic. Instead of star(*), print space at top and bottom corners and in the center intersection edge.
  • Finally modify hollow square logic to print star instead of space for Nth row.

Below is the step by step descriptive logic to print 8 star pattern.

  1. Read number of columns to print from user. Store it in some variable say N.
  2. Iterate through (N*2)-1 rows. Run an outer loop with structure for(i=1; i<N*2; i++).
  3. Iterate through N columns. Run an inner loop with structure for(j=1; j<=N; j++).
  4. Inside inner loop first check conditions for corner and center intersection spaces. Print space for
    1st row and 1st or Nth column = if(i==1 && (j==1 || j==N))
    Nth row and 1st or Nth column = if(i==N && (j==1 || j==N))
    N*2-1 row and 1st or Nth column = if(i==N*2-1 && (j==1 || j==N))
  5. Print stars for
    1st row or 1st column = if(i==1 || j==1)
    Nth row or Nth column = if(i==N || j==N)
    N*2-1th row = if(i==N*2-1)
  6. Otherwise print spaces if above conditions does not matches.

Program to print 8 star pattern


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

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

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

for(i=1; i<size*2; i++)
{
for(j=1; j<=size; j++)
{
// Condition for corner and center intersection space
if((i==1 && (j==1 || j==size)) || (i==size && (j==1 || j==size)) || (i==size*2-1 && (j==1 || j==size)))
printf("");
else if(i==1 || i==size || i==(size*2)-1 || j==1 || j==size)
printf("*");
else
printf("");
}

printf("\n");
}

return 0;
}
Output

Enter size: 6
****
* *
* *
* *
* *
****
* *
* *
* *
* *
****

Screenshot

Program to print 8 star pattern

Happy coding ;)

Recommended posts

C program to left rotate an array

$
0
0

Write a C program to left rotate an array by n position. Logic to rotate an array to left by n position in C program.

Example

Input

Input 10 elements in array: 1 2 3 4 5 6 7 8 9 10
Input number of times to rotate: 3

Output


Array after left rotation: 4 5 6 7 8 9 10 1 2 3

Required knowledge

Basic C programming, Loop, Array, Function

Logic to left rotate an array

Below is the step by step descriptive logic to left rotate an array.

  1. Read elements in an array say arr.
  2. Read number of times to rotate in some variable say N.
  3. Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last.

Algorithm to left rotate an array
Begin:
read(arr)
read(n)
Fori←1 to ndo
rotateArrayByOne(arr)
End for
End
rotateArrayByOne(arr[], SIZE)
Begin:
firstarr[0]
Fori←1 to SIZE - 1do
arr[i] ← arr[i + 1]
End for
arr[SIZE - 1] ← first
End

Program to left rotate an array


/**
* C program to left rotate an array
*/

#include <stdio.h>
#define SIZE 10 /* Size of the array */

void printArray(int arr[]);
void rotateByOne(int arr[]);


int main()
{
int i, N;
int arr[SIZE];

printf("Enter 10 elements array: ");
for(i=0; i<SIZE; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter number of times to left rotate: ");
scanf("%d", &N);

/* Actual rotation */
N = N % SIZE;

/* Print array before rotation */
printf("Array before rotation\n");
printArray(arr);

/* Rotate array n times */
for(i=1; i<=N; i++)
{
rotateByOne(arr);
}

/* Print array after rotation */
printf("\n\nArray after rotation\n");
printArray(arr);

return 0;
}


void rotateByOne(int arr[])
{
int i, first;

/* Store first element of array */
first = arr[0];

for(i=0; i<SIZE-1; i++)
{
/* Move each array element to its left */
arr[i] = arr[i + 1];
}

/* Copies the first element of array to last */
arr[SIZE-1] = first;
}


/**
* Print the given array
*/
void printArray(int arr[])
{
int i;

for(i=0; i<SIZE; i++)
{
printf("%d ", arr[i]);
}
}
Output

Enter 10 elements array: 1 2 3 4 5 6 7 8 9 10
Enter number of times to left rotate: 3
Array before rotation
1 2 3 4 5 6 7 8 9 10

Array after rotation
4 5 6 7 8 9 10 1 2 3

Happy coding ;)

Recommended posts

C program to right rotate an array

$
0
0

Write a C program to right rotate an array by n position. Logic to rotate an array to right by n position in C program.

Example

Input

Input 10 elements in array: 1 2 3 4 5 6 7 8 9 10
Input number of times to rotate: 3

Output

Array after right rotation: 8 9 10 1 2 3 4 5 6 7

Required knowledge

Basic C programming, Loop, Array, Function

Logic to right rotate an array

Below is the step by step descriptive logic to rotate an array to right by n positions.

  1. Read elements in an array say arr.
  2. Read number of times to rotate in some variable say N.
  3. Right rotate the given array by 1 for N times. In real right rotation is shifting of array elements to one position right and copying last element to first.
Algorithm to right rotate an array
Begin:
read(arr)
read(n)
Fori←1 to ndo
rotateArrayByOne(arr)
End for
End
rotateArrayByOne(arr[], SIZE)
Begin:
lastarr[SIZE - 1]
ForiSIZE-1 to 0 do
arr[i] ← arr[i - 1]
End for
arr[0] ← last
End

Program to right rotate an array


/**
* C program to right rotate an array
*/

#include <stdio.h>
#define SIZE 10 /* Size of the array */

void printArray(int arr[]);
void rotateByOne(int arr[]);


int main()
{
int i, N;
int arr[SIZE];

printf("Enter 10 elements array: ");
for(i=0; i<SIZE; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter number of times to right rotate: ");
scanf("%d", &N);

/* Actual rotation */
N = N % SIZE;

/* Print array before rotation */
printf("Array before rotation\n");
printArray(arr);

/* Rotate array n times */
for(i=1; i<=N; i++)
{
rotateByOne(arr);
}

/* Print array after rotation */
printf("\n\nArray after rotation\n");
printArray(arr);

return 0;
}


void rotateByOne(int arr[])
{
int i, last;

/* Store last element of array */
last = arr[SIZE - 1];

for(i=SIZE-1; i>0; i--)
{
/* Move each array element to its right */
arr[i] = arr[i - 1];
}

/* Copy last element of array to first */
arr[0] = last;
}


/**
* Print the given array
*/
void printArray(int arr[])
{
int i;

for(i=0; i<SIZE; i++)
{
printf("%d ", arr[i]);
}
}
Output

Enter 10 elements array: 1 2 3 4 5 6 7 8 9 10
Enter number of times to right rotate: 3
Array before rotation
1 2 3 4 5 6 7 8 9 10

Array after rotation
8 9 10 1 2 3 4 5 6 7

Happy coding ;)

Recommended posts