Write a C statement that produces a triangle wave with the following description
ID: 3795731 • Letter: W
Question
Write a C statement that produces a triangle wave with the following description:
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 ...... 1 2 3 4 5 6 7 8 ... N-1 N N-1 ....8 7 6 5 4 3 2 1
Assume variable N is declared and initialized, but you don’t know what value it has. You may assume that N is a constant and greater than 1. Once it reaches the Nth triangle, the whole pattern repeats indefinitely, starting over at 1 and going up to N.
You may declare additional variables you need.
Explanation / Answer
// C code
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
int main()
{
int n = 8;
for (int i = 1; i <= n; ++i)
{
int t = i;
for (int j = 1; j <= t; ++j)
{
printf("%d ",j);
}
while(t--)
{
if(t == 0)
break;
printf("%d ",t);
}
printf(" ");
}
}
/*
output:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.