[c]Nested for loop exercise.

This is a good lesson which trains my logic…

See the lessons here: https://codeforwin.org/2015/07/right-triangle-star-pattern-program-in-c.html

See sample codes:

#include <stdio.h>

int main()
{
    int num,rows,cols;
    printf("Enter the rows:");
    scanf("%d",&num);
    
    for(rows=1;rows<=num;rows++)
    {
        for(cols=1;cols<=rows;cols++)
        {
                printf("%d",cols);
        }
        
        printf("\n");
    }
    return 0;
}

Here is how it looks like when user enters 5:

1
12
123
1234
12345

Algorithm:
1. When row is 1, column is 1, is column less than or equals to 1? Yes, hence 1 is displayed.
2. when row is 2, column goes back to 1, is column less than or equals to 2? Yes, only 1 and 2.
3. when row is 3, column goes back to 1, is column less than or equals to 3? Yes, only 1,2 and 3.
4. when row is 4, column goes back to 1, is column less than or equals to 4? Yes, only 1,2,3,4.
5. when row is 5, column goes back to 1, is column less than or equals to 5? yes all the numbers.

Advertisements
This entry was posted in General stuffs. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s