Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

loop does not run as intended?

+1 vote
asked Nov 21, 2023 by Aster Lee (130 points)
i am trying to find the subarray that has the maximum product. the product is right, but the code i wrote doesn't seem to check for subarrays that do not start with the first element of the original array, as every time i run the code, 'first' is always 0, and the value of the maximum product is wrong if the subarray does not start from the first element. this is what i have so far:

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

int main(){

    int array[10];
    int i, j, k, product, current=1, first=0, last=0, min;


    for(i=0; i<10; i++){
        array[i] = rand() % 11 - 5;
        printf("%d ", array[i]);

    min = array[0];
    for(i=0; i<10; i++){
            min = array[i];
    product = min;
    printf("min: %d\n", min);

    for(i=0; i<10; i++){
        for(j=9; j>=0; j--){
            for(k=j; k>=0; k--){
                current = current*array[k];
                product = current;

    printf("%d %d %d", first, last, product);

i am unsure where i wrote the code for the loops wrong, and would appreciate any help, thanks!

1 Answer

0 votes
answered Nov 24, 2023 by Peter Minarik (89,130 points)

Try this to find the segment (sub array) that has the highest product of its members:

int maxProduct = array[0];
int start = 0;
int end = 0;
for (i = 0; i < 10; i++)
    int product = array[i];
    for (j = i + 1; j < 10; j++)
        product *= array[j];
        if (product > maxProduct)
            maxProduct = product;
            start = i;
            end = j;

printf("start: %d; end: %d, product: %d\n", start, end, maxProduct);
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.