Adding 2 numbers  – real/floating point numbers

0004

Exercise 1 : Modify your code from the previous example to use floating point numbers 5.1 and 6.1

  1. Teacher modifies variable declarations, but leaves prinf to output integer values.
  2. The erroneous result is observed and explained: the binary data stored at the variables are calculated and interpreted to show an integer result.  
  3. Teacher modifies the code of printf() to use %d and now the correct result is shown.


Exercise 2:

Observe what is output when %d is changed to each of the following, one at a time:

%d for int

%f for float

%lf for double

%c for char

%s for string

Video Demonstration

https://youtu.be/Be_QtiweYTY

You can download the files here: https://drive.google.com/file/d/1nVXCOXTJkPYNSs2jDwxGGbz9mvuKooDK/view?usp=sharing

Code

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

int main()
{
   //declare and identify variables
   float a,b;
   float c;

   //Initialize the variables
   a=5.1;
   b=6.1;

   //Perform processing c <-- a+b
   c=a+b;

   printf("The sum of %.1f and %.1f is %.f \n", a,b,c);


}

© 2021  Vedesh Kungebeharry. All rights reserved. 

Adding 2 numbers – Outputting the result with printf()

0003-OutputResults

Exercise: Modify your previous code to output results using printf()

Video Demonstration

https://youtu.be/YE0V_XLuOx8

You can download the file used in the video here: https://drive.google.com/file/d/1A4oCHsdXW0Ab7ox-T_zXi3eVmrQkXoic/view?usp=sharing

Code

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

int main()
{
   //declare and identify variables
   int a,b;
   int c;

   //Initialize the variables
   a=5;
   b=6;

   //Perform processing c <-- a+b
   c=a+b;

   printf("The sum of %d and %d is %d \n", a,b,c);


}

© 2021  Vedesh Kungebeharry. All rights reserved. 

Adding 2 numbers – (Declaring integer variables, Watching Variables)

0002-ADDING 2 integers , 5 and 6 no output

Exercise 1 

  1. Write code which declares 2 integer variables A and B .  Initialize A to 5 and B to 6.  Use a third variable , C to store the result of A+B.  

  2. Verify addition has occurred by using the variable watch window.

Demonstration Video

https://youtu.be/nfGwWUIZDaY

Download the files here: https://drive.google.com/file/d/15PfdndUqvnd_fLYPzctsgZMG4I9oSYtx/view?usp=sharing

Code

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

int main()
{
   //declare and identify variables
   int a,b;
   int c;

   //Initialize the variables
   a=5;
   b=6;

   //Perform processing c <-- a+b
   c=a+b;


}

© 2021  Vedesh Kungebeharry. All rights reserved. 

Your First Program Using Codeblocks IDE

0001 Your first program

*Using Codeblocks 17.12

1. Create a new Project

2.Select “Console Application” and click on go.

3.Select “C” and click next.

4. Give your project a title and optionally select a folder where you want the project to be created. In this case we use “Upper camel case”` : “0001-MyFirstProgram”

5.Leave all settings as default and choose finish:

6. Open main.c from the tree on the left. [1] Expand sources, [2]then double click on “main.c”.

7. Click on Build, and choose build and run.

8. Your code is now built to an executable file, and the program is executed in the console window:

Exercises

  1. What happens when “Hello world!\n” is changed to “Hello world!” and the program is run?
  2. Modify the printed message to say “Goodbye”.

You can download the project here:

https://drive.google.com/drive/folders/1-oDom6OVimkNZeBACsJs9FZ0byhsNXHv?usp=sharing

The code is shown below:

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

int main()
{
    printf("Goodbye world!");
    return 0;
}

© 2021  Vedesh Kungebeharry. All rights reserved. 

Debugging and Refactoring exercise

0008.2

Definition: Debugging is the process of finding and fixing errors in program code.

Definition: Factoring (Decomposition) is the breaking of a complex task to its atomized sub parts. The goal of factoring is to reach a level of detail that can be represented in an algorithm and eventually programming code.  

Definition: Refactoring – Changing program code’s structure to improve readability or efficiency without changing it’s behavior; or, to change a code’s factoring

Instructions

Copy and paste the following code into the main.c file of  a new project:

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


int main()
{
    float a,b,c,D,root1,root2;

    printf("Please enter a value for a...\n");
    scanf("%f",a);

    printf("Please enter a value for b...\n");
    scanf("%f",&b);

    printf("Please enter a value for c...\n");
    scanf("%f",&c);

    printf("\n");

    D=(b*b)-(4*a*c);


    if(D<0)
    {
        printf("no roots\n Exiting program...\n");
    }
    else if (D=0)
    {
        root1=(b*b)/(2*a);
        printf("Equation has only one root = %.2f \n Exiting program...\n ");

    }
    else
    {
        root1=((b*b)-sqrt(D))(2*a);
        root2=((b*b)+sqrt(D))/(2*a);
        printf("Roots are %.2f and %.2f \n Exiting program...\n",root1,root2);

    }
    return 1;




}

  1. Debug your program so that it produces correct results in all cases.
  2. Modify your code to use functions.
    • Move the code for calculating the Discriminant into another function. Do this by
      • Create a new function,which returns the value of the discriminant. The new function should implement the function declaration: float discriminant (acoef,bcoef,ccoeff);
      • Change the line which contains
        D=(b*b)-(4*a*c); to D=discriminant(a,b,c);
    • Move the code for calculating root 1 and root 2 into 2 separate functions. To do this, you must create suitable function declarations and accompanying function declarations which can accomplish the task.

© 2020  Vedesh Kungebeharry. All rights reserved. 

Introduction to functions

0008.1

Required reading: C functions (This is a link to an external website)

Exercise

Similar to our previous example, create a program which contains:

  1. A function which returns the area of a circle given its radius (assume all variables used are double)
  2. A Function which returns the volume of a circle given the radius(assume all variables used are double)
  3. A function which does not return any data and takes no parameters but outputs the author of your program .  Name your function Signature.

Solution

Note the function declarations.  This is necessary for proper execution of our code.

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

//global variables
double area,volume;
double radius;
const double PI = 3.14;

//function declarations
double Area(double radius);
double Volume(double radius);
void Signature();

int main()
{
    //initialization
    area,radius,volume = -999;

    printf("enter radius\n");
    scanf("%lf", &radius);

    area    =   Area(radius);
    volume  =   Volume(radius);

    printf("The  Area is \t: \t%.2f\n",area);
    printf("The  Volume is \t: \t%.2f\n",volume);

    Signature();



}

double Volume(double radius)
{
    return((4/3)*PI*radius*radius*radius);
}

double Area(double radius)
{
    return (PI*radius*radius);
}

void Signature()
{
	//ASCII Art Generated using https://patorjk.com/software/taag/#p=testall&f=Big&t=kunge
    printf("Thanks for using my program!  \n");
    printf("  _  __                       \n");
    printf(" | |/ /                       \n");
    printf(" | ' /_   _ _ __   __ _  ___  \n");
    printf(" |  <| | | | '_ \ / _` |/ _ \ \n");
    printf(" | . \.|_| | | | | (_| |  __/ \n");
    printf(" |_|\_\__,_|_| |_|\__, |\___| \n");
    printf("                   __/ |      \n");
    printf("                  |___/       \n");
    printf("Author: Vedesh Kungebeharry   \n");
    printf("contact: VKunge@gmail.com     \n");
    printf("exiting...  \n");


}

© 2020  Vedesh Kungebeharry. All rights reserved. 

Exercises – Finding the Volume Of Sphere, Quadratic Equation Roots

0007.(1 and 2)

Attempt the 2 c programming exercises below.  If you are having a hard time starting, try:

  1. Examining the solution the exercise 2 for guidance.
  2. Attempt exercise 1 (no solution was provided here)
  3. Ideally, attempt exercise 2 without looking at the solution.

Exercise.


1. Create a program which accepts the radius for a circle/sphere  and outputs the volume and maximum cross sectional area.  Your program must prompt for input, and produce relevant results.

2. Given the coefficient  a b and c of a quadratic equation in the form y=ax^2+bx+c output the solution to the equation when y=0

Solution to Find the roots of a Quadratic Equation:

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


int main()
{
    float a,b,c,D,root1,root2;


    printf("Please enter a value for a...\n");
    scanf("%f",&a);

    printf("Please enter a value for b...\n");
    scanf("%f",&b);

    printf("Please enter a value for c...\n");
    scanf("%f",&c);

    printf("\n");

    D=(b*b)-(4*a*c);


    if(D<0)
    {
        printf("no roots\n Exiting program...\n");
    }
    else if (D==0)
    {
        root1=(-b)/(2*a);
        printf("Equation has only one root = %.2f \n Exiting program...\n ");

    }
    else
    {
        root1=((-b)-sqrt(D))/(2*a);
        root2=((-b)+sqrt(D))/(2*a);
        printf("Roots are %.2f and %.2f \n Exiting program...\n",root1,root2);

    }
    return 1;




}

Strategy for Coding using Exercise 1 as an example

© 2020  Vedesh Kungebeharry. All rights reserved. 

Checking for Integers (in C code)

When processing text data , either from a text file or input entered via the keyboard, we sometimes need to check the data to see if it’s an integer first, then use it for processing.

Note: All code in this example can be downloaded here

Logical error…

In this example, we ask our user to enter a valid integer and we output the square of the integer:

/*
we ask our user to enter a valid integer
and we output the square of the integer
*/
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int inputInteger; //string used to store user input
    int  inputSquared;// used to store the square of a valid integer.

    printf("Enter an Integer value....\n");
    scanf("\n%d",&inputInteger);//get input from user

    printf("You entered : %d\n", inputInteger);

    inputSquared = inputInteger*inputInteger;//find square
    printf("\n%d squared is %d\n",inputInteger, inputSquared);
    printf("\nSuccess!  Exiting program\n");

    return 0;
}

This code works when we enter valid input , in this case the user enters 12:

However, if the user enters alpha text data, we get strange results:

A simple fix…

To fix this issue we adhere to 2 rules:

  1. Read all text data as character strings, and then
  2. use the atoi(…) function to convert the string to a valid integer

The previous example can be fixed by using the rules above applied to the current situation:

  1. Read all text data as character strings, and then
  2. use the atoi(…) function to TRY to convert the string to a valid integer
  3. If the user had entered alpha text data, generate an error message, prompt the user to re-enter the data, and go to step 1, otherwise :
  4. Calculate the valid output.

Below is the code…

/*
this programs shows how to validate user input as integers.
if the user enters a valid integer, we output the square of the integer,
otherwise we output an error message and prompt the user to re enter  a valid integer
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //in order touse true and false

int main()
{
    char input[50]; //string used to store user input
    int  inputAsAnInteger;//used store the converted input  as an integer
    int  inputSquared;// used to store the square of a valid integer.

    while(true)//loop 'infinitely'
    {
        printf("Enter an Integer value....\n");
        scanf("%s",&input);//get input from user

        printf("You entered : %s\n", input);

        inputAsAnInteger=atoi(input);//convert input to integer

        if (inputAsAnInteger==0)//if the input is not a number......
        {
            printf("Invalid input entered\n\n");
        }
        else//input is a number
        {

            inputSquared = inputAsAnInteger*inputAsAnInteger;//find square
            printf("\n%d squared is %d\n",inputAsAnInteger, inputSquared);
            printf("\nSuccess!  Exiting program\n");
            break;//exit 'infinite' loop.
        }
    }
    return 0;
}


And a sample run shown below with invalid input and valid input:

However, note that atoi(…) returns 0 when 0 is entered or invalid input entered, an edge case which produces erroneous results:

Fixing the fix…

This problem can be solved by checking every digit in the input string to see if they are all digits, before converting to string. In this way, we cater for a correct result if the text data “0” is entered.

Our rules to fix the problem now becomes:

  1. Read all text data as character strings, and then
  2. Check eack character of the string to ensure they’re all digits, then
  3. use the atoi(…) function to convert the string to a valid integer

This code uses a function which performs that check:

/*
this programs shows how to validate user input as integers.
if the user enters a valid integer, we output the square of the integer,
otherwise we output an error message and prompt the user to re enter  a valid integer
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //in order to use true and false
#include <ctype.h>   // in order to use the isdigit function.

bool isNumber(char* stringArray);

int main()
{
    char input[50]; //string used to store user input
    int  inputAsAnInteger;//used store the converted input  as an integer
    int  inputSquared;// used to store the square of a valid integer.

    while(true)//loop 'infinitely'
    {
        printf("Enter an Integer value....\n");
        scanf("%s",&input);//get input from user

        printf("You entered : %s\n", input);


        if (!isNumber(input))//if the input is not a number......
        {
            printf("Invalid input entered\n\n");
        }
        else//input is a number
        {
            inputAsAnInteger=atoi(input);//convert input to integer
            inputSquared = inputAsAnInteger*inputAsAnInteger;//find square
            printf("\n%d squared is %d\n",inputAsAnInteger, inputSquared);
            printf("\nSuccess!  Exiting program\n");
            break;//exit 'infinite' loop.
        }
    }
    return 0;
}

bool isNumber(char* stringArray)
{

    //go through each character
    //location in the array until
    //we reach the null character (end of input)
    for (int i = 0; stringArray[i]!='\000'; i++)
    {
        if(isdigit(stringArray[i])==0)//if the current character is not a digit....
            return false; //return false and end function here

    }

    return true;//return true since the entire array contained numeric characters
}

Now, we get correct results in all cases:

Conclusion And Thoughts

The basic strategy for checking for integer input, is to read all input as text and use the atoi(…) function to try converting the input whilst performing error checking.

To best understand the coded examples, I insist that you use the data in the sample runs to :

  1. perform a dry run as well as
  2. step through each line of code by running the code in debug mode .

The examples above contain minimal explanation, is intended pre-class preparation and presentation in our classroom where we can have a broader discussion and I can answer any questions that you may have.

© 2020 Vedesh Kungebeharry. All rights reserved.

Mini IA Example – A library catalog

In this post, we build on the menu system shown here:Mini Internal Assessment Example

Download the code here.

Screen Shots

The main Menu
Listing All books
Save Data sub menu

Project organization

Code is split into various C and Header files as shown in the screen capture below:

LibrarySystemExample-Files
LibrarySystemExample-Files

See the Contents of the code files below:

main.c

/*
This program demonstrates how a menu driven
system can be used to trigger functions used
to maintain a simple library catalog.

Data is loaded to and from a binary file.

Date    :   16th November 2019
Author  :   Vedesh Kungebeharry
*/

#include "MenuSystem.h"
#include "CatalogSystem.h"




//function declarations
void initialization();
void exitProgram();


int main()
{

    initialization();
    runMainMenu();
    exitProgram();


    return 0;
}


void initialization()
{
    menuInitialization();
    loadCatalogFromFile();
}

void exitProgram()
{
    saveCatalogToFile();
    exitProgramMenu();
}


CatalogSystem.h

#include <stdbool.h>
#ifndef CATALOGSYSTEM_H_INCLUDED
#define CATALOGSYSTEM_H_INCLUDED
//#include "CatalogSystem.c"

//structures
typedef struct BookStructure
{

    char    Title [50];
    char    Author [50];
    int     Year;
    bool    isOnLoan;
    bool    hasData;
} Book;


//function declarations
void printBookByLocation(int location);
void printBook(Book b);
int  findBook(char searchQuery[]);
void printAllBooks();
int  addBook(Book newBook);

//file function declaration
void saveCatalogToFile();
bool loadCatalogFromFile();

//functions for testing
void setupDummyData();

#endif // CATALOGSYSTEM_H_INCLUDED

CatalogSystem.c

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "CatalogSystem.h"

#define maxSize 1000

//constants
const char catalogFilename[50] = "catalog.bin";

//global variables
Book catalog[maxSize];
int count = 0;
FILE *datafilePtr;

//prints a book stored at a given index in the catalog array
void printBookByLocation(int location)
{
    printBook(catalog[location]);
}

void printBook(Book b)
{
    if (b.hasData)
    {
        printf("Title:\t%s\n",b.Title);
        printf("Author:\t%s\n",b.Author);
        printf("Year:\t%d\n",b.Year);
        printf("Loaned? : \t%s\n\n",b.isOnLoan?"Yes":"No");
        //printf("hasData: \t%s\n\n", b.hasData?"Yes":"No");


    }
    else
    {

        printf("\nNo book found at current index location...\n");
    }

}

int addBook(Book newBook)
{
    newBook.hasData=true;
    catalog[count]=newBook;//place book in next
                          //empty location in the array
    count++;//increment count to point to the
            //next empty location.

    return count-1;
}

void printAllBooks()
{
    if(count==0)
    {
        printf("\nNo books in catalog\n");
    }
    else
    {
        for (int i = 0; i<count;i++)
        printBook(catalog[i]);

    }

}

//finds a book by searching for titles that contain a substring of the query.
//this function finds the first positive result only
int findBook(char searchQuery[])
{
    for( int i = 0; i<count; i++)
    {
        char currentBookTitle[50];
        char lowercaseSearchQuery[50];
        strcpy(currentBookTitle,catalog[i].Title);
        strcpy(lowercaseSearchQuery,searchQuery);

        strlwr(currentBookTitle);
        strlwr(lowercaseSearchQuery);

        if(strstr(currentBookTitle, lowercaseSearchQuery))
            return i;

    }

    return -1;
}

void saveCatalogToFile()
{
    datafilePtr = fopen(catalogFilename,"wb");
    if (datafilePtr == NULL)
    {
        //unable to create file
        printf("Error creating file to save data\n");
        exit(1);
    }
    else
    {
        fwrite(&count,sizeof(int),1,datafilePtr) ;
        for(int i = 0; i<count; i++)
        {
           fwrite(&catalog[i],sizeof(Book),1,datafilePtr) ;
        }
    }
    fclose(datafilePtr);

}

bool loadCatalogFromFile()
{
    datafilePtr = fopen(catalogFilename,"rb");
    if (datafilePtr == NULL)
    {
        //unable to create file
        printf("Datafile not found...Catalog empty\n");
        printf("A new save file will be created during exit or manual save....\n");
        return false;
    }
    else
    {
        fread(&count,sizeof(int),1,datafilePtr);
        for(int i = 0; i<count; i++)
        {
           fread(&catalog[i],sizeof(Book),1,datafilePtr) ;
        }
    }
    fclose(datafilePtr);
    return true;

}


void setupDummyData()
{
    Book a=
            {
                .Title = "ATitle",
                .Author = "AAuthor",
                .Year = 2006 ,
                .isOnLoan=false
            };
    Book b=
            {
                .Title = "BTitle",
                .Author = "BAuthor",
                .Year = 2006 ,
                .isOnLoan=false
            };
    Book c=
            {
                .Title = "CTitle",
                .Author = "CAuthor",
                .Year = 2006 ,
                .isOnLoan=false
            };


    addBook(a);
    addBook(b);
    addBook(c);

    saveCatalogToFile();


}



MenuSystem.h

#ifndef MENUSYSTEM_H_INCLUDED
#define MENUSYSTEM_H_INCLUDED

//function declarations
void    menuInitialization();
void    showMainMenu();
void    showSaveLoadMenu();
void    runMainMenu();
void    runSaveLoadMenu();
void    pause();
void    printAllBooksUserInteraction();
void    AddNewBookUserInteraction();
void    exitProgramMenu();
void    SaveLoadUserInteraction();
void    ClearConsoleToColors(int ForgC, int BackC);
void    SetColor(int ForgC);


#endif // MENUSYSTEM_H_INCLUDED

MenuSystem.c

#include <time.h> // for pause()
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>   //for getch()
#include <string.h>
#include <windows.h> //for SetColor()
#include "MenuSystem.h"
#include "CatalogSystem.h"

/*See: https://stackoverflow.com/questions/29574849/how-to-change-text-color-and-console-color-in-codeblocks

system("Color F0");
Letter Represents Background Color while the number represents the text color.

0 = Black

1 = Blue

2 = Green

3 = Aqua

4 = Red

5 = Purple

6 = Yellow

7 = White

8 = Gray

9 = Light Blue

A = Light Green

B = Light Aqua

C = Light Red

D = Light Purple

E = Light Yellow

F = Bright White


*/

//global static  variables
char choice;


/*
*initialize all instance variables and arrays here
*
*/
void menuInitialization()
{
    choice = '_';
}

//displays the main menu and accepts input
void runMainMenu()
{
    int pauseDuration = 2000;
    int sentinel=0;//used to break  out of our menu loop
    while (sentinel>=0)//loop menu here
    {
        showMainMenu();//display menu text

        choice = getch();//get a character from the input buffer

        system("@cls");// clear screen after getting input

        switch (choice)//based on the choice take the desired action
        {
            case '1':   printf("\nList all books\n");
                        printAllBooksUserInteraction();
                        break;

            case '2':   printf("\nAdd a new book...\n");
                        AddNewBookUserInteraction();
                        break;

            case '3':   SaveLoadUserInteraction();
                        break;

            case 'q':   printf("\nYou chose to quit\n");
                        sentinel=-1;//update the sentinel so that looping will cease
                        break;

            case 'Q':   printf("\nYou chose to quit\n");//cease if upper case
                        sentinel=-1;
                        break;
            default:
                        printf("\nYou have entered an option that is not in the menu\n");
                        pause(pauseDuration);
                        break;

        }
        if(sentinel>=0)//if we have continued regular execution , continue looping
        {
            system("@cls");//clear last screen
        }

    }



}

//shows and accepts input for the math sub menu
void runSaveLoadMenu()
{
    int pauseDuration = 2000;
    int sentinel=0;

    while (sentinel>=0)
    {

        showSaveLoadMenu();//show options

        choice = getch();//get a character from the input buffer

        system("@cls");//clear screen

        switch (choice)
        {
            case '1':   printf("\n\tSaving All Changes...\n");
                        saveCatalogToFile();
                        printf("\n\tSaving Complete...\n");
                        system("pause");
                        break;
            case '2':   printf("\n\tLoading last save...\n");
                        if(loadCatalogFromFile())//if a catalog datafile exists....
                            printf("\n\tLoading Complete...\n");
                        system("pause");
                        break;
            case 'r':   //printf("\n\tYou chose to quit\n");
                        sentinel=-1;
                        break;
            case 'R':   //printf("\n\tYou chose to quit\n");
                        sentinel=-1;
                        break;
            default:
                    printf("\n\tYou have entered an option that is not in the menu\n");
                    printf("\n\tReturning to the save menu in %.2lf seconds\n",pauseDuration/1000.00);
                    pause(pauseDuration);
                    break;


        }

        system("@cls");
    }

}

void showMainMenu()
{
    int animationDelayMS=50;
    system("color F1");//set background color to bright white
    SetColor(13);//change foreground color of text
    //Ascii art generated at:http://patorjk.com/software/taag/#p=display&h=1&v=1&f=Doom&t=Main%20Menu%20
    pause(animationDelayMS);printf("___  ___        _         ___  ___                     \n");
    pause(animationDelayMS);printf("|  \\/  |       (_)        |  \\/  |                     \n");
    pause(animationDelayMS);printf("| .  . |  __ _  _  _ __   | .  . |  ___  _ __   _   _  \n");
    pause(animationDelayMS);printf("| |\\/| | / _` || || '_ \\  | |\\/| | / _ \\| '_ \\ | | | | \n");
    pause(animationDelayMS);printf("| |  | || (_| || || | | | | |  | ||  __/| | | || |_| | \n");
    pause(animationDelayMS);printf("\\_|  |_/ \\__,_||_||_| |_| \\_|  |_/ \\___||_| |_| \\__,_| \n");
    SetColor(3);;//change foreground color of text
    pause(animationDelayMS);printf("\n\n1. List all books in Catalog\n");
    pause(animationDelayMS);printf("2. Add a new book\n");
    pause(animationDelayMS);printf("3. Manually Save or Revert to last save\n");
    pause(animationDelayMS);printf("Q. Quit    \n");
    pause(animationDelayMS);printf("\nPlease select an option...");
}

void showSaveLoadMenu()
{
    int animationDelayMS=100;
    SetColor(12);
    pause(animationDelayMS);printf("\n\tSave / Revert to last save...\n");
    pause(animationDelayMS);printf("\t1. Save Changes\n");
    pause(animationDelayMS);printf("\t2. Load Data from Last save\n");
    pause(animationDelayMS);printf("\tR. Return to main menu    \n");
    pause(animationDelayMS);printf("\n\tPlease select an option...");
}

//pauses execution
void pause(int milliseconds)
{
    clock_t now = clock();
    while(clock()< now+milliseconds);

}

void exitProgramMenu()
{
    printf("\nExiting program in 2 seconds...\n");
    pause(2000);

}

void printAllBooksUserInteraction()
{
    printf("\nPrinting all books\n");
    printAllBooks();
    system("Pause");

}

void SaveLoadUserInteraction()
{
 runSaveLoadMenu();
}

void AddNewBookUserInteraction()
{
    char    theTitle[50];
    char    theAuthor[50];
    int     theYear;

    Book newBook;

    printf("\nEnter the Book's Title...\n");
    fflush(stdin);
    gets(theTitle);

    printf("\nEnter the Author's Name...\n");
    gets(theAuthor);

    printf("\nEnter Year\n");
    scanf(" %d",&theYear);

    strcpy(newBook.Title,theTitle);
    strcpy(newBook.Author,theAuthor);
    newBook.Year=theYear;
    newBook.isOnLoan=false;

    int catalogLocation = addBook(newBook);
    SetColor(0);
    printf("\nNew Book Created:\n");
    printBookByLocation(catalogLocation);
    system("pause");

}
//See:https://stackoverflow.com/questions/29574849/how-to-change-text-color-and-console-color-in-codeblocks
void ClearConsoleToColors(int ForgC, int BackC)
{
    WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
    COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
    DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
    CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
    SetConsoleTextAttribute(hStdOut, wColor);
    if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
    {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
    }
 return;
}

//See:https://stackoverflow.com/questions/29574849/how-to-change-text-color-and-console-color-in-codeblocks
void SetColor(int ForgC)
{
     WORD wColor;
     //This handle is needed to get the current background attribute

     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     //csbi is used for wAttributes word

     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
          //To mask out all but the background attribute, and to add the color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
}


© 2020  Vedesh Kungebeharry. All rights reserved. 

Mini Internal Assessment Example

In this post , we observe some code which establishes a menu driven interface and shows we can implement data processing from the menus.

This code will be demonstrated in class tomorrow.

See the code below:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
/*
Demonstrates a 2 level menu with
a simple data processing cycle

When faced with the main menu, select 1 then 1 again to
execute the process of calculating area.


Author: Vedesh Kungebeharry
*/


//constants
const double Pi=3.14;


//global static  variables
char choice;


//function declarations
void    initialization();
void    showMainMenu();
void    showMathMenu();
void    runMainMenu();
void    runMathMenu();
void    pause();
void    exitProgram();
void    AreaOfCircleUserInteraction();
double  AreaOfCircle(double radius);

//main flow of control from process to process
int main()
{

    initialization();
    runMainMenu();
    exitProgram();

    return 0;
}


/*
*initialize all instance variables and arrays here
*
*/
void initialization()
{
    choice = '_';
}

//displays the main menu and accepts input
void runMainMenu()
{
    int sentinel=0;//used to break  out of our menu loop
    while (sentinel>=0)//loop menu here
    {
        showMainMenu();//display menu text

        choice = getch();//get a character from the input buffer

        system("@cls");// clear screen after getting input

        switch (choice)//based on the choice take the desired action
        {
            case '1':   printf("\nYou chose Option 1: Math Calculations\n");
                        runMathMenu();//displays the math sub menu and accepts input
                        break;
            case '2':   printf("\nYou chose option 2\n");
                        break;
            case '3':   printf("\nYou chose option 3\n");
                        break;
            case 'q':   printf("\nYou chose to quit\n");
                        sentinel=-1;//update the sentinel so that looping will cease
                        break;
            case 'Q':   printf("\nYou chose to quit\n");//cease if upper case
                        sentinel=-1;
                    break;
            default:
                    printf("\nYou have entered an option that is not in the menu\n");
                    break;


        }
        if(sentinel>=0)//if we have continued regular execution , continue looping
        {
            printf("\nreturning to main menu in 2 seconds...\n");
            pause(2000);
            system("@cls");
        }

    }



}

//shows and accepts input for the math sub menu
void runMathMenu()
{
    int sentinel=0;
    while (sentinel>=0)
    {
        showMathMenu();//show options

        choice = getch();//get a character from the input buffer

        system("@cls");

        switch (choice)
        {
            case '1':   printf("\nYou chose option 1: Area\n");
                        AreaOfCircleUserInteraction();//start interaction to calculate area
                        break;
            case '2':   printf("\nYou chose option 2\n");
                        break;
            case 'r':   printf("\nYou chose to quit\n");
                        sentinel=-1;
                        break;
            case 'R':   printf("\nYou chose to quit\n");
                        sentinel=-1;
                        break;
            default:
                    printf("\nYou have entered an option that is not in the menu\n");
                    break;


        }
        printf("\nreturning to Math menu in 2 seconds...\n");
        pause(2000);
        system("@cls");
    }

}

void showMainMenu()
{
    printf("1. Option 1: Math Calculations\n");
    printf("2. Option 2\n");
    printf("3. Option 3\n");
    printf("Q. Quit    \n");
    printf("\nPlease select an option...");
}

void showMathMenu()
{
    printf("1. Area of circle\n");
    printf("2. Volume of Circle\n");
    printf("R. Return to main menu    \n");
    printf("\nPlease select an option...");
}

//pauses execution
void pause(int milliseconds)
{
    clock_t now = clock();
    while(clock()< now+milliseconds);

}
//prompt user to enter data and output results
void AreaOfCircleUserInteraction()
{
    double area,radius=-999.99;
    printf("Enter the radius...");
    scanf(" %lf", &radius);
    area=AreaOfCircle(radius);
    printf("\nThe area of a circle of radius \t%.2lf is \t%.2lf\n\n",radius,area);
    system("pause");

}
//helper function to calculate area
double AreaOfCircle(double radius)
{
    return Pi*radius*radius;
}
//exit gracefully
void exitProgram()
{
    printf("\nExiting program in 2 seconds...\n");
    pause(2000);

}



© 2019  Vedesh Kungebeharry. All rights reserved.