I need to add two vectors in the arrays together. For example my code should execute the vector = {3,6,9}.
I dont really know what I did wrong as I am still new to coding. So any help is appreciated!
void add_vectors( double vector1[3]={1,2,3},double vector2[3]={1,2,3},double
vector3[3]={1,2,3}, int n)
{
n=sizeof(vector1);
int i;
for(i=0; i>n; i++)
{
scanf("%f", &vector1[i]);
scanf("%f", &vector2[i]);
vector3[i]=vector1[i]+vector2[i];
}
printf (vector3[]);
Sorry for the bad formatting but it's my frist time using this site.
There are several mistakes here in the code:
First, sizeof() gives you a size of something in a memory (in bytes), which is probably not what you desire.
Secondly, i>n statement means that the loops will execute only while i > n! The first time i = 0, and n is a positive integer. That means that the loop will be skipped, since i is not larger than n.
Third, printf() does not work like this.
I explained you the second point; my first and third points are widely explained on the internet: try finding these answers yourself.
Related
I'm writing a program to track the number of rectangles being made in one week using the exponential growth function (X = a(1+b)^t). One person can make 60 rectangles per day.
a represents the initial population, this is the number of people already making rectangles on the first of the week. b represents the growth rate, this is the number of new people making rectangles each day. t represents the time interval, which is 7 days for this program.
I'm having difficulties getting started with the problem, and I need some guidance please.
I was thinking using using math.h and pow, something like this (this code is not compiling)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int initial_POPULATION;
int time_INTERVAL;
double growth_RATE;
printf("How many people are making rectangles at the
biginning of the week?\n");
scanf("%d", &initial_POPULATION);
printf("How many people are making rectangles each day?
\n");
scanf("%1f", &growth_RATE);
//Exponential growth function X = a(1+b)^t
printf("%d rectangles will be made this week!\n",
initial_POPULATION(pow(1+growth_RATE),time_INTERVAL));
return 0;
}
There are a couple problems, but the most apparent is that you are not setting the value of time_INTERVAL anywhere. Next is the line where the final value is calculated: in C, you need to use * to denote multiplication. Parens do not work as implied multiplication operators like in regular math (at any rate, the way the parenthesis are being used in the last printf is not right). Finally, make sure to read growth_RATE as a double by using %lf as the format specifier in scanf (using %f reads it as a single precision 4-byte value, even though it's declared as a double which is... well, double that).
Try this:
scanf("%lf", &growth_RATE);
time_INTERVAL=7;
printf("%f rectangles will be made this week!\n", initial_POPULATION * pow(1+growth_RATE, time_INTERVAL));
Also, as mentioned by #Asadefa, remove the line breaks from the string literals.
There are 4 possible reasons your code isn't compiling.
Did you try compiling like this if you're using unix, with -lm?
gcc /path/to/file.c -lm -o /path/to/outputfile
Also, you cannot have line breaks in string literals. This isn't allowed:
char *MyString = "Hello
World";
On top of that, you are trying to call initial_POPULATION (int) as if it were a function:
initial_POPULATION(pow(1+growth_RATE),time_INTERVAL)
Maybe you meant:
initial_POPULATION*(pow(1+growth_RATE),time_INTERVAL)
And lastly, time_INTERVAL is uninitialized, as brought up by #Z4-tier.
I got the task in university to realize an input of a maximum of 10 integers, which shall be stored in a one dimensional vector. Afterwards, every integer of the vector needs to be displayed on the display (via printf).
However, I don't know how to check the vector for each number. I thought something along the lines of letting the pointer of the vector run from 0 to 9 and comparing the value of each element with all elements again, but I am sure there is a much smarter way. I don't in any case know how to code this idea since I am new to C.
Here is what I have tried:
#include <stdio.h>
int main(void)
{
int vector[10];
int a;
int b;
int c;
a = 0;
b = 0;
c = 0;
printf("Please input 10 integers.\n\n");
while (a <= 10);
{
for (scanf_s("%lf", &vektor[a]) == 0)
{
printf("This is not an integer. Please try again.\n");
fflush(stdin);
}
a++;
}
for (b <= 10);
{
if (vector[b] != vector[c]);
{
printf("&d", vector[b]);
c++;
}
b++;
}
return 0;
}
Your code has several problems, some syntactic and some semantic. Your compiler will help with many of the former kind, such as
misspelling of variable name vector in one place (though perhaps this was a missed after-the-fact edit), and
incorrect syntax for a for loop
Some compilers will notice that your scanf format is mismatched with the corresponding argument. Also, you might even get a warning that clues you in to the semicolons that are erroneously placed between your loop headers and their intended bodies. I don't know any compiler that would warn you that bad input will cause your input loop to spin indefinitely, however.
But I guess the most significant issue is that the details of your approach to printing only non-duplicate elements simply will not serve. For this purpose, I recommend figuring out how to describe in words how the computer (or a person) should solve the problem before trying to write C code to implement it. These are really two different exercises, especially for someone whose familiarity with C is limited. You can reason about the prose description without being bogged down and distracted by C syntax.
For example, here are some words that might suit:
Consider each element, E, of the array in turn, from first to last.
Check all the elements preceding E in the array for one that contains the same value.
If none of the elements before E contains the same value as E then E contains the first appearance of its value, so print it. Otherwise, E's value was already printed when some previous element was processed, so do not print it again.
Consider the next E, if any (go back to step 1).
I am new to online judges. I solved a problem getting correct output on my PC but online judge is directly saying wrong answer.
Here is the problem https://www.codechef.com/problems/HORSES
This question deals with only shortest difference between elements of array.
My solution may not be efficient but it is correct.
Please help me
Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horses are comparable on their skill i.e. the difference in their skills is less.
There are N horses in the stable. The skill of the horse i is represented by an integer S[i]. The Chef needs to pick 2 horses for the race such that the difference in their skills is minimum. This way, he would be able to host a very interesting race. Your task is to help him do this and report the minimum difference that is possible between 2 horses in the race.
Input:
First line of the input file contains a single integer T, the number of test cases.
Every test case starts with a line containing the integer N.
The next line contains N space separated integers where the i-th integer is S[i].
You can read the problem here https://www.codechef.com/problems/HORSES
#include<stdio.h>
#include<limits.h>
int main(){
int t,n,i,u,v;
int min=INT_MAX;
scanf("%d",&t);
while(t>0){
scanf("%d",&n);
int *s=malloc(sizeof(int)*n);
for(i=0;i<n;i++){
scanf("%d",&s[i]);
}
for(i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(min>abs(s[i]-s[j]))
min=abs(s[i]-s[j]);
}
}
printf("%d\n",min);
t--;
}
}
I solved a problem getting correct output on my PC but online judge is directly saying wrong answer.
Insufficient testing. Code is correct when t ==1, yet not for t > 1.
Code needs to reset the minimum for each test case.
// int min=INT_MAX;
scanf("%d",&t);
while(t>0){
int min = INT_MAX; // add
Other short-comings exists too, yet the above is key.
Robust code would:
Check the return value of scanf()
Check that malloc() succeeded and then later free it.
Address potential; overflow in abs(s[i]-s[j])
Also
Consider delaying variable declaration to the block that needs it. Had OP done this, the above problem would not have occurred.
Format code more uniformly and use {} even with single line blocks with for, if, ....
Efficiency
Sort the array first (qsort()) and then walk the array noting difference between elements. O(n*lg(n))
I'm trying to learn how to optimize code (I'm also learning C), and in one of my books there's a problem for optimizing Horner's method for evaluation polynomials. I'm a little lost on how to approach the problem. I'm not great at recognizing what needs optimizing.
Any advice on how to make this function run faster would be appreciated.
Thanks
double polyh(double a[], double x, int degree) {
long int i;
double result = a[degree];
for (i = degree-1; i >= 0; i--)
result = a[i] + x*result;
return result;
}
You really need to profile your code to test whether proposed optimizations really help. For example, it may be the case that declaring i as long int rather than int slows the function on your machine, but on the other hand it may make no difference on your machine but might make a difference on others, etc. Anyway, there's no reason to declare i a long int when degree is an int, so changing it probably won't hurt. (But still profile!)
Horner's rule is supposedly optimal in terms of the number of multiplies and adds required to evaluate a polynomial, so I don't see much you can do with it. One thing that might help (profile!) is changing the test i>=0 to i!=0. Of course, then the loop doesn't run enough times, so you'll have to add a line below the loop to take care of the final case.
Alternatively you could use a do { ... } while (--i) construct. (Or is it do { ... } while (i--)? You figure it out.)
You might not even need i, but using degree instead will likely not save an observable amount of time and will make the code harder to debug, so it's not worth it.
Another thing that might help (I doubt it, but profile!) is breaking up the arithmetic expression inside the loop and playing around with order, like
for (...) {
result *= x;
result += a[i];
}
which may reduce the need for temporary variables/registers. Try it out.
Some suggestion:
You may use int instead of long int for looping index.
Almost certainly the problem is inviting you to conjecture on the values of a. If that vector is mostly zeros, then you'll go faster (by doing fewer double multiplications, which will be the clear bottleneck on most machines) by computing only the values of a[i] * x^i for a[i] != 0. In turn the x^i values can be computed by careful repeated squaring, preserving intermediate terms so that you never compute the same partial power more than once. See the Wikipedia article if you've never implemented repeated squaring.
#include<stdio.h>
int fact(int k)
{
int j,f=1;
for(j=1;j<=k;j++)
f*=j;
return f;
}
int main()
{
int t,i,n[100],s[100],j;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d",&n[i]);
}
for(j=0;j<t;j++)
{
s[j]=fact(n[j]);
printf("%d \n",s[j]);
}
return 0;
}
You are asked to calculate factorials of some small positive integers.
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
Your code will give correct results for the given test cases but that doesn't prove that your code works. It is wrong is because of integer overflow. Try to calculate 100! by your program and you'll see what's the problem.
My answer lacked details. I'll update this to add details for an answer to the question as it stands now.
C has limitations over the the maximum and minimum size that can be stored in a variable. For doing arbitrary precision arithmetic it is usually advisable to use a bignum library as PHIFounder has suggested.
In the present case however, the use of external libraries is not possible. In this case arrays can be used to store integers exceeding the maximum value of the integers possible. OP has already found this possibility and used it. Her implementation, however, can use many optimizations.
Initially the use of large arrays like that can be reduced. Instead of using an array of 100 variables a single variable can be used to store the test cases. The use of large array and reading in test cases can give optimization only if you are using buffers to read in from stdin otherwise it won't be any better than calling scanf for reading the test cases by adding a scanf in the for loop for going over individual test cases.
It's your choice to either use buffering to get speed improvement or making a single integer instead of an array of 100 integers. In both the cases there will be improvements over the current solution linked to, on codechef, by the OP. For buffering you can refer to this question. If you see the timing results on codechef the result of buffering might not be visible because the number of operations in the rest of the logic is high.
Now second thing about the use of array[200]. The blog tutorial on codechef uses an array of 200 elements for demonstrating the logic. It is a naive approach as the tutorial itself points out. Storing a single digit at each array location is a huge waste of memory. That approach also leads to much more operations leading to a slower solution. An integer can at least store 5 digits (-32768 to 32767) and can generally store more. You can store the intermediate results in a long long int used as your temp and use all 5 digits. That simplification itself would lead to the use of only arr[40] instead of arr[200]. The code would need some additional changes to take care of forward carry and would become a little more complex but both speed and memory improvements would be visible.
You can refer to this for seeing my solutions or you can see this specific solution. I was able to take the use down to 26 elements only and it might be possible to take it further down.
I'll suggest you to put up your code on codereview for getting your code reviewed. There are many more issues that would be best reviewed there.
Here, your array index should start with 0 not 1 , I mean j and ishould be initialized to 0 in for loop.
Besides, try to use a debugger , that will assist you in finding bugs.
And if my guess is right you use turbo C, if yes then my recommendation is that you start using MinGW or Cygwin and try to compile on CLI, anyway just a recommendation.
There may be one more problem may be which is why codechef is not accepting your code you have defined function to accept the integer and then you are passing the array , may be this code will work for you:
#include<stdio.h>
int fact(int a[],int n)// here in function prototype I have defined it to take array as argument where n is array size.
{
int j=0,f=1,k;
for (k=a[j];k>0;k--)
f*=k;
return f;
}
int main()
{
int t,i,n[100],s[100],j;
setbuf(stdout,NULL);
printf("enter the test cases\n");
scanf("%d",&t); //given t test cases
for(i=0;i<t;i++)
{
scanf("%d",&n[i]); //value of the test cases whose factorial is to be calculated
}
for(j=0;j<t;j++)
{
s[j]=fact(&n[j],t);// and here I have passed it as required
printf("\n %d",s[j]); //output
}
return 0;
}
NOTE:- After the last edit by OP this implementation has some limitations , it can't calculate factorials for larger numbers say for 100 , again the edit has taken the question on a different track and this answer is fit only for small factorials
above program works only for small numbers that means upto 7!,after that that code not gives the correct results because 8! value is 40320
In c language SIGNED INTEGER range is -32768 to +32767
but the >8 factorial values is beyond that value so integer cant store those values
so above code can not give the right results
for getting correct values we declare the s[100] as LONG INT,But it is also work
only for some range