So I'm trying to solve this http://www.codeabbey.com/index/task_view/sum-in-loop and I have 45 random numbers to input. I'm coding using C so I want to use the scanf function. The problem is that since it's 45 numbers (which are separated by spaces) what I want to do is copy paste the values so that the program can solve them from an array. Should I do it like this:
int x [45];
scanf("%d %d....(x42) %d",&x,&x,...(x42),&x);
or is there a more efficient way of doing this? (I hope there is T_T)
You need not (and you should not) write a single format string containing 45(or whatever) format specifier, following 45 pointers.
You need to use a loop.
Example:
for loop with an array, will hold the supplied operands, too
int x[45] = {0};
int sum = 0;
for (int i = 0; i < 45; i++) //style supported over C99
{
scanf("%d", &x[i]);
sum += x[i];
}
printf("sum = %d\n", sum);
for loop without an array, won't hold the operands, only result
int x = 0;
int sum = 0;
for (int i = 0; i < 45; i++) //style supported over C99
{
scanf("%d", &x);
sum += x;
}
printf("sum = %d\n", sum);
Related
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]);
}
in my first year University class we have just started fiddling with arrays and on the worksheet I was given this code, which doesn't seem to work. I've been scanning and looking for a problem but nothing seems to fix it. Here is my code...
#include <stdio.h>
#include <stdbool.h>
int main(){
int size = 10;
float suspect[size]; //Declaring suspect array
int sizeR = 3;
int sizeC = 10;
float criminals[sizeR][sizeC]; //Declaring criminals array
//Read 10 input values into suspect array from keyboard
printf("Enter the 10 chromosomes of the suspect separated by spaces: \n");
for (int i = 0; i < size; i++)
scanf(" %f", &suspect[i]);
//Read multiple profiles of 10 values into criminals array from the keyboard
for (int i = 0; i < sizeR; i++){
printf("Enter the 10 chromosomes of the %dth criminal: \n", i+1);
//Read 10 input values of a criminal into criminals array from the keyboard
for (int j = 0; j < sizeC; j++)
scanf(" %f", &criminals[i][j]);
}
//Match two profiles
bool match = true;
for (int i = 0; i < size; i++)
if(suspect[i] != criminals[i]) //Error is in this line
match = false;
//Display matching result
if (match)
printf("The two profiles match! \n");
else
printf("The two profiles don't match! \n");
return 0;
}
And when I run this code, I am returned with:
error: invalid operands to binary expression ('float' and 'float [sizeC]')
With the error being pointed to the != in the matching two profiles part. Excuse me if the solution is simple, coding is relatively new to me and I am struggling to find the solution to this particular problem using Google.
In this if statement
if(suspect[i] != criminals[i]) //Error is in this line
the expression criminals[i] is implicitly converted to the type float * because the original type of the expression before the conversion is float[sizeC].
And moreover the expressions suspect[i] has the type float. That is there are compared an object of the type float with a pointer of the type float * that does not make a sense.
So the compiler issues the error message.
If you are going to compare the array suspect with elements of the two-dimensional array criminals you should use one more inner for loop.
Why does the value of sum changes after for loop in the following code even after I have initialised it as 0 in CodeBlocks?
int main()
{
int a[5], i, sum;
sum= 0; // value of sum is not changed after this.
printf("\nSum=%d", sum);
for( i=1; i<6; i++)
{
printf("\n\nInput %d: ", i);
scanf("%d", &a[i]);
printf("Sum test=%d", sum);
}
printf("\n\nSum=%d", sum); // why does it changes?
return 0;
}
sum never changes because you never modify it.
Furthermore, you have undefined behavior because the loop index is off by one, so you make scanf() write beyond the end of the array arr, which might by coincidence be the location where sum is stored, this would explain why you get Sum=4, the value of the last input.
C arrays are 0 based: use this:
for (i = 0; i < 5; i++)
You must also include the required standard header files and test the return value of scanf() to avoid undefined behavior on invalid input.
Here is a corrected version:
#include <stdio.h>
int main() {
int a[5], i, sum;
sum = 0;
printf("Sum=%d\n", sum);
for (i = 0; i < 5; i++) {
printf("\nInput %d: ", i);
if (scanf("%d", &a[i]) != 1)
break;
sum += a[i];
printf("Sum test=%d\n", sum);
}
printf("\nSum=%d\n", sum);
return 0;
}
Because you are looping over 1 to 6! And rewrite the value of sum here. To avoid this, you should iterate over the scope of the array, from index 0 to 4.
You should be aware that as the memory of sum is adjacent to the allocated memory of the array such a thing is happened, and it is not a rule!
array index starts with 0 so arr[5] is not allocated and the value you entered is given to sum
if atlast you give it as input 6 then the sum value is 6
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: ");
I tried everything to get standard deviation to work.
I'm trying to make a program that gets grades of students (count decided by user) and it calculates the mean of the grades and also the standard deviation. It calculates the mean fine but for standard deviation it gives "7712160851427328.00"
#include <stdio.h>
int main(){
int i;
int j;
int count;
int grade = 0;
int grades[5] = {0}; //Init
int sum = 0;
float deviation_sum;
float mean;
float standard_deviation;
printf("Give Count: ");
scanf("%d", &count);
for(i = 0; i < count; i++){
printf("Give %d grade: ", (i+1));
scanf("%d", &grade);
switch(grade){
case 0:
grades[0]++;
break;
case 1:
grades[1]++;
break;
case 2:
grades[2]++;
break;
case 3:
grades[3]++;
break;
case 4:
grades[4]++;
break;
case 5:
grades[5]++;
}
sum += grade;
}
mean = sum/count;
printf("mean: %.2f \n", mean);
for(i = 0; i <= 5; i++){
while(grades[i] == 0){
i++;
}
for(j = 0; j < grades[i]; j++){
deviation_sum += (i-mean)*(i-mean);
printf("%d,%d\n",i,j);
}
}
standard_deviation = sqrt(deviation_sum /count - 1);
printf("deviation: %.2f\n", standard_deviation);
}
I think the problem is in the last for loop just can't figure it out.
You'll have to initilize deviation_sum to zero. Otherwise it takes garbage value as its initial value
Your mean calculation will fail as you are doing integer division, and this will then make the subsequent std dev calculation incorrect.
Change:
mean = sum/count;
to
mean = (float)sum/count;
so that the division is performed using floating point arithmetic. You might also want to print the value of mean at this point to check that it looks reasonable.
Also this
standard_deviation = sqrt(deviation_sum /count - 1);
shall be
standard_deviation = sqrt(deviation_sum / (count - 1));
Please see here for the background.
First of all, avoid this type of construct (i could cause array access out-of-bounds):
for(i = 0; i <= 5; i++){
while(grades[i] == 0){
i++;
}
Use if instead of while and use continue to loop over again.
For correcting the error you are getting, do following changes in your code (I am just giving you hints)
1. Use typecasting where necessary
2. Monitor variables (especially array indices) for proper bounds
3. When using functions like sqrt, do check for positivity of the argument otherwise you may face Domain ERROR.
4. Always remember to initialize variables when required.
I would also suggest a task for you:
Try removing your switch with a simpler logic.