Untitled

 avatar
unknown
c_cpp
3 years ago
2.2 kB
7
Indexable
/*
ex5b : Finding a zigzag in an array
 * ===============
 * written by : Tamar Ayache,id : 211359559 , login: tamaray
 * This program defines a one-dimensional array of six cells, reads
 * data into it, and displays the number
 * the cell where the longest zigzag begins in the array, 
 * as well as the length of that zigzag.
 * input: 6 int from the user
 * output: The length of the zigzag and the cell number in which it begins
 */    		
//----------include section-------
#include <cstdlib>
#include <iostream>

//---------using section------
using std::cin;
using std::cout;
using std::endl;

//--------const and enum section------
const int SIZE = 6;

//------prototypes section------
bool is_even(int num);
void input (int arr[], int size);
int zigzag_size (const int arr[], int arr_size, int index);
void find_max_zigzag(const int arr[] , int arr_size, int & max, int & index);

//--------main-------
int main()
{
    int arr [SIZE];
    int index;
    int max;
    input(arr, SIZE);
    find_max_zigzag(arr , SIZE , max , index);

    cout << "Longest zigzag is: " << max << ", starting at index " << index << endl;

	return EXIT_SUCCESS;
}

//----------- Input reading function.
void input(int arr[], int size)
{
	for (int i= 0 ;i < size ; i++)
		cin >> arr[i];
}

//----------A function that finds the length of the zigzag
int zigzag_size(const int arr[], int arr_size, int index)
{
	int counter = 1; //counter stars from 1.
	for (  ; index < arr_size - 1 ; index++)
	{

		if (is_even(counter)) //even
		{
			if (arr[index] > arr[index+1])
				counter++;
			else
			    break;
		}
		else
		{
			if (arr[index] < arr[index+1])
				counter ++;
			else
			    break;
		}

	}
	return counter;
}
//------A Boolean function in which the length of the zigzag is
//an even number
bool is_even(int num)
{
	return (num % 2 ==0);
}

//---------A function that finds the longest zigzag length
void find_max_zigzag(const int arr [] , int arr_size, int & max, int & index)
{
	max = 0;
    int curr_size;
	for(int i=	0 ; i< arr_size ; i++)
	{
        curr_size = zigzag_size(arr, arr_size, i);
		if (curr_size >= max)
		{
			index = i;
			max = curr_size;
		}
	}
}
Editor is loading...