User Tools

Site Tools


opus:spring2012:skinney1:cprogpart2

cprog Keywords

  1. Selection Structures (if, case/switch) (done)
  2. Repetition/Iteration Structures (for, while, do while) (done)
  3. Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional) (done)
  4. File Access (Read, Write, Append) (done)
  5. Structures (Declaration, Accessing Elements, Pointers to) (done)
  6. typedef, enum, union (done)
  7. Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments (done)
  8. Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile) (done)

cprog Keyword 9

Selection Structures (if, case/switch)

Definition

A selection structure allows the program to respond differently depending on users input. For example if the user is prompted a question responds “yes” a certain action is taken. On the other hand if the user responds “no” the program then goes to a part of the code the exit. A common way to set up the program to respond to input is to use the IF, or and switch statements.

Demonstration

The IF statement

int main()
{
        int num;
 
        printf("enter and number between -10 and 10: ");
        scanf("%d", &num);
 
        if (num > 0)
                printf("%d is a positive number\n", num);
 
        return (0);
}
lab46:~/src/cprog/classproject$ ./ex15.out
enter and number between -10 and 10: 10
10 is a positive number

The IF and Else statement

#include <stdio.h>

int main()
{
  int i = 6;

  if (i > 1)
    printf("We have\n");

  if (i > 10)
    printf("nice amount\n");
  else
    printf("not big enough\n");

  if (i == 5 )
  {
    printf("only got 5\n");
  }
  else if(i == 6 )
  {
    printf("just right\n");
  }
}
lab46:~/src/cprog/classproject$ ./ex17.out
We have
not big enough
just right

cprog Keyword 10

Repetition/Iteration Structures (for, while, do while)

Definition

The Repetition/Iteration Structures, also known as loops, allow the program to go through a self check to determine if it should continue the executing the program.

Demonstration

#include <stdio.h>
 
int main()
{
  int loopCount;
  printf("enter loop count: ");
  scanf("%d", &loopCount);
 
  while(loopCount > 0)
  {
    loopCount = loopCount -1;
     printf("only %d loops to go\n", loopCount);
  }
 
return (0);
}
 enter loop count: 12
only 11 loops to go
only 10 loops to go
only 9 loops to go
only 8 loops to go
only 7 loops to go
only 6 loops to go
only 5 loops to go
only 4 loops to go
only 3 loops to go
only 2 loops to go
only 1 loops to go
only 0 loops to go

cprog Keyword 11

Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)

Definition

An Array is setting up place holders for values. A good way to see this is if you picture an excel spreadsheet. You have a column and a row. The Array sets the number of columns and the number of rows. This allocates memory blocks to be used by the program. When you add more rows you are adding dimensions to the array.

That standard notation for an array is;

int array[SIZE] = {Column pointer,… ,…, etc..};

Demonstration

Single dimensional array

#include <stdio.h>
#define SIZE 5
int main()
{
	int array[SIZE] = {4, 5, 6, 7, 8};	
	int i;
 
	for (i= 0; i < SIZE; i++)	
	{
		printf("%d\n", array[i]);
	}
return 0;		
}
lab46:~/src/cprog/classproject$ ./ex19.out
4
5
6
7
8

cprog Keyword 12

File Access (Read, Write, Append)

Definition

File access is when the program gets information from a file or produces an output to a file. This can be helpful in many ways. For example. With our encoding program we took input from a file converted it and then output the results to a file.

Commands used fgetc fprintf

Demonstration

int main()
{
        FILE *in;
        char *c, fname[] = "message.in";
        int i;
        int *input[255];
 
        printf("Do you want to encrypt the file: ");
        scanf("%d", input);
 
        if (*input == 'y' || *input == 'Y')
                {
                        c = fgetc(in);
                        while(c != EOF)
                        {
                        if((c >=65) && (c <= 'Z'))
                                c++;
                        else if((c >= 'a') && (c <= 'z'))
                                c++;
                        if((c == ('Z' + 1)) || (c == ('z' + 1)))
                                c = c - 26;
                        fprintf(stdout, "%c", c);
                        c = fgetc(in);
                        }
                }
                else if (*input == 'n' || *input == 'N')
                {
                        c = fgetc(in);
                        while(c != EOF)
            {
                        if((c >=65) && (c <= 'Z'))
                                c--;
                        else if((c >= 'a') && (c <= 'z'))
                                c--;
                        if((c == ('Z' + 1)) || (c == ('z' + 1)))
                                c = c - 26;
                        fprintf(stdout, "%c", c);
                        c = fgetc(in);
                        }
                }
                fclose(in);
                return (0);
}

cprog Keyword 13

Structures (Declaration, Accessing Elements, Pointers to)

Definition

Structures are a collection of variables. They are grouped together into a single thing and proved a way of keeping data and needed elements together.

Basic Syntax

Structure Declaration: struct struct-name{ type field-name; type field-name; … };

Demonstration

#include <stdio.h>
 
struct color 
 
	{
	  int id;
	  char *name;
	  float percentage;
	} 
 
	black, blue, red;
 
 
int main() 
{
  struct color st;
  black.id=1;
  blue.name = "fav";
  red.percentage = 90.5;
  printf(" Id is: %d \n", black.id);
  printf(" Name is: %s \n", blue.name);
  printf(" Percentage is: %f \n", red.percentage);
  return 0;
}
 lab46:~/src/cprog/classproject$ ./ex20.out
 Id is: 1
 Name is: fav
 Percentage is: 90.500000

cprog Keyword 14

typedef, enum, union

Definition

typedef or type define allows you to declare one type of integer as another type. When you declare this definition the name is has been “enum”.

Demonstration

For example of the enum

typedef enum x{1, 2}  Value;

int main()
{
   Value data = 20;
   if (data == BLACK)
   {
      //etc.
   }
}  

This example defines the integer aaa, bbb and ccc and sets them as arrays.

typedef int aaa, bbb, ccc;
typedef int aaa[15], bbb[9][6], ccc[2];

This example sets char to have a double place value. 

typedef int (*char)(double);

cprog Keyword 15

Functions

Definition

A function is a relation between inputs and outputs. It will return a value for use within the program. A function lists the statements that is executes.

For example the function

result = power(val, pow);

This calls the function powers and assigning the return value to variable results.

Syntax

return-type function-name ( argument)
{
    local-declarations
    statements
    return return-value;
}

Demonstration

void exchange(int a, int b)
{
    int temp;
 
    temp = a;
    a = b;
    b = temp;
    printf(" From function exchange: ");
    printf("a = %d, b = %d\n", a, b);
}

cprog Keyword 16

Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)

Definition

Compiler The compiler translate high-level languages programs into assembly language.

Assembler

The assembler converts assembly language into object files. These contain a combination of machine instructions. They also convert decimal numbers in to programmer binary.

Linker

The linker merges the object files and creates the executable file. It has basically three tasks; searched the program to find routines, determine memory locations and resolves reference among the files.

Loader

The loader is the part of the OS that takes the executable file and brings it out in the open and starts running it.

Demonstration

Source file => Assembler => Object File \
Source file => Assembler => Object File  ---> Linker ---> Executable File
Source file => Assembler => Object File /       |
                                              library

cprog Objective

cprog Objective

Break down and look at the source code for a game.

Definition

Find the source code for any game that is written in C. In my own words explain what the code does and how it performs the desired tasks.

Method

Completion comes from the written explanation.

Measurement

There are many sources for code out there. I found a code for a battleship program written by Michael Margues.

URL: http://www.cprogramming.com/cgi-bin/source/source.cgi?action=Category&CID=2

Analysis

The code is long enough to wrap around my house. So I will be taking some highlights and working through the general structure of the program.

(1) The code includes the conio.h file that is part of the DOS world. It allows the creation of text user interfaces. From this point it then declares three main voids. Mike takes and int's the lengths of the boats by allocating each part of the boat to declaration. He then uses chars to create and array that is used at the board. This serves as a very creative way to tie the required game play to the text output world.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void checkShips();
void quitGame();
void targeting();

	int check[128];
	int target, hit = 0, i;
	int airpone, airptwo, airpthree, airpfour, airpfive;
	int destroypone, destroyptwo, destroypthree, destroypfour;
	int battlepone, battleptwo, battlepthree;
	int subpone, subptwo, subpthree;
	int patrolpone, patrolptwo;

	char rowone[50] = "11 12 13 14 15 16 17 18\n"; 
	char rowtwo[50] = "21 22 23 24 25 26 27 28\n";
	char rowthree[50] = "31 32 33 34 35 36 37 38\n";
	char rowfour[50] = "41 42 43 44 45 46 47 48\n";
	char rowfive[50] = "51 52 53 54 55 56 57 58\n";
	char rowsix[50] = "61 62 63 64 65 66 67 68\n";
	char rowseven[50] = "71 72 73 74 75 76 77 78\n";
	char roweight[50] = "81 82 83 84 85 86 87 88\n";
	char e;

	int airponetwo, airptwotwo, airpthreetwo, airpfourtwo, airpfivetwo;
	int destroyponetwo, destroyptwotwo, destroypthreetwo, destroypfourtwo;
	int battleponetwo, battleptwotwo, battlepthreetwo;
	int subponetwo, subptwotwo, subpthreetwo;
	int patrolponetwo, patrolptwotwo;

	char rowonetwo[50] = "11 12 13 14 15 16 17 18\n"; 
	char rowtwotwo[50] = "21 22 23 24 25 26 27 28\n";
	char rowthreetwo[50] = "31 32 33 34 35 36 37 38\n";
	char rowfourtwo[50] = "41 42 43 44 45 46 47 48\n";
	char rowfivetwo[50] = "51 52 53 54 55 56 57 58\n";
	char rowsixtwo[50] = "61 62 63 64 65 66 67 68\n";
	char rowseventwo[50] = "71 72 73 74 75 76 77 78\n";
	char roweighttwo[50] = "81 82 83 84 85 86 87 88\n";

(2)With everything set up for play he outputs the game board and begins getting the users input to establish the set up. This is setting data into each allocated spot on the board.

printf("Battle Ship\nBy Michael Marques\n");
	printf("These are the posible positions: \n");
	printf("11 ,12 ,13 ,14 ,15 ,16 ,17 ,18\n"); /* Displays posible ship positions */
	printf("21 ,22 ,23 ,24 ,25 ,26 ,27 ,28\n");
	printf("31 ,32 ,33 ,34 ,35 ,36 ,37 ,38\n");
	printf("41 ,42 ,43 ,44 ,45 ,46 ,47 ,48\n");
	printf("51 ,52 ,53 ,54 ,55 ,56 ,57 ,58\n");
	printf("61 ,62 ,63 ,64 ,65 ,66 ,67 ,68\n");
	printf("71 ,72 ,73 ,74 ,75 ,76 ,77 ,78\n");
	printf("81 ,82 ,83 ,84 ,85 ,86 ,87 ,88\n");

(3) The program prompts the user and allocates the selection as relevant to each ship. The program goes through this process with each piece of the game.

	printf("(3 spaces)Player 1 enter your Battle ship's poition: \n");
	printf("position1: ");     
	scanf("%d", &battlepone);
	printf("position2: ");
	scanf("%d", &battleptwo);
	printf("position3: ");
	scanf("%d", &battlepthree);

(4)

Ready to play! The user is then prompted for their input of where the enemy boats are. It runs through a long list of switch case statements for any of space that is hit.

	printf("Target: ");
	scanf("%d", &target);
	switch(target){
	case 11:
		switch(destroyponetwo) {
		case 11:
			printf("Hit!!!\n");
			hit = hit + 1;
			break;
		
			
		}
		switch(destroyptwotwo) {
		case 11:
			printf("Hit!!!\n");
			hit = hit + 1;
			break;
opus/spring2012/skinney1/cprogpart2.txt · Last modified: 2012/05/01 20:21 by skinney1