w3resource

C Exercises: Compute the sum of the numbers in a given array except those numbers starting with 5 followed by atleast one 6

C-programming basic algorithm: Exercise-53 with Solution

Write a C program to compute the sum of the numbers in a given array except those that begin with 5 followed by at least one 6. Return 0 if the given array has no integers.

C Code:

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

// Function prototype for 'test'
int test(int nums[], int arr_size);

int main(void){
    // Declaration and initialization of an integer array 'array1'
    int array1[] = {1, 5, 6, 9, 10, 17};

    // Calculating the size of the array 'array1'
    int arr_size = sizeof(array1)/sizeof(array1[0]);

    // Printing a message indicating the purpose of the program
    printf("Sum of values in the array of integers except those numbers starting with 5 followed by atleast one 6: ");

    // Printing the result of the 'test' function for the array 'array1'
    printf("%d",test(array1, arr_size));
}    

// Definition of the 'test' function
int test(int nums[], int arr_size)
{
    // Declaration of a variable 'sum' to accumulate the sum of values
    int sum = 0;

    // Declaration of a variable 'inSection' to track if we are inside the section
    int inSection = 0;

    // Looping through the elements of the array
    for (int i = 0; i < arr_size; i++)
    {
        // Checking if the current element is 5, marking the start of a section
        if (nums[i] == 5)
        {
            inSection = 1;
        }
        // Checking if the current element is 6, marking the end of a section
        else if (inSection && nums[i] == 6)
        {
            inSection = 0;
        }
        // Adding the value to 'sum' if it's not part of the section
        else if (!inSection)
        {
            sum += nums[i];
        }
    }

    // Returning the accumulated sum
    return sum;
}

Sample Output:

Sum of values in the array of integers except those numbers starting with 5 followed by atleast one 6: 37

Pictorial Presentation:

C Programming Algorithm: Compute the sum of the numbers in a given array except those numbers starting with 5 followed by atleast one 6

Flowchart:

C Programming Algorithm Flowchart: Compute the sum of the numbers in a given array except those numbers starting with 5 followed by atleast one 6

C Programming Code Editor:

Previous: Write a C program to compute the sum of values in a given array of integers except the number 17. Return 0 if the given array has no integer.
Next: Write a C program to check if a given array of integers contains 5 next to a 5 somewhere.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.