Home > Enterprise >  Print a sequence using a loop in C . 1,2,5,6,9,10,13,14,17,18
Print a sequence using a loop in C . 1,2,5,6,9,10,13,14,17,18

Time:12-04

Please help write a C Program to print this sequence

1,2,5,6,9,10,13,14,17,18 up to 500. I need it for my homework as a student. I tried

#include <iostream>
using namespace std;
int main()
{
    for (int i = 1; i < 454; i  ) {
        if (i = i   1) {
            continue;
        }
    }
    return 0;
}

CodePudding user response:

I guess this is what you were looking for

#include <iostream>

int main()
{
    for (int i = 1; i <= 500; i  ) {
        if (i % 4 == 1 || i % 4 == 2) {
            std::cout << i << ',';
        }
    }
    std::cout << '\n';
}

If the remainder after dividing a number by 4 is 1 or 2 then print the number.

CodePudding user response:

Assuming the sequence is defined as alternating increments of 1 and 3 i.e., 1, 3, 1, 3, 1, ... perhaps you can use a while loop:

#include <iostream>

int main() {
  int i = 0, x = 1;
  while (x <= 500) {
    std::cout << x << '\n';    // Print current value of x.
    x  = i == 1 ? 3 : 1;       // Increment x based on value of i.
    i ^= 1;                    // Toggle i between 1 and 0.
  }
}

Output:

1
2
5
6
9
10
13
14
17
18
21
22
25
26
29
30
33
34
37
38
41
42
45
46
49
50
53
54
57
58
61
62
65
66
69
70
73
74
77
78
81
82
85
86
89
90
93
94
97
98
101
102
105
106
109
110
113
114
117
118
121
122
125
126
129
130
133
134
137
138
141
142
145
146
149
150
153
154
157
158
161
162
165
166
169
170
173
174
177
178
181
182
185
186
189
190
193
194
197
198
201
202
205
206
209
210
213
214
217
218
221
222
225
226
229
230
233
234
237
238
241
242
245
246
249
250
253
254
257
258
261
262
265
266
269
270
273
274
277
278
281
282
285
286
289
290
293
294
297
298
301
302
305
306
309
310
313
314
317
318
321
322
325
326
329
330
333
334
337
338
341
342
345
346
349
350
353
354
357
358
361
362
365
366
369
370
373
374
377
378
381
382
385
386
389
390
393
394
397
398
401
402
405
406
409
410
413
414
417
418
421
422
425
426
429
430
433
434
437
438
441
442
445
446
449
450
453
454
457
458
461
462
465
466
469
470
473
474
477
478
481
482
485
486
489
490
493
494
497
498
  • Related