Darwin Leonard
Darwin Leonard

Reputation: 9

how to repeat a loop in C

I'm trying to create a program that display the value of days in a week. Monday is 1, Tuesday is 2, Wednesday is 3, ... Sunday is 7. If the user input is 3 then the output will be 1 2 3. If the user input is 10, then the output will be 1 2 3 4 5 6 7 1 2 3.

#include <stdio.h>

int main()
{
    int n;
    scanf("%d", &n);
    for( int i = 1; i <= n; i++)
    {
        if(i > 7)
        {
            continue;
        }
        printf("%d ", i);
    }
 
    return 0;
}

If I input 10, this code will only output 1 2 3 4 5 6 7.

Upvotes: 0

Views: 210

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

Just write

for( int i = 0; i < n; i++ )
{
    printf( "%d ", i % 7 + 1 );
}
putchar( '\n' );

Or it is better to introduce a named constant for the magic number 7 as for example

enum { DAYS_IN_WEEK = 7 };

for( int i = 0; i < n; i++)
{
    printf("%d ", i % DAYS_IN_WEEK + 1 );
}
putchar( '\n' );

Upvotes: 2

Deebika Karuppusamy
Deebika Karuppusamy

Reputation: 16

`#include <stdio.h>

int main()
{
    int n;
    int p=1;
    scanf("%d", &n);
    for( int i = 1; i <= n; i++)
    {
        if(p == 8)
        {
            p = 1;
        }
        printf("%d ", p);
        
        p = p+1;
        
    }
 
    return 0;
}`

Upvotes: 0

0___________
0___________

Reputation: 67476

Use modulo operator or general counter:

void printDays(unsigned day)
{
    while(day)
    {
        for(unsigned wd = 1; day && wd < 8; wd++, day--)
            printf("%u ", wd);
    }
    printf("\n");
}


void printDays1(unsigned day)
{
    for(unsigned d = 0; d < day; d++) printf("%u ", d % 7 + 1);
    printf("\n");
}

https://godbolt.org/z/6W6Gz7G9o

Upvotes: 0

Related Questions