i m working on this small C program to fill an array, insert and remove elements from an array and finally printing that array.
The program consists of a main() function, the addToArray() function, remFromArray() function and the printArray() function.
here's my main method: which prompts the user for a sequence of positive integers
• for each integer entered by the user, call the addToArray function to insert the integer into the array
• call the printArray function to print out the content of the array.
NOTE:do not prompt the user for the number of integers to be entered; you must accept input until the user enters a negative number
#include <stdio.h>
#define maxSize 100 //maxSize for array
int addToArray(int* arr, int size, int numToAdd);
int remFromArray(int* arr, int size, int numToGo);
void printArray(int* arr, int size);
int main (void){
int arr[maxSize];
int i, j;
printf("Enter a positive integer to add to an array\n");
while (i >= 0 ){
scanf("%d",&i);
if (i >= 0 ) {
addToArray(arr, maxSize, i);
printf("Enter another positive integer for array\n");
}
else{
printArray(arr, maxSize);
}
}
}
these are my other function that i created:
addToArray() =>
/*find the correct index in the array where to insert the
new element, so array in ascending order
- make room for the new element by moving other elements
- store the new element at the correct index
- return the new size (number of elements) of the array */
int addToArray(int* arr, int size, int numToAdd){
int i, n, m, pos;
for (int i = 0; i < maxSize; i++)
{
if (numToAdd < arr[i])
{
pos = i;
break;
}
if (numToAdd > arr[n-1])
{
pos = maxSize;
break;
}
}
if (pos != maxSize)
{
m = maxSize - pos + 1 ;
for (int i = 0; i <= m; i++)
{
arr[maxSize - i + 2] = arr[maxSize - i + 1] ;
}
}
arr[pos] = numToAdd;
}
void printArray(int* arr, int size){
printf("Resultant array is\n");
for (int c = 0; c <= maxSize; c++){
printf("%d\n", arr[c]);
}
}
as you can see I've tried writing the main(), addToArray(), printArray(), but for some reason its not working right. my printArray() is not displaying the desired result. I'll be glad if you could look at this code and guide me through it. thanks a million