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();
}
Related
So, I'm new in learning array structure, and I'm made a program that asks the user to determine first their array size, after the user inputs the data, I want to display all the data entered, here's the code:
{
int num, i;
printf("How many data you want to input? :");
scanf("%d", &num);
int datacapacity[num];
for(i=0; i<num; i++)
{
printf("Mark %d :", i+1);
scanf("%d", &datacapacity[i]);
}
printf("\nMark %d is %d", i+1, datacapacity[i]);
}
input
How many data you want to input? :4 // 4 entered from keyboard
Mark 1 :23 // 23 entered from keyboard
Mark 2 :23 // 23 entered from keyboard
Mark 3 :23 // 23 entered from keyboard
Mark 4 :12 // 12 entered from keyboard
Mark 5 is 4
The problem I have is it just printing Mark 5 is 4 How to print all the data the user entered?
#include<stdio.h>
int main() {
int num, i;
printf("How many data you want to input? :");
scanf("%d", &num);
int datacapacity[num];
for (i = 0; i < num; i++) {
printf("Mark %d :", i + 1);
scanf("%d", &datacapacity[i]);
}
for (i = 0; i < num; i++) {
printf("\nMark %d is %d", i + 1, datacapacity[i]);
}
}
Use the above code.
In the above line of the second for loop is used for printing the array elements it starts from index 0 .
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.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int numOfMeal, items[50];//, sum;
printf("Enter number of meals/snacks: ");
scanf("%d",&numOfMeal);
for(int i=1; i<=numOfMeal;i++)
{
printf("Enter kilojoules for item %d: ", i);
scanf("%d", &items[numOfMeal]);
}
printf("Your total kilojoules are: %d", items[numOfMeal]);
return EXIT_SUCCESS;
}
any ideas on how to calculate the sum of arrays, when i run this program it only displays the last kilojoule entered..
1.
You should run the loop from 0 to numOfMeal-1 because array indexing starts from the 0, not 1. If you are accessing the nth element that is a segmentation fault.
2.
The second problem in your code is that you are not taking the input values in the array. Your loop is, again and again, overwriting the items[numOfMeal] which is the last element in your array.
Write your code as below:
int numOfMeal, items[50],sum=0;
printf("Enter number of meals/snacks: ");
scanf("%d",&numOfMeal);
for(int i=0; i<numOfMeal;i++) // run loop from 0 to numOfMeal-1
{
printf("Enter kilojoules for item %d: ", i);
scanf("%d", &items[i]); // take the input at ith position in the array
sum+=items[i]; // sum them
}
printf("Your total kilojoules are: %d", sum); // print the final result
The short code for this can be
int numOfMeal, item, sum=0;
scanf("%d",&numOfMeal);
for(int i=0; i<numOfMeal;i++){
scanf("%d", &item);
sum+=item;
}
printf("Your total kilojoules are: %d", sum);
In this code I am not storing the value in the array, just saving it temporarily in the variable and add it to sum variable.
1) change your for loop. indexes of array start at 0. change i = 1 to i = 0 and i <= numOfMeal to i < numOfMeal
2) you have to calculate sum of array elements in loop
...
int result = 0;
for (int i = 0; i < numOfMeal; i++)
{
...
result += items[i];
}
printf("Your total kilojoules are: %d", result);
...
The purpose of my program thus far is to create 4 arrays. 1 'char' array which will take in 10 different string values with each element having a maximum of 25 characters. And 3 other array's that will take in 10 integer values and store them into my array. I compile and run my program, and cycle through my for loops and once completed, I get some weird integer values in the place of my teamName array, and for the 'teamWins' 'teamLosses' and 'teamTies' arrays, it gives me the first value I input for ALL elements in those arrays. I really want to understand how arrays work but I am having trouble declaring them, and using them with input, and output. Can anyone see and explain how I can take in 10 strings with values of 25 characters in each element, and take in 10 integers in the other 3 arrays with elements of 10? I will attach my source code below.
#include <stdio.h>
#include <stdlib.h>
#define NUM_TEAM 10
void displayWelcome(void);
int main(void)
{
char * teamName[NUM_TEAM + 1][30] = { "" };
int teamWins[NUM_TEAM] = {0};
int teamLosses[NUM_TEAM] = {0};
int teamTies[NUM_TEAM] = {0};
int i, bestPercent, worstPercent;
displayWelcome();
//Team Name
for (i = 0; i < NUM_TEAM; i++)
{
//Prompt and enter team name
printf("Enter %i's team name: ", i + 1);
fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);
//Data validation
}
//Team wins
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter wins for team number %i : ", i + 1);
scanf("%i", &teamWins[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamWins) || teamWins <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team losses
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter losses for team number %i : ", i + 1);
scanf("%i", &teamLosses[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamLosses) || teamLosses <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team ties
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter ties for team number %i : ", i + 1);
scanf("%i", &teamTies[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamTies) || teamTies <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Display Data
for (i = 0; i < NUM_TEAM; i++)/* output each word read */
{
printf("%s", teamName);
printf("wins losses ties\n");
printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);
}
return 0;
}
void displayWelcome(void)
{
printf("Welcome to my Football Stats\n\n");
}
You've got four issues:
Declaring teamName as char * teamName[NUM_TEAM + 1][30] = { "" }; is incorrect; if you want an array of strings, it's sufficient to declare char teamName[NUM_TEAM + 1][30] = { "" }; (you want a 2D array of chars, not char *s).
In fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);, you're writing each team name to the same unused element. Instead, use fgets (teamName[i], sizeof teamName[NUM_TEAM], stdin); to write to the proper team during each iteration.
Printing using printf("%s", teamName); is incorrect; you want to print each team name rather than attempt to print the address of the teamName array: printf("%s", teamName[i]);
You have an extra argument in printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);; since you've already printed teamName[i] in Point 3, you should remove it in this printf() call: printf("%i %i %i\n", teamWins[i], teamLosses[i], teamTies[i]);
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", ¬eNumber);
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", ¬eNumber);
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]);
}
}