×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to replace all EVEN elements by 0 and Odd by 1 in One Dimensional Array.

This program will read 10 elements of integer type using One Dimensional Array and replace all EVEN elements by 0 and ODD by 1.

Replacing all EVEN elements by 0 and Odd by 1 in an array

To replace EVEN and ODD elements by 0 and 1, we will check each elements whether it is EVEN or ODD, if it is EVEN assign 0 otherwise assign 1 to the variable with index. For example arr[i] is EVEN, then we will assign arr[i]=0;

Replace EVEN and ODD elements by 0 and 1 using C program

/*Program to replace EVEN elements by 0 and ODD elements by 1.*/
#include <stdio.h>

/** funtion :   readArray() 
    input   :   arr ( array of integer ), size 
    to read ONE-D integer array from standard input device (keyboard). 
**/
void readArray(int arr[], int size)
{
    int i = 0;

    printf("\nEnter elements : \n");

    for (i = 0; i < size; i++) {
        printf("Enter arr[%d] : ", i);
        scanf("%d", &arr[i]);
    }
}

/** funtion :   printArray() 
    input   :   arr ( array of integer ), size 
    to display ONE-D integer array on standard output device (moniter). 
**/
void printArray(int arr[], int size)
{
    int i = 0;

    printf("\nElements are : ");

    for (i = 0; i < size; i++) {
        printf("\n\tarr[%d] : %d", i, arr[i]);
    }
    printf("\n");
}

/** funtion :   replaceEvenOdd() 
    input   :   arr ( array of integer ), size 
    to replace EVEN elements by 0 and ODD elements by 1. 
**/
void replaceEvenOdd(int arr[], int size)
{
    int i = 0;

    for (i = 0; i < size; i++) {
        if (arr[i] % 2 == 0)
            arr[i] = 0;
        else
            arr[i] = 1;
    }
}

int main()
{
    int arr[10];

    readArray(arr, 10);

    printf("\nBefore replacement : ");
    printArray(arr, 10);

    replaceEvenOdd(arr, 10);

    printf("\nAfter replacement : ");
    printArray(arr, 10);

    return 0;
}

Output

Enter elements : 
Enter arr[0] : 1 
Enter arr[1] : 2 
Enter arr[2] : 3 
Enter arr[3] : 4 
Enter arr[4] : 4 
Enter arr[5] : 3 
Enter arr[6] : 4 
Enter arr[7] : 5 
Enter arr[8] : 6 
Enter arr[9] : 7 

Before replacement : 
Elements are : 
	arr[0] : 1 
	arr[1] : 2 
	arr[2] : 3 
	arr[3] : 4 
	arr[4] : 4 
	arr[5] : 3 
	arr[6] : 4 
	arr[7] : 5 
	arr[8] : 6 
	arr[9] : 7 

After replacement : 
Elements are : 
	arr[0] : 1 
	arr[1] : 0 
	arr[2] : 1 
	arr[3] : 0 
	arr[4] : 0 
	arr[5] : 1 
	arr[6] : 0 
	arr[7] : 1 
	arr[8] : 0 
	arr[9] : 1 

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.