c++ to c

hi there, I'm looking for a bit of help hear. I'm trying to write a program for a school project. I have spent ages online finding info about c++ and writing the code below. but I found out today that I have to use c rather then c++. is there any way to modify my code below to make it c or will it be easier to start over again ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
cout << " Enter a number above 0 : ";
cin >> num;
num /= 10;
while ( num > 0 ) 

{
sum += num % 10;
num /= 10;
}
cout << "Sum = " << sum;
return 0;
}
You can build on what you have without starting again from scratch.

Replace <iostream> with <stdio.h>
Delete line 2 (namespace).

Replace each cin/cout with scanf/printf respectively.
http://www.cplusplus.com/reference/cstdio/scanf/
http://www.cplusplus.com/reference/cstdio/printf/

The syntax and usage for those is completely different to C++, you may have some learning to do there.

Also save the file with a .c rather than .cpp extension, as well as configure the compiler for C, not C++.
thanks for the help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
int main()
{
int num;
int sum = 0;
printf (" Enter a number above 0 : ");
scanf (num);
num /= 10;
while ( num > 0 ) 

{
sum += num % 10;
num /= 10;
}
printf ("Sum = " << sum)
return 0;
}

iv changed the code about but I'm still getting errors on lines 1 7 and 15, been playing about with them and cant seem to get rid of the errors, I was getting more errors on till I put in the brackets after printf but by putting in the crackets it removed some errors
the links are very helpful thanks
Last edited on
This should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <conio.h>

int main()
{
  int num;
  int sum = 0;
  printf(" Enter a number above 0 : ");
  scanf("%d", &num);
  
  while (num > 0)
  {
    sum += num % 10;
    num /= 10;
  }
  printf("Sum = %d", sum);

  getch();

  return 0;
}
that's great thanks a million, how would I go about changing it so instead of entering a number it carry's gets its number from a previous calculation,
sorry about all the questions I'm new to coding and kind of struggling to get a grip on it
how would I go about changing it so instead of entering a number it carry's gets its number from a previous calculation,

A nice clean solution would be to put the code for your existing calculations into its own separate function. That way, it can be considered as a 'black box' with an input and an output and all the nitty-gritty detail need no longer concern you in the main code.

However, as a beginner, you may not be ready to write your own functions yet (but it isn't hard). Instead, insert whatever other code you need in main() so that it is executed first and stores whatever value you need in num instead of getting it from the user.
Topic archived. No new replies allowed.