Algorithm Development and Piece-Wise Functions in C Programming, Schemes and Mind Maps of Computer Science

A comprehensive guide to algorithm development and implementation using c programming. It covers the four-step process of algorithm development, including working through examples, writing down steps, generalizing steps, and testing the algorithm. The document also demonstrates the use of if/else statements in c programs for conditional execution and provides practical examples of implementing algorithms for various tasks, such as determining even or odd numbers, calculating profit or loss, and finding the area and perimeter of a rectangle.

Typology: Schemes and Mind Maps

2021/2022

Uploaded on 10/23/2024

aznia-patrick
aznia-patrick šŸ‡µšŸ‡°

3 documents

1 / 16

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
COMSATS University Islamabad
Course: Introduction to Computer Programming
(CSC-141)
Instructor: Engr. Imtiaz Ur Rehman
Student:
ASSESSMENT
In-Lab Performance:
Data Presentation (4) Data Analysis (4) Writing Style (4)
Total: /
Instructor’s remarks:
Lab # 02 Basic Steps for Algorithm Development and Piece-Wise
Functions using
if/else Statement
Objectives:
2
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Algorithm Development and Piece-Wise Functions in C Programming and more Schemes and Mind Maps Computer Science in PDF only on Docsity!

COMSATS University Islamabad

Course: Introduction to Computer Programming

(CSC-141)

Instructor: Engr. Imtiaz Ur Rehman

Student:

ASSESSMENT In-Lab Performance:

Data Presentation (4) Data Analysis (4) Writing Style (4)

Total: / Instructor’s remarks: Lab # 02 Basic Steps for Algorithm Development and Piece-Wise Functions using if/else Statement

Objectives:

ļ‚· Learn to develop algorithms for different computational problems

ļ‚· Learn basic input-out in C using printf() and scanf() functions

ļ‚· Learn basics of conditional execution using if/else statements

Required Tools:

Software Tools:

ļ‚· Code Blocks IDE or similar.

Pre-Lab Reading 1: The 4-Step Process of Algorithm Development

Step 1: Work an Example Yourself

The first step in trying to design an algorithm is to work at least one instance of the problem— picking specific values for each parameter—yourself (by hand). Often this step will involve drawing a diagram of the problem at hand, in order to work it precisely. The more precisely you can perform this problem (including the more precisely you can draw a diagram of the situation if applicable), the easier the remainder of our steps will be. A good example of the sort of picture you might draw would be the diagrams drawn in many science classes (especially physics classes). The figure shows multiple copies of the box for this step layered one on top of the other, as you may need to perform this step multiple times to generalize the algorithm properly. Figure 0-1 The 4-Step Process for Algorithm Development One of the examples of an algorithm that we mentioned early in this chapter was determining if a number is prime. If you were trying to write a function to determine if a number is prime, your first step would be to pick a number and figure out if it is prime. Just saying "ok, I know 7 is prime," is not of much use—you just used a fact you know and did not actually work out the problem. For a problem such as this one, which has a "yes or no" answer, we probably want to work at least one example that comes up with a "yes" answer, and one that comes up with a "no" answer. Another example would be if we wanted to write a program to compute x raised to the y power. To do Step 1, we would pick particular values for x and y , and work them by hand. We might try x = 3 and y = 4, getting an answer of 3^4 = 81. If you get stuck at this step, it typically means one of two things. The first case is that the problem is ill- specified —it is not clear what you are supposed to do. In such a situation, you must resolve how the problem should be solved before proceeding. In the case of a classroom setting, this resolution may require asking your professor or TA for more details. In an industrial setting, asking your technical lead or customer may be required. If you are solving a problem of your own creation, you may need to think harder about what the right answers should be and refine your definition of the problem. The second case where Step 1 is difficult is when you lack domain knowledge —the knowledge of the

we executed to solve them, we are ready to try to generalize those steps into an algorithm. In our Step 2 steps, we solve particular instances, but now we need to find the pattern that allows us to solve the whole class. This generalization typically requires two activities. First, we must take particular values that we used and replace them with mathematical expressions of the parameters. Looking at our Step 2 steps for computing 3^4, we would see that we are always multiplying 3 by something in each step. In the more general case, we will not always use 3— we are using 3 specifically because it is the value that we picked for x. We can generalize this slightly by replacing this occurrence of 3 with x : The second common way to generalize steps is to find repetition—the same step repeated over and over. Often the number of times that the pattern repeats will depend on the parameters. We must generalize how many times to do the steps, as well as what the steps are. Sometimes, we may find steps which are almost repetitive, in which case we may need to adjust our steps to make them exactly repetitive. In our 3^4 example, our multiplication steps are almost repetitive—both multiply x by "something," but that "something" changes (3 then 9 then 27). Examining the steps in more detail, we will see that the "something" we multiply is the answer from the previous step. We can then give it a name (and an initial value) to make all of these steps the same: Now, we have the same exact step repeated three times. We can now contemplate how many times this step repeats as a function of x and/or y. We must be careful not to jump to the conclusion that it repeats x times because x = 3—that is just a coincidence in this case. In this case, it repeats y - 1 times. The reason for this is that we need to multiply 4*3s together, and we already have one in n at the start, so we need y - 1 more. This would lead to the following generalized steps: We need to make one more generalization of a specific value to a function of the parameters. We start with n = 3; however, we would not always want to start with 3. In the general case, we would want to start with n = x :

Sometimes you may find it difficult to see the pattern, making it hard to generalize the steps. When this happens, returning to Steps 1 and 2 may help. Doing more instances of the problem will provide more information for you to consider, possibly giving you insight into the patterns of your algorithm. Step 4: Test Your Algorithm After Step 3, we have an algorithm that we think is right. However, it is entirely possible that we have messed up along the way. The primary purpose of Step 4 is to ensure our steps are actually right before we proceed. To accomplish this, we test our algorithm with different values of the parameters than the ones we used to design our algorithm. We execute our algorithm by hand and compare the answer it obtains to the right answer. If they differ, then we know our algorithm is wrong. The more test cases (values of parameters) we use, the more confident we can become that our algorithm is correct. Unfortunately, it is impossible to ensure that our algorithm is correct by testing. The only way to be completely sure that your algorithm is correct is to formally prove its correctness (using a mathematical proof), which is beyond the scope of this specialization. One common type of mistake is misgeneralizing in Step 3. As we just discussed, one might think that the steps repeated x times because x = 3 and the steps repeated 3 times. If we had written that down in Step 3, our algorithm would only work when x = y – 1; otherwise we would count the wrong number of times and get the wrong answer. If that were the case, we would hopefully detect the problem by testing our algorithm by hand in Step 4. When we detect such a problem, we must go back and re-examine the generalizations we made in Step 3. Often, this is best accomplished by returning to Steps 1 and 2 for whatever test case exposed the problem. Redoing Steps 1 and 2 will give you a concrete set of steps to generalize differently. You can then find where the generalization you came up with before is wrong, and revise it accordingly. Another common type of mistake is that there are cases we did not consider in designing our algorithm. In fact, in our x ^ y example, we did not consider what happens when y = 0, and our algorithm handles this case incorrectly. If you execute the algorithm by hand with x = 2, y = 0, you should get 2^0=1; however, you will get an answer of 2. Specifically, you will start with n = x = 2. We would then try to count up from 1 to 0 – 1 = –1, of which there are no numbers, so we would be done counting right away. We would then give back n (which is 2) as our answer. To fix our algorithm, we would go back and revisit Steps 1 and 2 for the case that failed ( x = 2, y = 0). This case is a bit tricky since we just know that the answer is 1 without doing any work ( x ^0=1 for any x ). The fact that the answer requires no work makes Step 2 a little different—we just give an answer of 1. While this simplicity may seem nice, it actually makes it a little more difficult to incorporate it into our generalized steps. We might be tempted to write generalized steps like these: These steps check explicitly for the case that gave us a problem ( y = 0), give the right answer for that case,

immediately after the expression. C does not have a then keyword (although some languages do), however, this block of code serves the same purpose regardless of the syntactic particulars of the language—it is executed if the conditional expression evaluates to true. After the ā€œthenā€ block, we have the keyword else, followed by the ā€œelseā€ block. This block of code is executed if the conditional expression evaluates to false. When your execution arrow reaches an if statement, evaluate the conditional expression. Evaluating this expression proceeds just like evaluating any other expression. If the result is true, move the execution arrow immediately inside the ā€œthenā€ block and continue executing statements as usual. When your execution reaches the close curly brace that ends the ā€œthenā€ block, skip over the else block, placing your execution arrow immediately after the close curly brace of the ā€œelseā€ block, and continue executing statements from there. If the result of the conditional expression is false, you should instead skip the ā€œthenā€ block and execute the ā€œelseā€ block. Move your execution arrow into the start of the ā€œelseā€ block, and continue executing statements from there. When your execution arrow reaches the close curly brace that ends the ā€œelseā€ block, simply move it past that curly brace (which has no effect—it just denotes the end of the block) and continue executing statements normally. C permits if with no else, which is equivalent to an empty ā€œelseā€ block (as if the programmer had written else {}). If you execute an if with no else, then simply imagine the empty ā€œelseā€ block. If the conditional expression evaluates to true, you should execute the ā€œthenā€ block as previously described, however, there is no ā€œelseā€ block to skip. Instead, continue executing statements immediately after the end of the ā€œthenā€ block (skipping over the nonexistent ā€œelseā€ block). If the conditional expression evaluates to false, then skip the ā€œthenā€ block, and execute whatever statements follow it (doing nothing for the ā€œelseā€ block). if/else statements may be nested—one (or more) may occur in the ā€œthenā€ or ā€œelseā€ block of another if/else statement. When you encounter nested statements, the same rules apply. The inner statement is just one of the (possibly) many statements in the block, and is executed according to its rules—the condition is evaluated, whichever of the ā€œthenā€ or ā€œelseā€ blocks is appropriate is executed, and then execution continues after the end of the ā€œelseā€ block. When the execution arrow reaches the end of the outer ā€œthenā€ or ā€œelseā€ block, it behaves no differently than if there were no inner if statement. The next video demonstrates the execution of some if/else statements. In Lab Tasks: Task 1: Develop an Algorithm Following figure shows a pattern of squares generated for different input values of N (for N=0 to N=5). Develop a general algorithm to fill in the grid for any input N. Use the 4 step process that was discussed in the class (and is given below for reference) The four – step algorithm development process:

1. Work an example yourself.

2. Write down what you just did.

3. Generalize your steps.

4. Test your algorithm.

Task 2: Write a C Program to Implement a Piecewise Function Write a C program for following piecewise function. Program must take input from user and calculate and print the function result on screen. ﻟ I š‘“[š‘›] = āŖ I

š‘›^2 āˆ’ 7, 3 ≤ š‘› ≤ 10

return 0; }

Task 4:

#include<stdio.h> #include<stdlib.h> int main() { float cost_price, selling_price, profit, loss; printf("Enter the cost price of an item: "); scanf("%f", &cost_price); printf("Enter the selling price of an item: "); scanf("%f", &selling_price); if (selling_price > cost_price) { profit = selling_price - cost_price; printf("We earn %.2f profit by selling item.", profit);

else if (selling_price < cost_price) { } else { }

Task 5:

#include <stdio.h> #include <stdlib.h> int main() { float length, width, area, perimeter; printf("Enter length of the Rectangle\n"); scanf("%f", &length); printf("Enter width of the Rectangle\n"); scanf("%f", &width); area = (length * width); perimeter = 2 * (length + width); if(area > perimeter) { printf("yes, area(%0.2f) is greater than its perimeter(%0.2f)\n", area, perimeter); } else { printf("Area(%0.2f) is not greater than its perimeter(%0.2f)\n", area, perimeter); }

else { } printf("Triangle is valid."); printf("Triangle is not valid."); ret urn 0; }

Task 8:

Post Lab Task: Write a program that takes integer input from user and tells (displays on the output console screen) whether it is even or odd. Performance: #include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); // true if num is perfectly divisible by 2 if(num % 2 == 0) printf("%d is even.", num); else printf("%d is odd.", num); return 0; }