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

  1. Include Necessary Header:

C

#include <stdio.h>
  1. Declare Variables:

C

int rows, i, j, num;
  1. Get Input for Number of Rows:

C

printf("Enter the number of rows: ");
scanf("%d", &rows);
  1. 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
}
  1. 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

  1. The sum_of_digits function calculates the sum of digits of a given number.
  2. The outer for loop iterates through the rows of the pattern.
  3. The inner for loop iterates through the columns within a row.
  4. num is initially set to 1 for each row.
  5. The next number in the sequence is calculated using num + sum_of_digits(num).
  6. 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.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button