Week 10 Worksheet

Note: Try to solve these questions on your own.

Filter:
Sort:

Question 1: Find the Errors

The following program has logic and/or compiler errors. Identify 5 errors and for each error:

  1. Mention the line number where the error occurred.
  2. Rewrite the line containing the error after fixing it.

Your answer should be in the following format:

  • Line xx should be: corrected version of line xx
  • Line yy should be: corrected version of line yy

Part 1

#include <stdio.h>

int main() {
    int numbers[5];
    int sum = 0;
    float average;

    printf("Enter 5 numbers: ");

    // Loop to read input
    for (int i = 0; i <= 5; i++) {
        scanf("%d", &numbers[i]);
        sum += numbers[i];
    }

    // Calculate average
    average = sum / 5; 

    // Print the result
    printf("The average is %.2f\n", average)

    // Check for perfect score
    if (average = 100) {
        printf("Perfect Score!\n");
    }

    // End message
    printf(Program Ended);

    return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int numbers[5];
    int sum = 0;
    float average;

    cout << "Enter 5 numbers: ";

    // Loop to read input
    for (int i = 0; i <= 5; i++) {
        cin >> numbers[i];
        sum += numbers[i];
    }

    // Calculate average
    average = sum / 5; 

    // Print the result
    cout << "The average is " << average << "\n"

    // Check for perfect score
    if (average = 100) {
        cout << "Perfect Score!\n";
    }

    // End message
    cout << Program Ended;

    return 0;
}
Solution (Part 1)
1. Line 11 should be: for (int i = 0; i < 5; i++) {
2. Line 17 should be: average = sum / 5.0;
3. Line 20 should be: printf("The average is %.2f\n", average);
4. Line 23 should be: if (average == 100) {
5. Line 28 should be: printf("Program Ended");

                        
1. Line 12 should be: for (int i = 0; i < 5; i++) {
2. Line 18 should be: average = sum / 5.0;
3. Line 21 should be: cout << "The average is " << fixed << setprecision(2) << average << "\n";
4. Line 24 should be: if (average == 100) {
5. Line 29 should be: cout << "Program Ended";

                        

Part 2

#include <stdio.h>

int sum = 0;

// stores x + y in result and adds the result to the global variable sum.
add(int x, int y, int* result) {
    result = x + y;
    int sum += (x + y);
}

// returns the absolute value of x
int absolute_value(int x) {
    if (x < 0)
        return x * -1;
}

int main() {
    int x = 7;
    int y = -8;

    // change y from -8 to 8 using the function absolute_value()
    absolute_value(y);

    // store in result the value of x + y
    int result;
    result = add(y, x);

    // should print: 7 + 8 = 15.
    printf("%d + %d = %d\n", x, y, result);
}
#include <iostream>
using namespace std;

int sum = 0;

// stores x + y in result and adds the result to the global variable sum.
add(int x, int y, int* result) {
    result = x + y;
    int sum += (x + y);
}

// returns the absolute value of x
int absolute_value(int x) {
    if (x < 0)
        return x * -1;
}

int main() {
    int x = 7;
    int y = -8;

    // change y from -8 to 8 using the function absolute_value()
    absolute_value(y);

    // store in result the value of x + y
    int result;
    result = add(y, x);

    // should print: 7 + 8 = 15.
    cout << x << " + " << y << " = " << result << "\n";
}
Solution (Part 2)
1. Line 6 should be: void add(int x, int y, int* result) {
2. Line 7 should be: *result = x + y;
3. Line 8 should be: sum += (x + y);
4. Line 15 should be: return x; // after the if statement scope
5. Line 23 should be: y = absolute_value(y);
6. Line 27 should be: add(y, x, &result);

                        
1. Line 7 should be: void add(int x, int y, int* result) {
2. Line 8 should be: *result = x + y;
3. Line 9 should be: sum += (x + y);
4. Line 16 should be: return x; // after the if statement scope
5. Line 23 should be: y = absolute_value(y);
6. Line 27 should be: add(y, x, &result);

                        

Question 2: What is the Output?

Determine the output of the following code snippet:

int x;
int y;
int *p = &x;
int *q = &y;

*p = 35;
*q = 98;
*p = *q;

printf("%d  %d  %d  %d", x, y, *p, *q);
int x;
int y;
int *p = &x;
int *q = &y;

*p = 35;
*q = 98;
*p = *q;

cout << x << "  " << y << "  " << *p << "  " << *q;
Solution
Expected Output:
98  98  98  98

                        
Expected Output:
98  98  98  98

                        

Question 3: Valid or Invalid?

Which of the following statements is NOT valid?

Part 1

Given the declaration:

int x = 5, y = 3;
int p[5] = {5, 6, 7, 8, 9};
int *q = &y;
  • p = q;
  • *p = 56;
  • *p = *q;
  • q = &x;
Solution (Part 1)
1. p = q;   -> INVALID. You cannot assign a new address to an array name (constant pointer).
2. *p = 56; -> VALID. Changes p[0] to 56.
3. *p = *q; -> VALID. Assigns value of y (3) to p[0].
4. q = &x;  -> VALID. Changes q to point to x.

                        
1. p = q;   -> INVALID. You cannot assign a new address to an array name (constant pointer).
2. *p = 56; -> VALID. Changes p[0] to 56.
3. *p = *q; -> VALID. Assigns value of y (3) to p[0].
4. q = &x;  -> VALID. Changes q to point to x.

                        

Part 2

Given the declaration:

int x = 5, y = 3;
int q[5] = {5, 6, 7, 8, 9};
int *p = &y;
  • p = q;
  • *p = 56;
  • *p = *q;
  • q = &x;
Solution (Part 2)
1. p = q;   -> VALID. p is a variable, can point to start of array q.
2. *p = 56; -> VALID. Changes value of y to 56.
3. *p = *q; -> VALID. Assigns q[0] (5) to y.
4. q = &x;  -> INVALID. You cannot assign a new address to an array name (constant pointer).

                        
1. p = q;   -> VALID. p is a variable, can point to start of array q.
2. *p = 56; -> VALID. Changes value of y to 56.
3. *p = *q; -> VALID. Assigns q[0] (5) to y.
4. q = &x;  -> INVALID. You cannot assign a new address to an array name (constant pointer).

                        

Question 4: Reverse Array using Pointers

Write a program that asks the user for the number of elements N, reads N integers into an array using pointers, and then prints the array elements in reverse order using pointers.

Example:

Enter number of elements: 5
Enter elements:
1 2 3 4 5
Reversed Array:
5 4 3 2 1 
Solution
#include <stdio.h>

int main() {
    int n;
    int a[100];
    int *ptr = a; 
    
    printf("Enter number of elements: ");
    scanf("%d", &n);
    int *left = a;
    int *right = &a[n - 1];
    
    printf("Enter elements:\n");
    while(left<=right){
        scanf(" %d", left);
        left++;
    }
    printf("Reversed array:\n");
    left = a;
    right = &a[n - 1];
    while(left<=right){
        int temp = *left;
        *left = *right;
        *right = temp;
        left++;
        right--;
    }
    left = a;
    right = &a[n - 1];
    while(left<=right){
        printf("%d ", *left);
        left++;
    }
    printf("\n");

    return 0;
}

                        
#include <iostream>
using namespace std;

int main() {
    int n;
    int a[100];

    cout << "Enter number of elements: ";
    cin >> n;

    int *left = a;
    int *right = &a[n - 1];

    cout << "Enter elements:\n";
    while (left <= right) {
        cin >> *left;
        left++;
    }

    // In-place reverse using two pointers
    left = a;
    right = &a[n - 1];
    while (left <= right) {
        int temp = *left;
        *left = *right;
        *right = temp;
        left++;
        right--;
    }

    cout << "Reversed array:\n";
    left = a;
    right = &a[n - 1];
    while (left <= right) {
        cout << *left << " ";
        left++;
    }
    cout << "\n";

    return 0;
}

                        

Question 5: Palindrome Check

Write a program that reads a string from the user, calculates its length N, and checks if it is a Palindrome (a string that reads the same from left to right and right to left).

Example:

Enter a string: racecar
The string is a Palindrome.
Solution
#include <stdio.h>

int main() {
    char str[100];

    printf("Enter a string: ");
    scanf("%s", str);

    char *start = str;
    char *end = str;

    while (*end != '\0') {
        end++;
    }
    end--;
    int isPalindrome = 1;

    while (start < end) {
        if (*start != *end) {
            isPalindrome = 0;
            break;
        }
        start++;
        end--;
    }

    if (isPalindrome) {
        printf("The string is a Palindrome.\n");
    } else {
        printf("The string is NOT a Palindrome.\n");
    }

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    char str[100];

    cout << "Enter a string: ";
    cin >> str;

    char *start = str;
    char *end = str;

    while (*end != '\0') end++;
    end--;

    int isPalindrome = 1;
    while (start < end) {
        if (*start != *end) {
            isPalindrome = 0;
            break;
        }
        start++;
        end--;
    }

    if (isPalindrome) {
        cout << "The string is a Palindrome.\n";
    } else {
        cout << "The string is NOT a Palindrome.\n";
    }

    return 0;
}

                        

Question 6: What is the Output?

Determine the output of the following code snippet, which tests your understanding of function parameters (call by value and call by reference).

#include <stdio.h>

int f1(int x, int y) {
    x = x + 2;
    y = y + 3;
    return x + y;
}

int f2(int *x, int y) {
    *x = *x + 2;
    y = y + 3;
    return *x + y;
}

int f3(int *x, int *y) {
    *x = *x + 2;
    *y = *y + 3;
    return *x + *y;
}

int f4(int x, int *y, int *z) {
    x = x + *y;
    *y = *z + 3;
    z = &x;
    *z = (*y) * 2;
    return *z;
}

int main() {
    int k = 3, m = 5, r = 0;

    printf("1) %d %d %d \n", k, m, r);

    r = f1(k, m);
    printf("2) %d %d %d \n", k, m, r);

    r = f2(&k, m);
    printf("3) %d %d %d \n", k, m, r);

    r = f3(&k, &m);
    printf("4) %d %d %d \n", k, m, r);

    r = f4(k, &m, &r);
    printf("5) %d %d %d \n", k, m, r);

    return 0;
}
#include <iostream>
using namespace std;

int f1(int x, int y) {
    x = x + 2;
    y = y + 3;
    return x + y;
}

int f2(int *x, int y) {
    *x = *x + 2;
    y = y + 3;
    return *x + y;
}

int f3(int *x, int *y) {
    *x = *x + 2;
    *y = *y + 3;
    return *x + *y;
}

int f4(int x, int *y, int *z) {
    x = x + *y;
    *y = *z + 3;
    z = &x;
    *z = (*y) * 2;
    return *z;
}

int main() {
    int k = 3, m = 5, r = 0;

    cout << "1) " << k << " " << m << " " << r << " \n";

    r = f1(k, m);
    cout << "2) " << k << " " << m << " " << r << " \n";

    r = f2(&k, m);
    cout << "3) " << k << " " << m << " " << r << " \n";

    r = f3(&k, &m);
    cout << "4) " << k << " " << m << " " << r << " \n";

    r = f4(k, &m, &r);
    cout << "5) " << k << " " << m << " " << r << " \n";

    return 0;
}
Solution
Expected Output:
1) 3 5 0 
2) 3 5 13 
3) 5 5 13 
4) 7 8 15 
5) 7 18 36 
                        
Expected Output:
1) 3 5 0 
2) 3 5 13 
3) 5 5 13 
4) 7 8 15 
5) 7 18 36 
                        

Question 7: Remove Commas

Write a CC++ function called RemoveCommas. The function receives two Strings in the form of character pointers as the following: void RemoveCommas(char * oldval, char * newval).

Your function should generate a new string called newval out of oldval by removing all the commas in oldval.

Example: Given the following code:

char FilteredName[20];
RemoveCommas("v1,v2,v3", FilteredName);

It should store the value "v1v2v3" inside FilteredName.

Constraints:

  • You are not allowed to use arrays inside your function, only character pointers.
Solution
#include <stdio.h>

void RemoveCommas(char * oldval, char * newval)
{
    char * p1, * p2;
    p1 = oldval;
    p2 = newval;
    while (*p1 != '\0')
    {
        if (*p1 != ',')
        {
            *p2 = *p1;
            p2++;
        }
        p1++;
    }
    *p2 = '\0';
}

int main()
{
    char Name[] = "v1,v2,v3";
    char FilteredName[20];
    RemoveCommas(Name, FilteredName);
    printf("Name before filter is %s \n", Name);
    printf("Name after filter is %s \n", FilteredName);

    return 0;
}
                        
#include <iostream>
using namespace std;

void RemoveCommas(char *oldval, char *newval) {
    char *p1, *p2;
    p1 = oldval;
    p2 = newval;
    while (*p1 != '\0') {
        if (*p1 != ',') {
            *p2 = *p1;
            p2++;
        }
        p1++;
    }
    *p2 = '\0';
}

int main() {
    char Name[] = "v1,v2,v3";
    char FilteredName[20];
    RemoveCommas(Name, FilteredName);
    cout << "Name before filter is " << Name << "\n";
    cout << "Name after filter is " << FilteredName << "\n";

    return 0;
}

                        

Question 8: Find Min and Max of Array using Pointers

Write a complete CC++ program including a function FindMinMax() that receives an array pointer, array size, and two pointer variables to store the minimum and maximum values found in the array.

Constraints:

  • Do not use array bracket notation [] inside the FindMinMax function; perform array traversal using only pointer arithmetic and dereferencing.

Example:

Enter number of elements: 5
Enter 5 elements: 12 5 20 8 15
Min: 5
Max: 20
Solution
#include <stdio.h>

void FindMinMax(int *arr, int size, int *min, int *max) {
    *min = *arr;
    *max = *arr;
    for (int i = 1; i < size; i++) {
        int val = *(arr + i);
        if (val < *min) {
            *min = val;
        }
        if (val > *max) {
            *max = val;
        }
    }
}

int main() {
    int size;
    int arr[50];
    int min, max;

    printf("Enter number of elements: ");
    scanf("%d", &size);

    printf("Enter %d elements: ", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    FindMinMax(arr, size, &min, &max);

    printf("Min: %d\n", min);
    printf("Max: %d\n", max);

    return 0;
}

                        
#include <iostream>
using namespace std;

void FindMinMax(int *arr, int size, int *min, int *max) {
    *min = *arr;
    *max = *arr;
    for (int i = 1; i < size; i++) {
        int val = *(arr + i);
        if (val < *min) {
            *min = val;
        }
        if (val > *max) {
            *max = val;
        }
    }
}

int main() {
    int size;
    int arr[50];
    int min, max;

    cout << "Enter number of elements: ";
    cin >> size;

    cout << "Enter " << size << " elements: ";
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }

    FindMinMax(arr, size, &min, &max);

    cout << "Min: " << min << endl;
    cout << "Max: " << max << endl;

    return 0;
}

                        

Question 9: Sum Array Range via Pointers

Write a complete CC++ program including a function SumRange() that receives two integer pointers representing the start (inclusive) and end (exclusive) boundaries of an array range, and returns the sum of the elements within that range.

Example:

Enter number of elements: 5
Enter 5 elements: 10 20 30 40 50
Enter start and end indexes: 1 4
Sum: 90
Solution
#include <stdio.h>

int SumRange(const int *start, const int *end) {
    int sum = 0;
    while (start < end) {
        sum += *start;
        start++;
    }
    return sum;
}

int main() {
    int size;
    int arr[50];
    int startIdx, endIdx;

    printf("Enter number of elements: ");
    scanf("%d", &size);

    printf("Enter %d elements: ", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Enter start and end indexes: ");
    scanf("%d %d", &startIdx, &endIdx);

    int sum = SumRange(&arr[startIdx], &arr[endIdx]);
    printf("Sum: %d\n", sum);

    return 0;
}

                        
#include <iostream>
using namespace std;

int SumRange(const int *start, const int *end) {
    int sum = 0;
    while (start < end) {
        sum += *start;
        start++;
    }
    return sum;
}

int main() {
    int size;
    int arr[50];
    int startIdx, endIdx;

    cout << "Enter number of elements: ";
    cin >> size;

    cout << "Enter " << size << " elements: ";
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }

    cout << "Enter start and end indexes: ";
    cin >> startIdx >> endIdx;

    int sum = SumRange(&arr[startIdx], &arr[endIdx]);
    cout << "Sum: " << sum << endl;

    return 0;
}