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]);
}
}
Related
I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 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.
I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");
#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);
...
I'm trying to make a one-month calendar that prints the sum of the last row of days.
The output of this is correct for the calendar, but the sum keeps printing out that it's 0. For an input of 3=day_of_week and 30=days_in_month, the sum should be 26+27+28+29+30 = 140
Thanks.
int main() {
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i=0; i<3*day_of_week; i++)
printf(" ");
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}
I don't understand why you are doing ++day_of_week,
something like this should work better:
int main()
{
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i = 0; i < 3 * day_of_week; i++)
printf(" ");
for (i = 1; i <= days_in_month; i++)
{
printf("%3d", i);
array[i] = i;
if (i % 7 == 0)
printf("\n");
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}
You have
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
but day_of_week does not remain constant in your program and changes before with this statement:
day_of_week++;
Use a second variable to increment and do not modify day_of_week after scanf.
One problem is here:
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
You are allowing day_of_week to go out of range. Your code expects that value to be no more than 7. This loop will result in that variable being set to the value the user entered plus (days_in_month - 1). In your final for loop, the statement 7 - day_of_week will likely be negative, which will throw the rest of your code off.
You are sort of checking for overflow when you test the variable modulo 7 and print a newline. When you do that, set day_of_week = 0 as well.
Also, calculate (days_in_month-(7-day_of_week)) and store it in a temporary variable as soon as you get the input from the user. Since you're manipulating these variables inside your code, your final for loop probably isn't using the values that you think it's using. Alternatively, don't modify the variables that you use for user input and create other variables to use as temporaries.