'My C code. How to prevent numbers in columns to repeat? [closed]
Hi, I have a question. I want to print a list of odd numbers from 1 to 99 in 2 columns using C, but as you can see in the image, the numbers are repeating. I want the numbers to follow the sequence. Like: 1-3-5-7etc..., not 1-3-3-5-5-7... Hope someone can help me, thank you.
#include<stdio.h>
int main(){
int sum=0,i=1,k=0;
printf("List of odd numbers:\n");
while(i<99){
k=i;
i=i+2;
printf("%d\t%d\n",k,i);
}
for(i=1;i<=99;i++){
if(i%2!=0)
sum+=i;
}
printf("Sum is: %d",sum);
return 0;
}
Solution 1:[1]
Print your current number and the next number (+2). Afterwards, increment the current number by two positions (+4).
#include <stdio.h>
int main(void) {
for (unsigned i = 1; i < 99; i += 4)
printf("%d\t%d\n", i, i + 2);
}
stdout
:
1 3
5 7
9 11
13 15
17 19
21 23
25 27
29 31
33 35
37 39
41 43
45 47
49 51
53 55
57 59
61 63
65 67
69 71
73 75
77 79
81 83
85 87
89 91
93 95
97 99
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oka |