Week 2: More Control Flow and Functions
Last updated
Last updated
The while
loop in programming is used to repeatedly execute a block of code as long as a specified condition is true.
Syntax: while (condition) { code to be executed }
When to use: Use a while
loop when you don't know in advance how many times the loop needs to run, and the loop's execution depends on a certain condition. For example, when simulating a physical system until it reaches a specific state or when reading data until the end of a file is reached.
Free fall of object from 200m above the ground:
You will see from the above example the the current height will be negative. You should improve it! How?
Break when the current height is negative. Where should you put the break?
If the initial height is increasing, i.e. to 2000 m, how will you modify the code?
The for
loop is used for iterating over a sequence of values, such as numbers, and executing a block of code for each value.
Syntax: for (initialization; condition; update) { code to be executed }
When to use: Use a for
loop when you know the exact number of iterations required or when you need to iterate through a range of values. This is commonly used in physics for numerical simulations, solving differential equations, or iterating through arrays.
We will calculate the potential energy of an object mass 5 kg at different heights.
The switch statement is a control structure in programming used for making decisions based on the value of an expression. It provides an efficient way to choose among a large number of discrete values for the expression. The switch statement can be a powerful alternative to long chains of if-else if-else statements when dealing with multiple conditions.
Advantages of the Switch Statement:
Readability: Switch statements are often more readable and concise than long if-else chains, especially when dealing with a fixed set of discrete values.
Efficiency: Switch statements can be more efficient than if-else chains because the compiler can optimize them into a jump table or lookup table, resulting in faster execution.
The do-while loop is another type of loop in programming, similar to the while loop. It is used for repetitive execution of a block of code as long as a specified condition remains true. However, unlike the while loop, the do-while loop guarantees that the block of code is executed at least once, even if the condition is false initially. The condition is checked after the code block execution.
Syntax of the do-while loop:
The code block is executed at least once before checking the condition.
If the condition is true, the loop continues; otherwise, it terminates.
Nested loops are loops placed inside other loops. They allow for more complex iterations and are particularly useful when dealing with multidimensional data or when simulating systems with multiple components or dimensions.
To calculate and print a table of projectile distances for various angles and initial velocities.
In programming, a function is a self-contained, reusable block of code that performs a specific task or set of tasks. Functions are a fundamental concept in computer programming because they help make code modular, organized, and easier to understand and maintain. By breaking down a program into smaller functions, each responsible for a particular task, you can write code that is more readable, testable, and maintainable.
Functions have several advantages:
Modularity: Functions allow you to break complex problems into smaller, more manageable parts. Each function focuses on a specific task, making the code easier to design, implement, and maintain.
Reusability: Once a function is defined, you can reuse it in different parts of your program or even in other programs. This promotes code reuse and reduces duplication.
Abstraction: Functions abstract away the implementation details of a task. When you call a function, you don't need to know how it works internally; you only need to understand its interface (the inputs and outputs).
In C programming, a function prototype is a declaration of a function that provides the compiler with essential information about the function's name, return type, and parameters before the function's actual definition. Function prototypes serve several important purposes:
Compiler Checking: Function prototypes inform the compiler about the existence and signature (return type and parameter types) of functions used in the program. This enables the compiler to check that function calls match the declared signatures.
Order Independence: Function prototypes allow you to call functions in your code before defining them. This is useful when functions call each other, as long as the prototypes are declared before the calls.
Documentation: Prototypes also serve as a form of documentation, providing other developers (and your future self) with information about the functions used in the code.
Here's how you declare and define functions in C:
Declaration (Function Prototype):
return_type
is the type of data the function will return (e.g., int
, double
, void
).
function_name
is the name of the function.
parameter_type1
, parameter_type2
, etc., are the types of parameters the function accepts.
Definition:
return_type
must match the type of value the function returns.
parameter_name1
, parameter_name2
, etc., are the names of the function's parameters.
Here's an example of a simple C function that calculates the sum of two integers:
Functions in programming can take parameters (also known as arguments) as inputs and return values as outputs. Parameters allow you to pass data to a function so that it can perform operations on that data, and return values allow functions to communicate their results back to the caller. The proper use of data types and their consistency is crucial for ensuring that functions work correctly and produce meaningful results.
Parameters are variables or values that you provide to a function when calling it. They allow functions to receive data that they can work with.
Parameters are defined within the parentheses of a function's prototype and definition.
Data types of parameters should match the expected data types in the function.
Return values are values that a function sends back to the caller.
Functions can return a single value of a specific data type.
The return value can be assigned to a variable or used directly in expressions.
Example: Solve Quadratic Equation
A void
function is a function that does not return any value. It is typically used for functions that perform a task or operation but do not need to return a result.
Write a program that inputs one five-digit number, separates the number into its individual digits and displays the digits separated from one another by three spaces each. For example, if the user types in 10300, the program should display
Write a C program to simulate the motion of a projectile under gravity. Your program should calculate the time of flight, maximum height, and range of the projectile for various initial velocities and launch angles. Use if-else
statements, a prototype function, and loops in your code. Your program should ask for user inputs including initial velocity (in m/s) and launch angle (in degrees).
The problem is not difficult. Think carefully and write a good program!
Improve your calculator program by
Instead of performing 4 basic calculations, your program also ask for operator to calculate.
As physics student, your program should display an answer with proper significant figures.