C (programming language)
C program to print following numbers series 1 2 3 6 9 18 27 54 81
Understanding the Number Series
- This number series doesn’t follow a standard mathematical progression like arithmetic or geometric sequences.
- It appears to have a pattern of alternating multiplication and addition operations.
- To generate this series in C, we’ll create a custom logic that replicates this pattern.
Approach to Printing the Series
- Initialize variables:
- Start with the first two numbers (1 and 2) stored in separate variables.
- Use a loop:
- Employ a loop to iterate through the desired number of terms.
- Apply the pattern:
- Inside the loop, perform the following actions:
- Print the current value of the first variable.
- Calculate the next value by multiplying the second variable by 3.
- Print the current value of the second variable.
- Calculate the next value by adding 3 to the first variable.
- Inside the loop, perform the following actions:
- Update variables:
- Assign the newly calculated values to the respective variables for the next iteration.
C Program Implementation
C
#include <stdio.h>
int main() {
int num1 = 1, num2 = 2;
int n = 9; // Number of terms to print
printf("Number Series:\n");
for (int i = 1; i <= n; i++) {
printf("%d ", num1); // Print the current value of num1
num2 = num2 * 3; // Calculate the next value of num2
printf("%d ", num2); // Print the current value of num2
num1 = num1 + 3; // Calculate the next value of num1
}
printf("\n");
return 0;
}
Explanation:
- The variables
num1
andnum2
are initialized with 1 and 2, respectively. - The
for
loop iterates 9 times (to print 9 terms). - Inside the loop:
- The current value of
num1
is printed. num2
is multiplied by 3 to obtain the next value.- The current value of
num2
is printed. num1
is incremented by 3 to obtain the next value.
- The current value of
- The updated values of
num1
andnum2
are used in the next iteration of the loop.
Key Points:
- This approach effectively generates the specified number series using a combination of multiplication and addition operations.
- The code is well-structured and easy to understand.
- You can modify the value of
n
to control the number of terms printed. - Consider adding comments within the code to further enhance readability and maintainability.