How To: C / C++ Main
This howto shows the basic C/C++ main method as well as how to handle arguments. Whenever
I learn a new language these are just a few of the things that I want know ASAP and oddly
find that they are hard to find. Hopefully, this collection will be helpful to those
learning C / C++ or those who just need a quick question answered.
#include <stdio.h>
int main( int argc, const char* argv[] )
{
printf( "\nHello World\n\n" );
}
Try running this program with some command line parameters.
#include <stdio.h>
int main( int argc, const char* argv[] )
{
// Prints each argument on the command line.
for( int i = 0; i < argc; i++ )
{
printf( "arg %d: %s\n", i, argv[i] );
}
}
-- Note that the first argument is the name of the program.
Try running this program with two numbers.
#include <stdio.h>
int main( int argc, const char* argv[] )
{
int x;
int y;
// ensure the correct number of parameters are used.
if ( argc == 3 )
{
x = atoi( argv[1] );
y = atoi( argv[2] );
printf( "%d + %d = %d\n", x, y, x + y );
// Will print something like: 3 + 2 = 5
}
}
#include <stdio.h>
int main( int argc, const char* argv[] )
{
int i;
for( i = 0; i < 10; i++ )
{
printf( "Iteration %d\n", i );
}
}
#include <stdio.h>
int main( int argc, const char* argv[] )
{
int i = 0;
while ( i < 10 )
{
i++;
printf( "Iteration %d\n", i );
}
}
#include <stdio.h>
int main( int argc, const char* argv[] )
{
for ( i = 0; i < 10; i++ )
{
if ( i == 1 ) {
printf( "i = 1\n" );
} else if ( ( i == 2 ) || ( i == 3 ) ) {
printf( "i = 2 or 3\n" );
} else {
printf( "i = %d\n", i );
}
}
}
#include <stdio.h>
int main( int argc, const char* argv[] )
{
int numbers[10];
int i;
for ( i = 0; i < 10; i ++ )
{
numbers[i] = i * i;
// Note that arrays are zero based
}
for ( i = 0; i < 10; i ++ )
{
printf( "numbers[%d] = %d", i, numbers[i] );
}
}
Feedback
Please send me some
feedback
on how this worked for you. I'd be happy to help you figure it out for yourself.
|