C (programming language)

# C program to print square number pattern 3

**Introduction**

This guide will walk you through creating a C program that generates a unique square number pattern, specifically Pattern 3. We’ll explore the logic behind this pattern, break down its code structure, and provide a step-by-step implementation.

**Understanding Pattern 3**

**Shape:**The pattern forms a square, with equal numbers of rows and columns.**Composition:**Numbers are used to construct the square, but their arrangement differs from traditional square patterns.**Sequence:**Each row begins with the number 1 and follows a specific rule for determining subsequent numbers.

**Steps to Implement**

**Include Necessary Header:**

C

`#`**include** <stdio.h>

**Declare Variables:**

C

```
int rows, i, j, num;
```

**Get Input for Number of Rows:**

C

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

**Use Nested Loops to Print the Pattern:**

C

```
for (i = 1; i <= rows; i++) {
num = 1; // Reset num for each row
for (j = 1; j <= i; j++) {
printf("%d ", num);
num = num + sum_of_digits(num); // Calculate next number based on sum of digits
}
printf("\n"); // Move to the next line
}
```

**Define the**`sum_of_digits`

Function (if not already defined):

C

```
int sum_of_digits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
```

**Complete Example Code:**

C

`#`**include** <stdio.h>
int sum_of_digits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
int main() {
int rows, i, j, num;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
num = 1;
for (j = 1; j <= i; j++) {
printf("%d ", num);
num = num + sum_of_digits(num);
}
printf("\n");
}
return 0;
}

**Explanation**

- The
`sum_of_digits`

function calculates the sum of digits of a given number. - The outer
`for`

loop iterates through the rows of the pattern. - The inner
`for`

loop iterates through the columns within a row. `num`

is initially set to 1 for each row.- The next number in the sequence is calculated using
`num + sum_of_digits(num)`

. `printf("\n")`

moves the cursor to the next line after each row.

**Key Points to Remember**

- The
`sum_of_digits`

function is crucial for generating the correct sequence of numbers. - The nested loops control the positioning of numbers within the square pattern.
- Adjust the
`rows`

variable to control the size of the pattern.