Skip to Content

Simple Examples

Simple Examples

Example 1: Prints Hello World

#include <stdio.h>

int main()
{
  printf( "Hello World\n" );
  return 0;
}

Example 2: Declare Variables

#include <stdio.h>
int main() 
{
    int x;
    printf( "Declare x first\n" );
    return 0;
}

Example 3: If Else

#include <stdio.h>	

int main()            /* Most important part of the program! */
{
    int age;                          /* Need a variable... */
    printf( "Please enter your age" );  /* Asks for age */
    scanf( "%d", &age );                 /* The input is put in age */
    if ( age < 100 ) {                  /* If the age is less than 100 */
    printf ("You are pretty young!\n" ); /* Just to show you it works... */
  }
else if ( age == 100 ) {            /* I use else just to show an example */ 
     printf( "You are old\n" );       
  }
  else {
    printf( "You are really old\n" );     /* Executed if no other 
statement is */
  }
  return 0;
}

Example 4: For Loop

#include <stdio.h>

int main()
{
    int x;
    /* The loop goes while x < 10, and x increases by one every loop*/
    for ( x = 0; x < 10; x++ ) {
        /* Keep in mind that the loop condition checks 
           the conditional statement before it loops again.
           consequently, when x equals 10 the loop breaks.
           x is updated before the condition is checked. */   
        printf( "%d\n", x );
    }
    getchar();
}

Example 5: While Loop

#include <stdio.h>

int main()
{
    int x;
    /* The loop goes while x < 10, and x increases by one every loop*/
    for ( x = 0; x < 10; x++ ) {
        /* Keep in mind that the loop condition checks 
           the conditional statement before it loops again.
           consequently, when x equals 10 the loop breaks.
           x is updated before the condition is checked. */   
        printf( "%d\n", x );
    }
    getchar();
}

Example 6: Do While Loop

#include <stdio.h>

int main()
{
  int x;

  x = 0;
  do {
    /* "Hello, world!" is printed at least one time
      even though the condition is false*/
    printf( "%d\n", x );
  } while ( x != 0 );
  getchar();
}


Dr. Radut | forum