Stages in problem solving

Problem Definition

This is a precise and concise definition of a problem stating what needs to happen to transform from the current state of things to the desired future state. The problem definition should address the inputs to the problem and the desired outcome.

Problem Analysis

We determine:

Input

  • what data needs to be recorded/managed by our solution;

Processing

  • What events need to occur during the use of the solution,
  • the rules for manipulating/processing the data in our solution;

Output

  • and what data and files our solution needs to deliver to the end user and save for future use.

Identify and evaluate possible solutions

Multiple approaches may be used to solve the problem, thus many solutions may be generated.

Identify and evaluate possible solutions

Multiple approaches may be used to solve the problem, thus many solutions may be generated. Each solution’s comparative strength and weakness is documented at this point.

Select and justify the optimal solutions;

Of all solutions generated, we select the one which is most optimal and best suited to solve the problem.

The optimal solution is chosen based on criteria which point to the most efficient solution based on speed, storage capacity and generally how good the solution is suited against the problem statement/definition.

A detailed algorithm of the best solution is the output of the process.

Implementation and review

Implementation: The algorithm is implemented in code and placed in the environment of its intended and made accessible to users.

Review : To determine any unforeseen issues:

  • The implementation is observed in its environment. 
  • Feedback is elicited from users.

After the initial review phase, any major issues are fixed. 

We compare our solution back to our original problem statement to verify the problem has indeed been solved.

Implementation Review then continues in the form of maintenance  where additional feedback is gathered to improve the solution which is implemented at a reasonable future date.

Summary

Problem definition – A concise definition of the problem is made which decribes what the future solution should do

problem analysis – determine all details that are needed to solve the problem, e.g processes, procedures, data etc.

Identify and evaluate possible solutions – generate many solutions and learn each solutions strength and weaknesses compared to each other.

Select and justify the optimal solutions – choose the optimal solution based on criteria which point to the most efficient solution based on speed and storage capacity.

Implementation and review – the solution is created and reviewed to determine any issues that prevents it from solving the problem. The issues, if any are fixed so that the problem is now completely solved.

© 2020 Vedesh Kungebeharry.  All rights reserved.

CAPE 2012 U1 Q3 Solution

2012 U1 Q3

Part A

Algorithms are used to solve computational problems and are a technique for precisely documenting the solution.

Part B


i) Bounded, since the number of iterations are constant every time the algorithm is applied. In this case, the loop is executed 16 times.

ii) Unbounded, since the number of iterations is not set and is dependent on the value of a sentinel variable, in this case X     

Part C) 

START
rcount, bcount,gcount,ncount <--0
for i<-- 1 to 150 do
	input vote
	if (vote = "red") then
		rcount++
	else if (vote = "green") then
		gcount++
	else if (vote = "blue") then
		bcount++
	else
		ncount++
	endif
endfor

output "total votes for color  = " + rcount+gcount+bcount
output rcount " voted for red"
output bcount " voted for blue"
output gcount " voted for green"
END

Part d

(Flowgorithm file here: https://drive.google.com/drive/folders/1pazPgOeE2OA75OPIpUScROX302NyBhrX?usp=drive_link)

Alternatively, in Pseudocode:

© 2020  Vedesh Kungebeharry. All rights reserved.

Mail Merge

A mail merge is the term used when a database of recipients and other fields are placed (or merged) onto a template letter to produce a mass mailing.

Basically , a template document is created using a list of names. e.g:

Template Document (Primary Document)

List of names (Data source or Secondary Document)

Steps to create a mail merge

These steps vary silghtly from version to version of microsoft word, but the principle is the same. In this case, I’m using the version of microsoft word as current as January 2020.

  1. Create a new document
  2. write and format the basic idea for your letter
  3. save your document. This document is your Primary Document (Template).
  4. Click on Mailings -> Select recipients -> Type new list.
  5. Use the “New Entry” button to add new records. Add as many as you need.
  6. Click on “ok”. Save your list. This document is your secondary document (Data Source).
  7. Finally, from the mailings ribbon, click on Finish and merge -> Edit individual documents. This creates a new document from the previous two. This document is your Merged document (Mass mailing).

Thats it!

© 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. 

CSEC Video Revision

CSEC INFORMATION TECHNOLOGY – YOUTUBE VIDEO LIST

 These videos were chosen for each topic because they cover the subject matter in a relevant context. They definitely were not created specifically for the CSEC Syllabus, however , they do address the fundamental concepts in real world scenarios.

 OBJECTIVE/TOPICLINK
Explain the concept of Information Technology;Definition and scope Information Technology.https://www.youtube.com/watch?v=Z0A7OMkYQf8
Distinguish among the major types of computer systems in terms of processing speed, storage and portabilityMajor types:(a)Super Computers (for example, Cray).(b)Mainframes (for example,IBM zEnterprise System).(c)Desktop systems.(d)Mobile devices (for example, laptops, notebooks, netbooks, smartphones, tablets and game consoles).(e)Embedded devices (for example,special-purpose systems such as controllers in microwaves, car ignition systems, answering machines).Types of computers:https://www.youtube.com/watch?v=uD0acIhi8xE

What is a super computer:https://www.youtube.com/watch?v=utsi6h7IFPs

Using Supercomputers:https://www.youtube.com/watch?v=yvbSX–LOko


Explain the functions of the major hardware components of a computer system;Major  components:  input, central  processing unit,Primary memory   (RAM and ROM),secondary storage, output.(a)Secondary  storage devices:  hard disk,magnetic   tape, flash   drive, memorycard, and optical disks (CD, DVD and Blu-Ray).(b)Units  of storage:  bits,bytes,  kilobytes,megabytes, gigabytes, terabytesData Processing (IPOS) Cycle:https://www.youtube.com/watch?v=j0XOLp_PbgA
Ram and Rom: https://www.youtube.com/watch?v=XY18amKzOvA
Storage: https://www.youtube.com/watch?v=OsEDJM9NuGA











Units: https://www.youtube.com/watch?v=HRmfXA4EUBs
Explain how the major hardware components of a computer system interrelate;Input processing output storage (IPOS) cycle.Covered in an earlier video:https://www.youtube.com/watch?v=j0XOLp_PbgA
Evaluate the relative merits of cloud storage and local storage;Definition of cloud and local storage.Assessment criteria: capacity, cost, accessibility; security issues.Cloud: https://www.youtube.com/watch?v=gu4FYSFeWqg
Select appropriate input/output devices to meet the needs of specified applications;Associate the following devices with suitable applications:(a)Input:Optical mark reader (OMR), character readers (OCR,MICR),mouse,joystick,barcode reader, document scanner,light-pen, touch terminals,voice response unit, Touch Screens (tablets, point of sale, ATM),keyboard,digital camera,biometric systems, sensors, remote control, sound capture,pointing  devices,webcam.(b)Visual output:Printers (laser, inkjet, dot matrix, thermal, plotters, 3D Printers),microfilm.(c)Audible output: speakers,headphones,earphones.Omr:https://www.youtube.com/watch?v=Yd8PWYCT7w8
OCR : https://www.youtube.com/watch?v=jO-1rztr4O0

Micr : https://www.youtube.com/watch?v=LX-FyRcdUmM
Mouse: https://www.youtube.com/watch?v=eccSwn9QVxo
printers:https://www.youtube.com/watch?v=JEVurb1uVFA

Explain the role of the different types of software in computer operation;System Software: Operating System, Utilities.Application software: general-purpose and special-purpose; integrated package; source: off the shelf, custom-written, and customized. 
Discuss the relative merits of the various types of user interface;Hardware: touch screens, specializedkeyboards.Software: command line, menu-driven, graphical user, touch. 
Evaluate the suitability of a given computer system for a specific purpose;Basic knowledge of system specification needed for purposes such as: to run a video game, web browsing, graphic design, video editing, and desktop publishing. Criteria:(a)Processing speed (CPU type and speed); (b)Memory (RAM);(c)Secondary storage (capacity and speed);(d)Types of software; and,(e)Input/Output devices.https://www.youtube.com/watch?v=eqrJmstbzu4
RAM:https://www.youtube.com/watch?v=PVad0c2cljo

Troubleshoot basic computer hardware problems;Cable problems (for example, loose cables).Monitor problems (for example, improperly adjusted monitor controls).Printer problems (for example, changing printer cartridges).Battery problems (for example, loose or dead battery). 
Distinguish between data and information;Data as raw unprocessed facts;information as processed data.Sources of data and information (people, places and things).Document types: turnaround document, human-readable and machine-readable forms; hard copy, and soft copy.Data and information https://www.youtube.com/watch?v=sIjSY05JE9Q
Evaluate the reliability of information obtained from online sources;Evaluation of information retrieved electronically for authenticity, currency, relevance, and bias.https://www.youtube.com/watch?v=EyMT08mD7Ds
Differentiate between validation and verification of data;Difference between validation and verification. 
Identify appropriate validation and verification checks given a particular scenario;Methods of validation: range check,reasonableness checks, data type checks, consistency checks, presence, format and length. 
Select appropriate file organisation for particular application.File access methods: sequential, serial, direct and random.Application areas: archiving, payroll file, real time systems. 
Distinguish among types of networks;Types of networks (local area network, metropolitan area network, wide area network, mobile network).(a) Concept of mobile network as radio- based common carrier.(b) Overview of mobile networks: from 2G to current. (Knowledge of the inner workings of mobile systems is NOT required)Wireless network technologies (for example, Bluetooth, Wi-Fi, hotspot).Level of privacy (intranet, extranet, Internet).Types: https://www.youtube.com/watch?v=4_zSIXb7tLQ
Mobile:https://www.youtube.com/watch?v=1JZG9x_VOwA





Explain the functions of the basic components of a network;Basic components and functions:(a) Transmission media:(i) Wired: twisted pair, coaxial, fibre; and,(ii) Wireless: infrared, microwave, satellite.(b) Switch, router, modem. (c) Network interface card/network adapter.Hub/switch/router https://www.youtube.com/watch?v=1z0ULvg_pW8
Topologies : https://www.youtube.com/watch?v=zbqrNg4C98U
Ethernet:https://www.youtube.com/watch?v=_NX99ad2FUA
Cable: https://www.youtube.com/watch?v=qQYiwmamq38
Wireless:https://www.youtube.com/watch?v=OxiY4yf6GGg



Assess the importance of mobile communication technologies as a component of modern communication networks;Suitability of mobile networks to various applications (for example, education, commerce, and journalism). 
Explain the interrelationship among keyWeb technology concepts.World Wide WebHypertext Markup Language.Hypertext Transfer Protocol.Hyperlinks.Web Server.Web Page.File Transfer Protocol.Web Browser.Uniform Resource Locator.Upload and download. www:https://www.youtube.com/watch?v=J8hzJxb0rpc
http:https://www.youtube.com/watch?v=hExRDVZHhig


© 2019  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.

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);

}



Updates to this post

28th Sept 2023 – changed “This code will be demonstrated in class tomorrow.” to “This code will be demonstrated in class.”

© 2019  Vedesh Kungebeharry. All rights reserved.