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.
CodePudding user response:
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' );
CodePudding user response:
`#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;
}`
CodePudding user response:
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");
}