Monday 13 February 2017

triangle of letters in increasing order of lines


Write a Program to print triangle of letters in increasing order of lines.

This type of question usually asked to check looping concept


/*A triangle can be represented using rows and columns.
 *Each next row will contain one extra column of letters.
 */
void print_triangle(unsigned int height, char ch){
        int column=0, row=0;
        for(row=0 ; row < height; row++, printf("\n")){
                for(column=0; column <=row; column++){
                        printf("%c", ch);
                        if(ch == 'Z'){
                                ch = 'a';
                        }else if(ch == 'z'){
                                ch = 'A';
                        }else{
                                ch++;
                        }
                }
        }
}

Full Source Code for this Problem


#include <stdio.h>
#include <stdlib.h>
/*A triangle can be represented using rows and columns.
 *Each next row will contain one extra column of letters.
 */
void print_triangle(unsigned int height, char ch){
        int column=0, row=0;
        for(row=0 ; row < height; row++, printf("\n")){
                for(column=0; column <= row; column++){
                        printf("%c", ch);
                        if(ch == 'Z'){
                                ch = 'a';
                        }else if(ch == 'z'){
                                ch = 'A';
                        }else{
                                ch++;
                        }
                }
        }
}

int main(int argc, char *argv[]){
        if(argc != 2){
                fprintf(stderr, "USAGE: %s <triangle_height>\n", argv[0]);
                return -1;
        }
        int height = atoi(argv[1]);
        print_triangle(height, 'A');
        return 0;
}

Compile and Output


rajesh@ideapad:~/Rajesh/Blog/loop$ gcc triangle.c
rajesh@ideapad:~/Rajesh/Blog/loop$ ./a.out 10
A
BC
DEF
GHIJ
KLMNO
PQRSTU
VWXYZab
cdefghij
klmnopqrs
tuvwxyzABC

No comments:

Post a Comment