Skip to content

A basic C program….

February 18, 2014

Well, I have not done any programming in a *few weeks.  I thought I would write a little C program to refresh my brain on some basic programming rules.  These rules are applicable in ANY language that you may choose to write in.  The rules that come to mind after spending about 90 minutes on this simple little program are: 

program structure – break up your code into meaningful functions.

use existing functions – most languages will want you to reference the many existing functions to do things.

You don’t have to write new code for commonly performed tasks.

When writing functions, at least in C, define the function, its return type and any parameters it may use.

declare your variables before using them

This is the sample code I wrote – all it does is present a simple menu, requesting a keystroke choice of 1-4, while echoing the selection back to the user.  There is a simple while loop used to continue the program until a certain value is entered.  This program contains 4 functions, the main or driving function, where program control starts and ends.  three other simple functions that

1 – print the menu

2 – gathers the response

3 – echos the response

think like this

  1. program starts
  2. main runs
  3. main calls print_menu
  4. main calls get_selection
  5. main calls process_request
  6. loop in main starts over again, until a specific condition.

Program source code: you could copy and paste this code into a new C source file and compile and run it.

//request use of functions in these header files

#include <stdio.h> // a pre-processor directive
#include “stdlib.h”

// prototype functions (name, return type, parameters)

void print_menu();
int get_selection();
void process_request(int);

int main(){
 
    int choice = 0;
    
    while(choice != 4){
        print_menu();
        choice = get_selection();
        process_request(choice);  
    }//end while
    
}

void print_menu(){
     printf (“Main Menu\n\n\n”);
     printf(“Choose from the menu below, 1,2 or 3\n\n”);
     printf(“1 – New Game\n”);
     printf(“2 – Play previous game\n”);
     printf(“3 – Create a new game\n\n\n”);
     printf(“4 – To Quit\n\n”);
     
}

int get_selection(){
     
     int selection;
     scanf(“%d”, &selection);
     return selection;
}

void process_request(int value_entered){
     
     printf(“the value entered is %d \n\n”, value_entered);
     system(“pause”);     
}

Advertisements

From → C programming

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: