Answer the question
In order to leave comments, you need to log in
(C) How to make a function return a string from a loop?
I recently started learning C (I work in VisualStudio 13)
How can I fix the loop so that it writes intermediate values to a string and the function returns the finished string (or ...?). Perhaps there is a better solution to the problem.
I type 841 into the console, it returns:
>Sum = 13 // OK
I want it to return:
>Sum = 8 + 4 + 1 = 13
#include <stdio.h>
#include <stdlib.h>
unsigned Sum(unsigned n); // Functions' prototype
void main() {
unsigned n;
printf_s("Please, print --> ");
scanf_s("%u", &n);
printf_s("Sum=%u\n", Sum(n));
system("pause");
}
unsigned Sum(unsigned n) {
unsigned s = 0; // iteration(s)
while (n > 0) {
s+= n % 10;
n /= 10;
}
return s;
}
Answer the question
In order to leave comments, you need to log in
#include <stdio.h>
#include <stdlib.h>
void Sum(unsigned n); // Functions' prototype
void main() {
unsigned n;
printf_s("Please, print --> ");
scanf_s("%u", &n);
Sum(n);
system("pause");
}
void Sum(unsigned n) {
unsigned s = 0; // iteration(s)
printf_s("Sum = ");
while (n > 0) {
printf("%d + ",n % 10);
s+= n % 10;
n /= 10;
}
printf_s("\b\b= %d\n",s);
}
Options
1) Pass a pointer to an array or a string to the function, and write intermediate values to this array at each iteration of the loop
2) Create a global variable, and the function writes to it - not kosher
3) Create a structure that will contain the result and intermediate values - fill it in and return it (or do it by pointer/reference)
4) Variations with an array, but the last number is the result.
Choose.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question