How do I print a value on a console in a jupyter notebook?

Hello, apologies for this very basic question, but I am struggling with outputting a value on a function. I am running the following simple programm in a C++ notebook:

Whenever I press the run button, it just creates another cell and doesn’t output anything. Where do I find the console to output the line in the printf() function, or is it more of a syntax error (I am also new to C++)?

Thanks in advance.

Did you try putting the following code in the next cell after the one you had in the image and running that following executing the first cell?

main()

Your first code block declared & defined the function. Then you need to call the function. (More about main() here and here.)

Additionally, putting a simpler printf() in a cell alone and running that cell would have been a more direct way to test where the output for the printf() function will show.


Always share code as text and not an image, or at least not just an image. It makes it easy for those trying to help you test things and return to you a variation on your code. In this case, the image was indeed useful because it also indicated the specific C++ kernel you were using as launches via MyBinder service from here (click ‘launch binder’) offer three versions.


Because you mention being new to C++, you may want to go to the work through the demo notebook available when you press ‘launch binder’ at the site I referenced in the last section. (Click here to launch directly.) If you prefer to do it in C++17 & JupyterLab, when the classic interface opens, click on the Jupyter logo in the upper left side. That will switch to the JupyterLab interface. It will start it in what corresponds to the root of the repository and so to get to the demo notebook in the JupyterLab interface, double-click on ‘notebooks’ in the file browser panel on the left. Then double-click on ‘xcpp.ipynb’ listed there. When you are in the ‘xcpp.ipynb’ notebook in JupyterLab, click on the kernel indicator in the upper right to toggle a selector & change the kernel to ‘C++17’ so that it matches your kernel. Work through executing the cells.



Technical Supplement
Leaving C++ code here to be handy, if needed later:

#include <cstdio>
#include <iostream>
#include <string>

int main() {
    int x =5;
    double y = 3.14;
    printf("The value of x is: %d and the value of y is: %f\n",x,y);
    return 0;
}
1 Like

Many thanks for the help. Indeed it seems to work if I call the main() function within the same cell:

int main() {
int x =5;
double y = 3.14;
printf(“The value of x is: %d and the value of y is: %f\n”,x,y);
return 0;
}
main();

1 Like