Thursday, November 2, 2023

15.ASCII alphabet value triangle

 I have added numbers to make you understand how we will create this pattern using for loop

  • As we know we first see how many lines of code needs to be printed, in this case it is 9
  • Since we will take user input it can be simply n which will be taken from user
  • As we can see for each line character c is printed
  • The character c is incremented after the inner for loop
  • So each line there is a different character printed
  • For i=1, character printed is 1 a,
  • So j loop that will decide what needs to be printed will iterate from 1 to i
  • Remember to print "\n" to make it move to next line




Code
#include <stdio.h>
#include <conio.h>

void main() {
    int i, j, n;
    clrscr();
    printf("Enter number of lines: ");
    scanf("%d", &n);
    char currentChar = 'a';

    for (i = 1; i <= n; i++) {
        for (j = 1; j <= i; j++) {
            printf("%c", currentChar);
        }
        currentChar++;  // Move to the next character
        printf("\n");
    }

    getch();
}

Note: scanf is used for taking user input