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.

Exercises:


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. 

Video:Evaluating Sources of Information

See the following objective content and related videos

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.

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

Video: Data and Information

See the following objective content and related videos

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.

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

Stacks and Queues Discussion and Variant implementation

This post is intended for use in class and review. In this lesson we will observe some multiple choice question examples to provoke thoughts on the fundamental principles governing stack and queue operations.

Note that the multiple choice questions are not included on this website.

Discussion: Stacks and Queues

If a stack is implemented using a one-dimensional array and the top of the stack is always found at location 0 in the array, how would you implement push and pop?

That is, at the end of any push or pop operation, the top of the stack is stored at location 0.

Write separate algorithms for your push and pop operations.


After considering the scenario above do you think it’s possible to implement a stack using the wrap-around technique (that was used in the implementation of a queue ) to omit the intermediate copying of elements? Consider this scenario where the first element that was pushed onto the stack goes into location 0, and every time a pop operation occurs top is incremented (unless the stack is empty) , and every time a push operation occurs top is decremented.

Justify your conclusion.


Write an algorithm which can be used to reverse the elements of a queue by using a stack. Accomplish this task by only using valid stack and queue operations.


Assuming you are required to write a c program that must use two separate stacks and five separate queues , what modifications would you need to make to the coded implementations that will already demonstrated in class.


Write the algorithm for the dequeue operation in a traditional queue with no wrap around, i.e every time an element is dequeued , all elements of are copied down one location such that location 0 in the array stores the new head of the queue.


© 2020  Vedesh Kungebeharry. All rights reserved. 

Practical Exercise – Range names, Advanced Filters, Linking to other sheets

Please download this file : https://drive.google.com/file/d/1tMYafnf_j6TtAvBaGCARwVpI1lPQe0MQ/view?usp=sharing

And complete the following tasks as demonstrated by the videos at the end of this post:

Task Task Instructions
1Apply a range name to the table used in the vlookup. Name this range “PriceList”
2Update the Vlookup function to use the “PriceList” Name range
3Use a range name for the percentage and update the formula which calculates the vat
4Insert a new row for “Cinnamon rolls” which sold 2000 items
5Insert  a new column “Hot Seller?”. This column will contain a value of “Yes” if more than 1500 Items were sold for the month and “NO” otherwise. Implement this using an “if” function.
6Apply a custom sort, First sort by “Hot Seller” Descending then by “revenue per item” descending
7Apply an advanced filter using to show items that weren’t hot sellers but sold more than 1000 items
8Create a pie chart showing  the net revenue per item
9Create a barchart showing both the revenue per item and the vat per item
10Move the tables and constants to a new sheet, “Constants”. i.e the vat value and price list. Observe how the formula for the vlookup has changed.

Add a new column, “Discounted price” to the sales table .  Add a new constant called Discount to the Constants sheet with a value of 6%.  Use this value to calculate the discounted price per item in the sheet.

See the video demonstrations below for the tasks outlined above.

The above video was continued in another class session:

© 2020  Vedesh Kungebeharry. All rights reserved. 

Spreadsheet Exercise

Use the following sheet to accomplish the tasks that follow:

https://drive.google.com/file/d/1lsyXnA7q5VWMpAPu8pDG-4lRI6DmhXoI/view?usp=sharing

Tasks

Task NumberTask Instructions
1Ensure that the data in  columns in the sales sheet fit on 1 page. To do this: Change the layout of the page to “Landscape” (Page Layout–> orientation)
2Change the view to “Normal”
3Add borders for the table: Sales for the month of june
4Format the vat rate as a percentage (use the number grouping from the home menu ribbon.
5Format the price in the Price List table  as currency to 2 decimal places
6Apply a similar formatting for Price Per Item
7Use a vlookup to list the Price Per Item
8Use a formula/function to fill in the Revenue Per Item . Format this column as currency
9Calculate the vat Per item to be paid for each item row USING the vat rate provided
10Show the total revenue  and the total vat to be paid. You will need to choose the cell locations to display this information and add lables yourself.

Note that these tasks can also be found on the second sheet within the spreadsheet file for easy reference

Solution

A solution from a previously recorded class is shown below:

© 2020  Vedesh Kungebeharry. All rights reserved. 

Advanced formulae – Spreadsheets

In this tutorial, we seek to use the basic arithmetic operations addition subtraction multiplication and division to accomplish complex tasks.

Usually when using a computer system to represent addition subtraction multiplication and division we use the following symbols respectively:

Addition

The plus sign : +

Hold shift and press the plus sign
Subtraction

The hyphen: –

Hyphen Key
Multiplication

The asterisk : *

Asterisk key
Division

The front slash: /

Front slash key.

Tutorial:

Click the link below to download the file. Do not open the documents using Google Sheets, rather download the documents and open it with your desktop application of Microsoft Excel:

https://drive.google.com/file/d/1lubYKdD70AAx_9eD2BeoBb8FbjKcd9Wq/

This tutorial demonstrates how a spreadsheet can be used to perform a complex calculation. The complex calculation chosen is the quadratic formula.

Note that you do not need to have an intimate understanding of the quadratic formula. All you will need to do is to break down the quadratic formula into its sub parts, and represent those parts using functions and formulas in your spreadsheet software.

This Excel document contains two worksheets. Use the first worksheet to fill in formulas and functions which can be used to calculate the items shown in the labels.

How to fill the sheet:

A copy of the sheet is shown below:

Advanced formulae tutorial

Start filling in the correct formula for each level shown in the sheet. For example, you would start with the label negative B an insert a formula in the cell next to the label which would calculate the volume negative B. In this case you would enter =-1*C10 Into cell location H3.

Continue following all the way down for b squared, 4ac …. All the way until you have calculated root 1 and root 2.

The second sheet contains notes and solutions to the first worksheet.

Homework

Complete the challenge listed in the sheet above. Ensure that you do not use any pre-calculated values.

Video Tutorial

Updated 2021 November 8th

-Fixed a spelling error

-Improved formatting

-Added Tutorial Video

© 2020  Vedesh Kungebeharry. All rights reserved. 

Solution to Queue Exercise

Implementation using flowgorithm

Download the file here: https://drive.google.com/file/d/1adiH9SG9vbXVNBydWC5tKR1_9i9y9ZPj/view?usp=sharing

Coded Implementation in C

Code is split into 3 files:

main.c

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

int main()
{
    char userInput[5];
    int data = -9999;



    puts("\nEnter a valid command: add, remove, peek , exit\n");
    scanf("%s", userInput);
    while(strcmp("exit",userInput)!=0)
    {
        if (strcmp("add",userInput)==0)
        {
            puts("\nEnter data to add to the end of the queue\n");
            scanf("%d", &data);
            enqueue(data);
        }
        else if (strcmp("remove",userInput)==0)
        {
            data = dequeue();
            printf("\nremoved %d from the front of the queue\n",data);
        }
        else if (strcmp("peek",userInput)==0)
        {
            data = peek();
            printf("\npeeking at front : %d\n",data);
        }
        else
        {
            puts("\nInvalid command entered. Ensure that your command is in lowercase\n");
        }

        puts("\nEnter a valid command: add, remove, peek , exit\n");
        scanf("%s", userInput);
    }
    puts("\nExiting Program...\n");



    return 0;
}

Queue.h

#include <stdio.h>
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED

void enqueue(int newData);
int dequeue();
int peek();



#endif // QUEUE_H_INCLUDED

Queue.c

#define MAX_SIZE 5

int sizeOfQueue = 0;
int head = 0;
int tail = -1;

int queueData[MAX_SIZE];



void enqueue(int newData)
{
    if (sizeOfQueue==MAX_SIZE)
        puts("Error in \"void enqueue(int newData)\". Queue is full" );
    else
    {
        queueData[++tail]= newData;
        sizeOfQueue++;
    }


}

int dequeue()
{
    int result=-999;
    if (sizeOfQueue==0)
        puts("error in \"int dequeue()\". Queue is empty, -999 returned");
    else
    {
        result=queueData[head++];
        sizeOfQueue--;
    }
    return result;

}

int peek()
{
    int result=-999;
    if (sizeOfQueue==0)
        puts("error in \"int peek()\". Queue is empty, -999 returned");
    else
        result=queueData[head];


    return result;

}


© 2020  Vedesh Kungebeharry. All rights reserved.