C programming help - adding values together/for loop - c

I'm trying to add values together that I get using a for loop but I'm stumped as to how to do it. This is the code I have so far:
float counter;
float harmonic;
float sum;
for (counter = 2; counter <= n; counter ++)
{
harmonic = 1/counter; // current value
sum = harmonic; // stores current value
}
return 0;
}
So basically for each value I get for the "harmonic" variable I need to add it to the next until the loop ends. Should I be looking at arrays? Thanks for any help.

Change your code to read
float sum = 0;
then inside the loop write
sum += harmonic;
You don’t need an array unless you want to remember all of the values you’ve summed.
Also, don’t use a float as your loop counter. You probably want an int instead.

Related

Need help solving a problem with an array

Task: Calculate the 25 values of the function y = ax'2 + bx + c on the interval [e, f], save them in the array Y and find the minimum and maximum values in this array.
#include <stdio.h>
#include <math.h>
int main()
{
float Y[25];
int i;
int x=3,a,b,c;
double y = a*pow(x,2)+b*x+c;
printf("a = ", b);
scanf("%d", &a);
printf("b = ", a);
scanf("%d", &b);
printf("c = ", c);
scanf("%d", &c);
for(i=0;i<25;i++)
{
printf("%f",y); //output results, not needed
x++;
}
system("pause");
}
Problems:
Cant understand how can I use "interval [e,f]" here
Cant understand how to save values to array using C libraries
Cant understand how to write/make a cycle, which will find the
minimum and maximum values
Finally, dont know what exactly i need to do to solve task
You must first ask the user for the values of a, b, c or initialize those variables, and ask for the interval values of e, f, or initialize those variables.
Now you must calculate double interval= (f - e)/25.0 so you have the interval.
Then you must have a loop for (int i=0, double x=e; i<25; i++, x += interval) and calculate each value of the function. You can choose to store the result in an array (declare one at the top) or print them directly.
Problems:
Cant understand how can I use "interval [e,f]" here
(f-e) / 25(interval steps)
Cant understand how to save values to array using C libraries
You need to use some form of loop to traverse the array and save the result of your calculation at every interval step. Something like this:
for(int i = 0; i < SIZE; i++)
// SIZE in this case 25, so you traverse from 0-24 since arrays start 0
Cant understand how to write/make a cycle, which will find the minimum and maximum values
For both cases:
traverse the array with some form of loop and check every item e.g. (again) something like this: for(int i = 0; i < SIZE; i++)
For min:
Initialize a double value(key) with the first element of your array
Loop through your array searching for elements smaller than your initial key value.
if your array at position i is smaller than key, save key = array[i];
For max:
Initialize a double value(key) with 0;
Loop through your array searching for elements bigger than your initial key value.
if your array at position i is bigger than key, save key = array[i];
Finally, dont know what exactly i need to do to solve task
Initialize your variables(yourself or through user input)
Create a function that calculates a*x^2 + b*x + c n times for every step of your interval.
Create a function for min & max that loops through your array and returns the smallest/biggest value.
Thats pretty much it. I will refrain from posting code(for now), since this looks like an assignment to me and I am confident that you can write the code with the information #Paul Ogilvie & I have provided yourself. Good Luck
#include<stdio.h>
#include<math.h>
int main()
{
double y[25];
double x,a,b,c,e,f;
int i,j=0;
printf("Enter a:",&a);
scanf("%lf",&a);
printf("Enter b:",&b);
scanf("%lf",&b);
printf("Enter c:",&c);
scanf("%lf",&c);
printf("Starting Range:",&e);
scanf("%lf",&e);
printf("Ending Range:",&f);
scanf("%lf",&f);
for(i=e;i<=f;i++)
{
y[j++]=(a*pow(i,2))+(b*i)+c;
}
printf("\nThe Maximum element in the given interval is %lf",y[j-1]);
printf("\nThe Minimum element in the given interval is %lf",y[0]);
}
Good LUCK!

how to write function which returns the position of the number in the array?

I have just started leran about C++. And I have to do one exercise but I don't know how. Please help me.
I have to write the function which returns the position of the number in the array,rate and size are pass to this function and the value of the expression|tab[i]_M| is the maximum, where M is the average of all the elements.
Thank you for your help
You will want to look at the values in your array one by one. You can access the individual values like this:
yourarray[index]
The best way to do it is a loop. There are several loops available in C++. You can use the for loop for example. Inside of the loop you check if the value is the one you are looking for
for (int i = 0; ...
{
if your array[i] == your value
If you found the value, break the loop and return the index i.
// Returns the index of the first occurrence of a value in the array, or -1 if not found
int GetPositionInArray(int array[], int value)
{
for (int i = 0; i < sizeof(array)/sizeof(int); i++) {
if (array[i] == value)
return i;
}
return -1;
}

finding how many times an element has repeated in c

I've got a c study which it must print all the numbers in an array then how many times they repeated.
int lottery(int a,int b,int c,int d,int e,int f,int i,int count)
{
printf("Enter the loop count:");
scanf("%d",&d);
a=time(NULL);
srand(a);
int genel[100][100];
int hepsi[50]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49};
count=0;
for(e=0;e<=d-1;e++)
{
for(b=0;b<=5;b++)
{
genel[e][b]=(rand()%49+1);
while(i>=0 && i<=49)
{
if(genel[e][b]==hepsi[i])
{
count=count+1;
}
else{
count=count;
}
}
printf("%d->%d\t",genel[e][b],count);
}
}
}
This doesnt work obviously. the output must be something like that
1-->0 2-->3 3-->15 etc
TY for your help, cheers :)
It is important that you understand what you are doing, naming is therefore very important. Nesting loops is okay if you know what you are doing. An easier to understand approach would be:
void lottery() {
int i, j //forloop counters
int randArray[100][100]; //array for random values
srand(Time(NULL)); //set random seed based on system time
//set random values
for(i = 0; i < 100; i++) {
for(j = 0; j < 100; j++) {
randArray[i][j] = rand()%49 + 1; //sets random ranging from 1 to 49 (49 incl)
}
}
//here you can start the counting procedure, which I won't spoil but ill give some hints below
}
There are a few options, first the easy lazy approach:
use a loop over all the values, 'int number' from 1 up to 49, inside that forloop use two forloops to search through the whole array, incrementing int x everytime you encounter the value 'number'. After youve searched through the whole array, you can use printf("%d -> %d", number, x); to print the value, set x to zero and count another number.
Another approach is as u tried,
create an array with for each number a location where you can increment a counter. Loop through the whole array now using two for-loops, increment the arraylocation corresponding to the value which youve found at randArray[i][j]. Afterwards print the array with counts using another forloop.
I suggest you try to clean up your code and approach, try again and come back with problems you encounter. Good luck!
sorry if this wasn't helpful to you, I tried to spoil not too much because according to my own experience programming should be learned by making mistakes.

What does this C code mean? Arrays and pointer variables

So I am instructed to write a function that uses the following prototype:
double stats(int *array, int size, double *std_dev);
The function should return the average value of the array. The argument std_dev is passed by reference so that the standard deviation of the data in the array can be returned. I assume this to mean that I need to calculate standard deviation as well.
I set about this in the following manner:
double stats(int *array, int size, double *std_dev){
int sum = 0; //declare int to hold sum
int i; //index used in for-loops
for (i = size; i>0; i--){ // for every element(i)
sum += array[i]; //add array element to
}
int mean = sum/size;
for (i = size; i>0; i--){ // for every element(i)
sum += array[i] -mean;
}
return 0;
}
The code compiles; but I'm not quite sure if these lines actually do what I think they do, and I don't have parameters to test with:
sum += array[i]; //add array element to
sum += array[i] -mean;
I know that "array" is a pointer variable, but I'm not exactly sure what it is my code is actually doing, can someone please tell me what these lines actually do? Thanks.
EDIT: I am aware that this code does not completely satisfy my objective, it is a WIP that compiles.
EDIT EDIT: That includes the logical correctness of my program.
when you do this
sum += array[i];
you are iterating through every element of the array - i.e., element at each index and storing the result in the variable sum.
a[i] is the ith element of the array a. It can be thought of as *(a+i).
Similarly in the second loop, you are adding up a[i] - sum to the variable sum. I think you are trying to compute the standard deviation in the second loop in which case you need to sum (a[i] - mean)^2 (i.e, square of difference from the mean) into the variable std_dev and then divide by size.
you have problems in your for:
you will never get to array[0] which is the first element in array
use for(i=0;i<size;i++)as for your question
sum +=array[i]; will put in variable sum the result of sum + array[i]
sum += array[i] -mean; will put in sumthe result of array - mean
BTW I have no idea what are you doing in second for loop (mathematically)
but if you don't want to use previous sum which contain the sum of all the array then you
should to set sum to 0 before you run the second for.
BTW, you returning 0
don't you want to return your average which is return mean; in your case ?
in function prototype it says function should return double
what you've done is int mean = sum/size; is an integer value that will cut the numbers after the "."
you probably want to use double mean = sum/size;
and then to return it as I have mentioned before.

C, pgcc - automatic parallelization "not countable"

I use this for loop, which I want to have parallelizide automaticaly, it is used for count of PI number:
piece=1.0/100000;
for (t=0.0; t<1.0; t=t+piece){
x=t+piece/(float)2;
if(x<=1.0){
integral=4/(1+x*x);
sum=sum+integral;
}
}
This is doint partial sum for all values in interval 0-1. Then I made from it PI value. But this is not the problem, problem is, when I use automatic parallelization with pgcc, I set up number of processes but I am told that "Loop not vectorized/parallelized: not countable" when I am compiling my program. I have tried everything, but still no change. Any ideas? Thanks
Your loop variable is a double, try changing the code so it uses an integer:
for (int t = 0; t < 100000; t++) {
x=(t/100000.0)+piece/(float)2;
if(x<=1.0){
integral=4/(1+x*x);
sum=sum+integral;
}
}
I'm guessing this is because your loop counter is a float or double. Try using an integral counter.
int step;
for (step = 0; step < 100000; step++) {
// determine x from step
...
}

Resources