Home | UNC | CS Dept. | Rose-Hulman | Bandar | Contact
Research

Courses

Schedule

Resume

Biography

T-Files

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.

The Main Method

#include <stdio.h>
int main( int argc, const char* argv[] )
{
	printf( "\nHello World\n\n" );
}

Command Line Arguments

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
	}

}


The For Loop

#include <stdio.h>
int main( int argc, const char* argv[] )
{
	int i;
	
	for( i = 0; i < 10; i++ ) 
	{
		printf( "Iteration %d\n", i );
	}
}

The While Loop

#include <stdio.h>
int main( int argc, const char* argv[] )
{
	int i = 0;

	while ( i < 10 )
	{
		i++;
		printf( "Iteration %d\n", i );
	}

}

The If Statement

#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 );
			
		}
	}
}

Arrays

#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.
Last Modifed December 31st, 1969
Copyright c 2003 - Travis Sparks - All Rights Reserved


DISCLAIMER: All usage of content on this site is subject to the UNC Honor Code. All contect on this site is posted with the express purpose of collaboration and general information.