Quantcast
Channel: Codeforwin
Viewing all 132 articles
Browse latest View live

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

Viewing all 132 articles
Browse latest View live