Traversal in Array

Rumman Ansari   Software Engineer   2023-03-27   6318 Share
☰ Table of Contents

Table of Content:


It is an operation in which each element of a list, stored in an array, is visited. The travel proceeds from the zeroth element to the last element of the list. Processing of the visited element can be done as per the requirement of the problem.

Example: A list of N integer numbers is given. Write a program that travels the list and determines as to how many of the elements of the list are less than zero, zero, and greater than zero.

Solution: In this program, three counters called numNeg, numZero and numPos, would be used to keep track of the number of elements that are less than zero, zero, and greater than zero present in the list. The required program is given below:



/* This program determines the number of less than zero, zero, and greater than zero numbers present in a list */

#include <stdio.h>

void main()

{

int List [30];

int N;

int i, numNeg, numZero, numPos;

  printf ("\n Enter the size of the list");

  scanf ("%d", &N);

printf ("Enter the elements one by one");

/* Read the List*/

for (i = 0; i < N; i++)

{

  printf ("\n Enter Number:");

  scanf ("%d", &List[i]);

}

numNeg = 0; /* Initialize counters*/

numZero = 0;

numPos = 0;

/* Travel the List*/

for (i=0; i < N; i++)

{

    if (List[i] < 0)

        numNeg = numNeg + 1;

    else

      if (List[i] == 0)

        numZero = numZero + 1;

      else

      numPos = numPos + 1;

}

}