
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Perform Operations on Two Halves of a Single Array in C
Problem
Write a program to accept a one-dimensional array of N elements and split into two halves. Later on, sort the first half in an ascending order and the second half into descending order.
Solution
The solution to perform the two operations on two halves’ in a single array in C programming language is explained below −
The logic used to sort the first half in an ascending order is as follows −
for (i=0; i<b; ++i){ for (j=i+1; j<b; ++j){ if (number[i] > number[j]){ a = number[i]; number[i] = number[j]; number[j] = a; } } }
The logic used to sort the second half in the descending order is as follows −
for (i=b; i<n; ++i){ for (j=i+1; j<n; ++j){ if (number[i] < number[j]){ a = number[i]; number[i] = number[j]; number[j] = a; } } }
The logic used to split an array into two halves and print accordingly is given below −
- Ascending order first half
for (i=0; i<b; ++i) printf ("%d ",number[i]);
- Descending order second half
for(i=b;i<n;i++) printf("%d ",number[i]);
Example
Following is the C program to perform two operations on two halves’ in a single array −
#include<stdio.h> void main(){ int i,j,a,n,b,number[30]; printf ("Enter the value of N
"); scanf ("%d", &n); b = n/2; printf ("Enter the numbers
"); for (i=0; i<n; ++i) scanf ("%d",&number[i]); for (i=0; i<b; ++i){ for (j=i+1; j<b; ++j){ if (number[i] > number[j]){ a = number[i]; number[i] = number[j]; number[j] = a; } } } for (i=b; i<n; ++i){ for (j=i+1; j<n; ++j){ if (number[i] < number[j]){ a = number[i]; number[i] = number[j]; number[j] = a; } } } printf (" The 1st half numbers
"); printf (" arranged in asc
"); for (i=0; i<b; ++i) printf ("%d ",number[i]); printf("
The 2nd half Numbers
"); printf("order arranged in desc.order
"); for(i=b;i<n;i++) printf("%d ",number[i]); }
Output
When the above program is executed, it produces the following result −
Enter the value of N 10 Enter the numbers 20 34 23 11 45 56 78 98 76 54 The 1st half numbers arranged in asc 11 20 23 34 45 The 2nd half Numbers order arranged in desc.order 98 78 76 56 54
Advertisements