Friday, January 24, 2020

Posted on Leave a Comment

Count all non-zero, odd and even numbers in the singly linked list


A ‘C’ program to count all non-zero elements, odd numbers and even numbers in the singly linked list.

Odd And Even Numbers In The Singly Linked List

Singly linked list Source Code 


#include

#include

typedef struct NUM

{
  int data;
  struct NUM * link;

}
num;

num * createnode() {
  num * nn = NULL;
  nn = (num * ) malloc(sizeof(num));
  if (nn == NULL) {
    printf(“\n insufficient memory”);
    exit(0);
  } //end if
  return (nn);

} //end createnode

num * create() {
  num * hn = NULL, * cn = NULL, * nn = NULL;
  int i, n;
  printf(“\n enter no of node“);
  scanf(“ % d”, & n);
  printf(“\n enter data\ t”);
  for (i = 0; i < n; i++) {
    nn = createnode();
    scanf(“ % d”, & nn - > data);
    nn - > link = NULL;
    if (hn == NULL) {
      hn = nn;
      cn = nn;
    } //end if
    else {
      cn - > link = nn;
      cn = nn;
    }
  } //end for
  return (hn);
} //end create
void display(num * hn) {
  num * cn = NULL;
  int cnt_nonzero = 0, cnt_even = 0, cnt_odd = 0;
  num * temp = NULL;
  printf(“\n data present in link list is“);
  for (cn = hn; cn != NULL; cn = cn - > link) {
    printf(” % d”, cn - > data);
  } //end for
  /*following code counts the nonzero,even,odd*/
  temp = hn;
  while (temp != NULL) {
    if (temp - > data != 0) {
      cnt_nonzero++;
    }
    if (temp - > data != 0) {
      if ((temp - > data) % 2 == 0) {

        cnt_even++;
      }
      if ((temp - > data) % 2 != 0) {
        cnt_odd++;
      }
    }

    temp = temp - > link;
  }

  printf(“\nThe number of non - zero elements is % d”, cnt_nonzero);
  printf(“\nThe number of even elements is % d”, cnt_even);
  printf(“\nThe number of odd elements is % d”, cnt_odd);
} //end display
void main() {
  num * hn, * nn, * pn;
  int ch;
  clrscr();
  hn = create();
  display(hn);

  getch();
} //end main


Output


enter no of node 5
enter data 0 1 0 2 3
data present in link list is 0 1 0 2 3
The number of non-zero elements is 3
The number of even elements is 1
The number of odd elements is 2

0 comments:

Post a Comment

Codearea.in is featured by projectsgeek.com. Powered by Blogger.