I have debugged this code and it works perfectly fine in C, but I'd like it to work in C++. If anyone can tell me how to translate it, please let me know.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
int main()
{
bool Prime(int A)
{
int k;
if (A == 2)
{
return true;
}
for (k = 0; k < (int)sqrt(A); k++)
{
if ( A % (k+2) == 0)
{
return false;
}
}
return true;
}
int start, end, max, j;
start = 101;
end = 150;
if (start < 2) { start = 2; }
max = end - (start - 1);
for(j = 0; j < max; j++)
{
if( Prime(j+start))
{
printf("\t\t\t\t %4d\n",j+start);
}
}
}
#include <iostream> //C++ equivalent of C's stdio.h
#include <cmath> //C Math Library - instead of math.h
//All the imports you need in C++ for this program
bool Prime(int A) //Define the function outside main
{
if(A == 2)
returntrue;
for(int k = 0; k <= static_cast<int>(sqrt(static_cast<float>(A))); k++) //You can create the counter k inside the for brackets
{
if(A % (k+2) == 0)
returnfalse;
}
returntrue;
}
int main() //The main function
{
int start, end, max;
start = 101;
end = 150;
if(start < 2)
start = 2;
max = end - (start-1);
for(int j = 0; j < max; j++)
{
if(Prime(j+start))
std::cout << "\t\t\t\t " << j+start << std::endl; //std::cout prints the things, std::endl adds a new line.
}
return 0;
}
When someone told me I can include the stdio.h which is the C language standard library into C++ code and use it. I tried and it actually works using GNU C++ Compiler...
So that means you don't need to convert the code at all.
Just as kbw said, most C programs are valid C++ programs.