for loop - C program to print numbers between 100 and 1000 which sum of digit is 20 -
i writing c program should display me numbers between 100 , 1000 sum of digit 20. tried code down here, displays 0 ouput when compile it, can me? tried moving if(ivsota==20) outside of while loop. using orwell dev c++ ide.
#include <stdio.h> int main (void) { int ivnos=0; int iostanek=0; int ivsota=1; int istevec1=100; for(istevec1=100; istevec1<1000; istevec1++) { while(istevec1>0) { iostanek=istevec1%100; istevec1=istevec1/10; ivsota=iostanek+ivsota; if(ivsota==20) { printf("%i\n", istevec1); } } } return(0);
i hope better.
this should work you:
(changed variable names it's more readable)
#include <stdio.h> int add_digits(int n) { static int sum = 0; if (n == 0) return 0; sum = n%10 + add_digits(n/10); return sum; } int main() { int start, end; start = 100, end = 1000; for(start = 100; start <= end; start++) { if(add_digits(start) == 20) printf("number: %d\n", start); } return 0; }
edit:
(your code fixed comments explanation)
#include <stdio.h> int main() { int ivnos=0; int iostanek=0; int ivsota=0; int istevec1=100; int temp; //temp needed for(istevec1=100; istevec1<=1000; istevec1++) { temp =istevec1; //assign number temp ivsota=0; //set sum every iteration 0 while(temp>0) { iostanek=temp%10; //you need % 10 last digit of number temp = temp / 10; //'delete' last digit of number ivsota+=iostanek; //add digit sum } if(ivsota==20) //you need check digits after sum calculated printf("number %d\n", istevec1); } return 0; }
Comments
Post a Comment