Cosc 104 Lec Iv
Cosc 104 Lec Iv
REPETITION LOGIC
These structures play a crucial role in determining how a program flows based on specific
conditions. Here are the key concepts and examples:
- Sequential logic follows a linear flow, executing instructions in the order they are given.
- Modules are executed one after the other unless new instructions alter the sequence.
- Example: A simple program that reads input, processes data, and produces output.
#include <iostream>
int main() {
string name;
int age;
cout << "Hello, " << name << "! You were born around " << birth_year << "." << endl;
return 0;
1. We declare a `string` variable `name` to store the user's name and an `int` variable `age`
to store their age.
- **Single Alternative**:
- **Double Alternative**:
- **Multiple Alternatives**:
#include <iostream>
int main() {
int i = 20;
if (i == 10)
else if (i == 15)
else if (i == 20)
else
return 0;
In this example:
#include <iostream>
int main() {
int i = 25;
else
return 0;
In this second example, the program checks the value of `i` and prints the corresponding
message based on the specified
- The loop executes the module from `A` to `N`, incrementing by `I`.
- **Repeat-While Structure**:
#include <iostream>
int main() {
std::cout << "Iteration " << count << ": Hello, World!" << std::endl;
return 0;
In this example:
- The loop will execute 5 times, printing "Hello, World!" for each iteration.
HOMEWORK:
1. **Functions**:
- Functions are subprograms designed to perform a specific task and return a value.
int p = 0;
while (y > 0) {
if (y % 2 == 0) {
y /= 2;
x *= 2;
} else {
p += x;
y--;
return p;
```
int i = times(3, i + 2) + 1;
2. **Procedures**:
void factors(int x) {
int f = 2;
while (x != 1) {
if (x % f == 0) {
x /= f;
} else {
f++;
```
factors(i);
3. **Parameter Passing**:
- Call-by-value makes a copy of the argument, while call-by-reference passes the memory
location.
- Example:
// Code for p
4. **Benefits of Subprograms**:
Functions allow us to break down complex tasks into smaller, reusable chunks of code. We'll
cover both basic function examples and more advanced concepts.
#include <iostream>
// Function declaration
void greet() {
int main() {
// Calling the function
greet();
return 0;
- Output:
Hello there!
#include <iostream>
int main() {
int num1 = 5;
displayNum(num1, num2);
return 0;
- Output:
- A function that computes the sum of two integers and returns the result:
#include <iostream>
return a + b;
int main() {
return 0;
- Output:
Sum: 30
4. **Function Templates**:
#include <iostream>
T max(T a, T b) {
return (a > b) ? a : b;
int main() {
return 0;
- Output:
Max int: 20
HOMEWORK: