removing a range of elements from an array in c - c

I need to remove a range of elements from an array but I can't figure out how. I tried this for loop where start is the start of the range and end is the end of the range.
int main(void)
{
int n, n2, i, start, end, index;
int a1[n];
int a2[n2];
printf("Enter the length of the array#1: ");
scanf("%d", &n);
printf("Enter the elements of the array#1: ");
for (i = 0; i < n; i++){
scanf("%d", &a1[i]);}
printf("Enter the length of the array#2: ");
scanf("%d", &n2);
printf("Enter the elements of the array#2: ");
for (i = 0; i < n2; i++){
scanf("%d", &a2[i]);}
printf("Enter the start and end indexof array #1 to be removed: ");
scanf("%d %d", &start, &end);
int a3[(end-start)+1];
printf("Enter the position(index)of the array #2 to be added before: ");
scanf("%d", &index);
for (i=0;i < (n - end - 1);i++){
a1[start + i] = a1[end + i + 1];
a1[end + i + 1] = 0;
}
printf("\n");
printf("array1: ");
for (i=0;i < (n);i++){
printf("%d", a1[i]);
printf(" ");
}

You have:
Used n and n2 to give size of the array without initializing those variables first. Though you have not initialized your array but if you did, it would've failed due to VLA.
Not checked the input you are receiving from the user whether the range provided is feasible? What if end - start is greater than the length of the arrays.
Used 0 as a value to replace after that element has moved to a new location/index, what if the number being moved is 0 itself?
For the last point, use some value which has a very less probability of being entered by user like INT_MAX & you'll be needing limits.h header + after that it'll be good to make your for loop look like this:
for(index=0;((index<sizeArr)&&((arr[index]!=INT_MAX)));++index)
This loop will print start - end lesser values from the original array.

Since you want to determine the array size at runtime (via input from the user), you should be using dynamic allocation.
I'm not positive exactly what you are trying to accomplish with this script, but here's an example of what moving to dynamic allocation would look like:
int main(void)
{
int n, n2, i, start, end, index;
int *a1;
int *a2;
printf("Enter the length of the array#1: ");
scanf("%d", &n);
a1 = malloc(sizeof(int)*n);
printf("Enter the elements of the array#1: ");
for (i = 0; i < n; i++){
scanf("%d", &a1[i]);
}
printf("Enter the length of the array#2: ");
scanf("%d", &n2);
a2 = malloc(sizeof(int)*n2);
printf("Enter the elements of the array#2: ");
for (i = 0; i < n2; i++){
scanf("%d", &a2[i]);
}
You can access the values pointed to by a1 using normal array notation, but you should add some bounds checking to ensure the user does not specify an array index outside the bounds of n/n2.

Related

C Programming How to get results of an mathematical operation stored in a different array?

I am trying to subtract a given number from an array and then store the results in a completely different array. Is it possible to write the code without using pointers?
I am trying to write the code with using for loop and or do/while loop.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int num[100];
int i ;
int size;
int sub;
int diff[100];
printf("Enter the size of the array: ");
scanf("%d", &size);
for(i=0;i<size; i++){
printf("Enter the element %d :", i+1);
scanf("%d", &num[i]);
}
printf(" Enter the number to substract: \n");
scanf("%d", &sub);
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}
for (y=0; y<size; y++)
{
printf("%d", diff[y]);
}
}
After I scan the results, I tried different ways to initialize and store the values in the second array but haven't been successful. What mistake am I making here?
y = num[i] - sub;
This is fine, as it's the result of subtraction for a given source array element.
scanf("%d", &diff[y]);
This doesn't make sense, as it's attempting to read input from the user. Not only that, it's using the result of the subtraction as the index of the destination array.
Just assign the result of the subtraction to the corresponding destination array member:
diff[i] = num[i] - sub;
In your question, you try to scan the value to another array, but the correct form is to assign the value in the new array position.
For example, in your first for loop use the i variable as the position and assign num[i] - sub on diff[i]:
for (i = 0; i < size; i++)
{
diff[i] = num[i] - sub;
}
instead of:
for (i=0;i<size; i++)
{
y = num[i]- sub;
scanf("%d", &diff[y]);
}

Displayed number deleted in array is not correct

I have this program where it lets the user input an array of numbers.
For example, I would input an array size of 4 and input the numbers 40, 20, 1, and 8 as the elements in the array.
Input array size: 4
Input array elements: 40 20 1 8
The program also lets the user delete any elements from the array and the output should also show the element that was deleted.
For example, I would delete the number 40 from the elements. The output should be like this:
Enter the position of the element that you would like to delete: 1
The element 40 is completely deleted!
But instead of showing 40, the output goes like this:
Enter the position of the element that you would like to delete: 1
The element 20 is completely deleted!
Here is my source code:
int a[100];
int arraySize, elementPosition;
printf("\n Input Array Size: ");
scanf("%d", &arraySize);
printf("\n Input Array Elements: ");
for(i = 0; i < arraySize; i++)
{
scanf("%d, ", &a[i]);
}
printf("\n Enter the position of the element you would like to delete: ");
scanf("%d", &elementPosition);
int deletedElement = a[elementPosition];
if (elementPosition >= arraySize + 1)
{
printf("\n \n \t Invalid position! Enter numbers from 1 to %d only.\n", arraySize);
getch();
del();
}
else
{
for (i = elementPosition; i < arraySize - 1; i++)
{
a[i] = a[i+1];
}
printf("\n \The element %d is completely deleted!", deletedElement);
arraySize = arraySize - 1;
getch();
}
It would be a very big help if someone can point out where did I go wrong.
Array index starts from 0. This deletedElement = a[elementPosition]; should be changed to deletedElement = a[elementPosition - 1];.
Additionally, you need to make sure that subtracting 1 does not cause deletedElement to become less than 0.
Could you test it, the index begin from 0 the position from 1.
int a[100];
int arraySize, elementPosition;
printf("\n Input Array Size: ");
scanf("%d", &arraySize);
printf("\n Input Array Elements: ");
for(i = 0; i < arraySize; i++)
{
scanf("%d, ", &a[i]);
}
printf("\n Enter the position of the element you would like to delete: ");
scanf("%d", &elementPosition);
int deletedElement = a[elementPosition - 1 ];
if (elementPosition >= arraySize)
{
printf("\n \n \t Invalid position! Enter numbers from 1 to %d only.\n", arraySize);
getch();
del();
}
else
{
for (i = elementPosition - 1; i < arraySize - 2; i++)
{
a[i] = a[i+1];
}
printf("\n \The element %d is completely deleted!", deletedElement);
arraySize = arraySize - 1;
getch();
}

C While loop does not exit correctly

I have to take a university course on C and I shall read in some integers with a while loop. The code is:
#include <stdio.h>
#define max 100
int main(){
int a[max];
int i,n;
printf("Enter the number of persons: ");
do{
scanf("%i", &n);
}while((n < 1) || (n > max));
i = 0;
while (i < n){
printf("Enter the age of the %i th Person", i+1);
scanf("%i", &a[i]);
i = i + 1;
}
/* further code */
It compiles (with the gcc compiler), but as soon as I get into the loop, it reads in the numbers correctly, but after the last input, nothing is executed anymore.
Initialise i
int i = 0;
int n;
[edit: I see now that you have edited your code as I suggested]
Initialize i = 0
Here is the working code.
#define max 5
int main()
{
int a[max];
int i = 0,n;
printf("Enter the number of persons:\n");
do{
scanf("%d", &n);
}while((n < 1) || (n > max));
while (i < n){
printf("Enter the age of the %i th Person:\n", i+1);
scanf("%i", &a[i]);
i = i + 1;
}
return 0;
}
i has a garbage value at first you should write i=0 at first
and than scanf("%d", &n); Because you are calling a while loop with a garbage value of i at the beginning and code executes if the belove statistics satisfied while((n < 1) || (n > max)) but i has no value so you do not increment it. Think about sum,count I'm sure you know what i mean. if you want to increment something you should define first. An integer i defined with no value cant increment. Use for loop at last loop, instead of while

How to get the value of the last element of an array?

Observe the following code. I want to divide the amount by the value of the last element in the array. I have tried in the following way but it is not working. Can anyone tell me what is the proper way to do it?
#include<stdio.h>
int main()
{
int i, j, k, noteNumber, array[100], amount, result;
printf("Enter the number of the notes: \n");
scanf("%d", &noteNumber);
printf("Enter the value of %d notes: \n", noteNumber);
for(i = 0; i < noteNumber; i++){
scanf("%d", &array[i]);
}
printf("Enter the amount: \n");
scanf("%d", &amount);
i = j;
if(amount / array[j] == 0){
printf("Minimum %d number of is needed", (amount/array[j]));
printf("The value of each note is %d", array[j]);
}
}
As I can see
i = j;
is wrong as you're using the value of an uninitialized variable to assign to another. This does not make any sense and can lead to undefined behavior.
C arrays use 0-based indexing, so for an array of size n, the last index would be n-1.
That said, never use an unbound index for a statically defined array, always perform the bound checking before using the index.
If noteNumber is the size of the array, then the last Element will be
array[noteNumber - 1]
As far as I can see, j isn't even initialized?
You are having a line
i = j;
j is not even initialized so you are doing a mistake here , maybe what
you wanted was
j = i - 1
As i would have incremented to noteNumber in your for loop and array with number of elements n has last element index n-1 because index starts from 0 rather than 1.
So Proper Code Would Be
#include<stdio.h>
int main(){
int i, j, k, noteNumber, array[100], amount, result;
printf("Enter the number of the notes: \n");
scanf("%d", &noteNumber);
printf("Enter the value of %d notes: \n", noteNumber);
for(i = 0; i < noteNumber; i++){
scanf("%d", &array[i]);
}
printf("Enter the amount: \n");
scanf("%d", &amount);
j = i - 1; // Line Changed
if(amount / array[j] == 0){
printf("Minimum %d number of is needed", (amount/array[j]));
printf("The value of each note is %d", array[j]);
}
}

Fibonacci Series in C Program where FIRST 2 numbers are given by user

When the first number is 1 and second number is 2, and the length is 5, it should be 1 2 3 5 8. But then my output is always 1 2 1 3 4. I can't seem to find the problem.
Another input is 2 and 5. Output is 2 5 1 6 7. The 3rd number which is 1 shouldn't be there. What should I change or add?
*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.
int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}
printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}
printf("%d\t", fib);
}
}
The first time you print fib (before the for loop), you haven't assigned it anything yet.
Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.
Putting it all together, we get something like:
#include <stdio.h>
int main() {
int length = 0, a, b;
while (length < 2 || length > 100 || a > b ) {
printf("\nFirst number: ");
(void) scanf("%d", &a);
printf("\nSecond number: ");
(void) scanf("%d", &b);
printf("\nHow long?: ");
(void) scanf("%d", &length);
}
printf("%d\t%d\t", a, b);
for (int i = 2; i < length; i++) {
int fib = a + b;
printf("%d\t", fib);
a = b;
b = fib;
}
printf("\n");
return 0;
}
Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.
just add fib=a+b; before printing fib value.
Its a good coding habit to initialize all variable before using it(especially in C).
Your code seems strange to me. I tried to simplify your code a bit. See this once:
int main()
{
int a,b,next,last,i;
printf("Enter the first Value:");
scanf("%d",&a);
printf("Enter the second Value:");
scanf("%d",&b);
printf("Enter the length of Fab. series:");
scanf("%d",&last);
printf("%d,%d,",a,b);
for (i=3; i<= last; i++)
{
next = a + b;
if(i<last)
printf("%d,",next);
else
printf("%d",next);
a = b;
b = next;
}
return 0;
}
Hope it's Helpful!!

Resources