COMP1911 17s1 Code Examples from Lectures on revision Introduction to Programming

Read in 10 numbers using getchar.

May have many spaces between them or not.

If not enough numbers are read in, should be an error

Negative numbers or anything else should be an error

Note: this is to show you how to skip spaces and read in ints with getchar(). Usually if you were just reading in ints you would use scanf with %d.

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

#define MAX 10

void printData(int data[], int size);
int readData(int data[], int maxSize);

int main(void){
    int nums[MAX];
    int numRead = readData(nums,MAX);
           
    if ( numRead != MAX){
        printf("Invalid\n");
        return EXIT_FAILURE;
    }
    printData(nums,MAX);
    
    return EXIT_SUCCESS;  
}

// Valid input examples

// 1 4 789 23 12 45 12 5 4 3

//     1      4 789 23 12 45 12   5 4      3

// We could break this function down into further functions
// for example we could write a function to read an integer 
int readData(int data[], int maxSize){
    int i = 0;
    int valid = 1;
    int c;
    int num = 0;
        
    c = getchar();
    while ( i < MAX && valid == 1 && c != EOF ){
       while(isspace(c)){
          c = getchar();
       }
       //read in a letter
       
       //skip more space
       if(isdigit(c)){
           num = 0;
           while(isdigit(c)){  
               
              num = num * 10 + c - '0';
              c = getchar();
           }
           data[i] = num;
           i++;
       } else {
           valid = 0;
       }
    }
    return i;
}


void printData(int data[], int size){
    int i = 0;
    
    while ( i < size ){
        printf("%d ",data[i]);
        i = i + 1;
    }
    printf("\n");
}

Some rbasic evision examples

What do these programs do?

#include <stdio.h>

int main(void) {
    int a = 25;
    if (a < 50) {
        if (a > 25) {
            printf("1\n");
        } else {
            printf("2\n");
        }
    } else {
        if (a < 75) {
            printf("3\n");
        } else {
            printf("4\n");
        }
    }
    return 0;
}

#include <stdio.h>

int main(void) {
    int a = 42;
    if (a < 25) {
        printf("1\n");
    }
    if (a < 50) {
        printf("2\n");
    }
    if (a < 75) {
        printf("3\n");
    }
    return 0;
}

#include <stdio.h>

int main(void) {
    int a = 42;
    if (a < 25) {
        printf("1\n");
    } else if (a < 50) {
        printf("2\n");
    } else if (a < 75) {
        printf("3\n");
    }
    return 0;
}

#include <stdio.h>

int main(void) {
    int a = 47;
    if (a < 25) {
        printf("1\n");
    }
    if (a < 50 && a > 45) {
        printf("2\n");
    }
    if (a < 75 || a > 70) {
        printf("3\n");
    }
    return 0;
}

#include <stdio.h>

int main(void) {
    int x = 30;
    int y = 50;
    int i;

    i = x;
    while (i <= y) {
        if (i % 7 == 0) {
            printf("%d\n", i);
        }
        i = i + 1;
    }
    return 0;
}

#include <stdio.h>
int main(void) {
    int s = 0;
    int t = 2048; 
    while (t != 0) {
       s = s + t % 10;
       t = t / 10;
    }
    printf("%d %d\n", s, t);
    return 0;
}

#include <stdio.h>
#include <string.h>

#define MAX 100

int main(void) {
    char str[MAX];
    int i, j, temp;
                 
    strcpy(str, "live"); 
                                  
    i = 0;
    j = strlen(str) - 1;
    while (i < j) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i = i + 1;
        j = j - 1;
    }

    printf("Str contains: %s \n", str);
    return 0;
}

Calculate the mathematical constant pi by summing the series 4 - 4/3 + 4/5 - 4/7 + 4/9 + ...

#include <stdio.h>


#define N_SERIES_TERMS 1000000

int main(void) {
    int n;
    double sum;

    n = 0;
    sum = 0;
    while (n < N_SERIES_TERMS) {
        if (n % 2 == 0) {
            sum = sum + 4.0 / (2 * n + 1);
        } else {
            sum = sum - 4.0 / (2 * n + 1);
        }
        n = n + 1;
    }

    printf("4 - 4/3 + 4/5 - 4/7 + 4/9 + ... = %f\n", sum);
    return 0;
}

This program should expect 2 command line arguments.

The first argument should be the name of a file that your program should read from and the second should be the name of a file that your program should write to.

Your program should read a search string from standard input.

Your program should then print all of the lines from the input file to the output file, with all occurrences of the search string removed. The input file should remain unchanged.

We are doing case sensitive matching.

If the wrong number of command line arguments are given, or a file can't be opened, a suitable message should be printed to standard error.

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

#define MAX_KEY 15
#define MAX_LEN 1026




int main(int argc, char * argv[]){
 
    return EXIT_SUCCESS;
}



This is the incomplete and possibly buggy version we were working on in class.

This program should expect 2 command line arguments.

The first argument should be the name of a file that your program should read from and the second should be the name of a file that your program should write to.

Your program should read a search string from standard input.

Your program should then print all of the lines from the input file to the output file, with all occurrences of the search string removed. The input file should remain unchanged.

We are doing case sensitive matching.

If the wrong number of command line arguments are given, or a file can't be opened, a suitable message should be printed to standard error.

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

#define MAX_KEY 15
#define MAX_LEN 1026


int matches(char in[],int i,char key[]);
void processData(char key[], FILE * fIn, FILE * fOut);
// argc = 3
//       0      1       2  
// ./remove f.txt out.txt


int main(int argc, char * argv[]){
    char key[MAX_KEY]; //Sing
      
    FILE * fileIn;
    FILE * fileOut;
   
    //Check there are command line arguments 
    if ( argc < 3){
        fprintf(stderr,"Usage: ./remove fname1 fname2\n");
        return EXIT_FAILURE;
    }
    
    //Open file for reading and check it worked
    fileIn = fopen(argv[1],"r");
    if( fileIn == NULL){
        fprintf(stderr,"could not open file\n");
        return EXIT_FAILURE;
    }
    
    //Open file for writing and check it worked
    fileOut = fopen(argv[2],"w");
    if( fileOut == NULL){
        fprintf(stderr,"could not open file\n");
        return EXIT_FAILURE;
    }
    
    //Read in string to search for and remove
    printf("Enter string to remove: ");
    fgets(key,MAX_LEN,stdin);
    int len = strlen(key);
    if(len > 0 && key[len-1] == '\n'){
        key[len -1] = '\0'; //get rid of trailing newline
    }
    
    //Read in each line of input from the file and 
    //remove the key if it exists
    processData(key,fileIn,fileOut);
    
    //Close the files
    fclose(fileIn);
    fclose(fileOut);
    return EXIT_SUCCESS;
}

void processData(char key[], FILE * fIn, FILE * fOut){
    char in[MAX_LEN];  //One line of input from the file
    //         Sing
    //One. Singular sensation
    while(fgets(in,MAX_LEN,fIn) != NULL){
        i = 0;
        while ( in[i] != '\0'){
            if(matches(in,i,key)){
               i = i + strlen(key);
            } else {
               fprintf(fOut,"%c",in[i]);
               i++;
            }
        }
    }
}
//LEFT AS AN EXERCISE
int matches(char in[],int i,char key[]){
    

}

This is my solution to remove0.c

This program should expect 2 command line arguments.

The first argument should be the name of a file that your program should read from and the second should be the name of a file that your program should write to.

Your program should read a search string from standard input.

Your program should then print all of the lines from the input file to the output file, with all occurrences of the search string removed. The input file should remain unchanged.

We are doing case sensitive matching.

If the wrong number of command line arguments are given, or a file can't be opened, a suitable message should be printed to standard error.

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

#define MAX_KEY 15
#define MAX_LEN 1026


void processLine(char input[],char key[], FILE *f);
int matches(char input[], int index, char key[]);

int main(int argc, char * argv[]){
    char key[MAX_KEY];
    
    char in[MAX_LEN];
    
    FILE * fileIn;
    FILE * fileOut;
   
    if(argc < 3 ){
        fprintf(stderr,"Usage: argv[0] fnameIn fnameOut\n");
        exit(EXIT_FAILURE);
    }
    
    fileIn = fopen(argv[1],"r");
    if(fileIn == NULL){
        fprintf(stderr,"Could not open %s\n",argv[1]);
        exit(EXIT_FAILURE);       
    }
    
    fileOut = fopen(argv[2],"w");
    if(fileOut == NULL){
        fprintf(stderr,"Could not open %s\n",argv[1]);
        exit(EXIT_FAILURE);       
    }
    
    printf("Enter string to remove: ");
    fgets(key,MAX_KEY,stdin);
    int len = strlen(key);
    if(len > 0 && key[len-1] == '\n'){
        key[len -1] = '\0'; //get rid of trailing newline if it exists
    }
  
    
    while(fgets(in,MAX_LEN,fileIn)!= NULL){
        processLine(in,key,fileOut);    
    }
    
    fclose(fileIn);
    fclose(fileOut);

    return EXIT_SUCCESS;
}

//returns 1 if the key matches the input at the given index
//case sensitive matching is used.
int matches(char input[], int index, char key[]){
    int i = 0;
    
    while(key[i] != '\0' &&
          key[i] == input[i + index]){
         i++;      
    }
    return key[i] == '\0';
}

//Prints characters to the file f, from the input that don't match the key
//skips over the characters that do match the key
void processLine(char input[],char key[], FILE * f){
    int i = 0;
        
    int keyLen = strlen(key);
       
    while(input[i] != '\0'){
        if(matches(input,i,key)){
            i = i + keyLen;
        } else {
            fprintf(f,"%c",input[i]);
            i++;  
        }         
    }
}


Write a program that reads in rgb colour data from stdin, stores them in a grid and detects horizontal stripes of the same colour.

For this question you MUST use a struct to store each colour.

Each colour has 3 values, a red, a green and a blue.

These values are all numbers between 0 and 255.

The program prompts the user to enter a size for the grid. You can assume the maximum size will be 20.

The program then prompts the user to enter size*size colours. So for example, if the user entered 4, they would then need to enter 4*4*3 numbers as there are 4*4 colours and each colour has 3 components.

The program needs to store the colours and then check each row of the grid to see if all the colours in the row are identical ( a stripe ).

It should print out the colour of the stripe and the row id of the stripe.

For this question you can assume you do not need to do any error checking.

Sample input/output is shown below:

./rgb

Enter grid size : 3

Enter 9 colours : 1 0 0 1 0 0 1 0 0 255 0 0 255 0 0 255 255 255 0 0 0 0 0 0 0 0 0

Colour Grid ( 1, 0, 0) ( 1, 0, 0) ( 1, 0, 0) (255, 0, 0) (255, 0, 0) (255,255,255) ( 0, 0, 0) ( 0, 0, 0) ( 0, 0, 0)

Stripes:

Horizontal stripe of colour ( 1, 0, 0) on row 0

Horizontal stripe of colour ( 0, 0, 0) on row 2

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

int main(void){
    
     
    return EXIT_SUCCESS;
}


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

#define GRID_SIZE 20

typedef struct colour Colour;

struct colour {
   int r; //0..255
   int g; //0..255
   int b; //0..255
};

void showColour(Colour col);
void readColours(Colour grid[GRID_SIZE][GRID_SIZE], int size);
void printStripes(Colour grid[GRID_SIZE][GRID_SIZE], int size);
void printColours(Colour grid[GRID_SIZE][GRID_SIZE], int size);
int coloursAreEqual(Colour col1, Colour col2);

int main(void){
    Colour grid[GRID_SIZE][GRID_SIZE];
    int size;
    
    printf("Enter grid size : ");
    scanf("%d",&size);
    printf("Enter %d colours : ", size*size);
    readColours(grid,size);
    
    printf("Colour Grid\n");
    printColours(grid,size);
    printf("\nStripes:\n");
    printStripes(grid,size);
     
    return EXIT_SUCCESS;
}


void readColours(Colour grid[GRID_SIZE][GRID_SIZE], int size){
    int i = 0;
    int j = 0;
    while( i < size){
         j = 0;
         while ( j < size ){
             scanf("%d %d %d",&grid[i][j].r,
                              &grid[i][j].g,
                              &grid[i][j].b);                    
             j++;
         }
         i++;
    }
}


void printStripes(Colour grid[GRID_SIZE][GRID_SIZE], int size){
   int i = 0;
   int j = 0;
   int stripe  = 1;
   
   while ( i < size ){
       j = 0;
       stripe = 1;
       while ( j < size-1 ) {
           if(coloursAreEqual(grid[i][j], grid[i][j+1]) == 0){
               stripe = 0;
           }
           j++;
       }   
       if(stripe){
          printf("Horizontal stripe of colour ");
          showColour(grid[i][0]);
          printf("on row %d\n",i);
       }
       i++;
   }

}

void printColours(Colour grid[GRID_SIZE][GRID_SIZE], int size){
    int i = 0;
    int j = 0;
    while( i < size){
         j = 0;
         while ( j < size ){
             showColour(grid[i][j]);                
             j++;
         }
         printf("\n");
         i++;
    }
}

int coloursAreEqual(Colour col1, Colour col2){
    return (col1.r == col2.r && 
            col1.g == col2.g &&
            col1.b == col2.b );
}

void showColour(Colour col){
    printf("(%3d,%3d,%3d) ",col.r,
                            col.g,
                            col.b);    
}