I'm supposed to do a freqency analysis of a user input array. User may enter as many numbers between 0-1000 as s/he wants and a maximum of 100 numbers can be entered, user ends input by entering a negative number. A void function will calculate which number appears the most times and those 2 variables should be sent to the function as pointers.
My problem is that no matter what I do the analysis seems to calculate all the "empty" elements of the array and I can't figure out what I'm doing wrong. If i make the array smaller to lets say 10 elements it works fine. As I'm a complete novice when it comes to programming and I've changed the code about a million times so at this point I can't remeber what I've changed from my original code. When debugging I get stuck in the second for loop in the function..
#include <stdio.h>
#define MAX 100
#define INTERVAL 1000
void frequencyAnalysis(int array[],int *number, int *freq)
{
int element = 0, count = 0;
for (int i = 0; i < MAX; i++) {
int tempElement = array[i];
int tempCount = 0;
for (int j = 0; j < MAX; j++)
if (array[j] == tempElement)
tempCount++;
if (tempCount > count) {
element = tempElement;
count = tempCount;
}
}
*number = element;
*freq = count;
}
int main(void)
{
int array[MAX], i, j, number = 0, freq = 0;
printf("Hello.\n"
"Please enter a number between 0-1000. "
"Enter as many number as you want (maximum 100).\n"
"Exit by entering a negative number.\n\n");
printf("Enter a number:\n");
for (i = 0; i < MAX; i++) {
scanf("%d", &array[i]);
if (array[i] < 0)
break;
}
frequencyAnalysis(array, &number, &freq);
printf("The number:%d is the most frequent number and appears %d times.\n", number, freq);
return 0;
}
Addressing the first issue, pass in how many items the user actually entered so you're not running up to MAX (which would include all the unused cells). The key is nitems.
void frequencyAnalysis(int array[], int nitems, int *number, int *freq)
{
for (int i = 0; i < nitems; i++) {
...
for (int j = 0; j < nitems; j++)
{
// do stuff
}
}
}
int main(void)
{
int array[MAX],i, j, number = 0, freq = 0;
...
frequencyAnalysis(array, i, &number,&freq);
///
}
Related
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].
#include <stdio.h>
void main()
{
int array[100], i, num,diff;
printf("Enter the size of an array \n");
scanf("%d", &num);
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
printf("\n Numbers in a.p: ");
for (i = 0; i < num; i++) {
diff = array[i+1]-array[i];
if (array[i]-diff == array[i+1]-diff);
{
printf("%d, ", array[i]);
}
}
printf("\n Common difference:%d", diff);
}
like this
#include <stdio.h>
int main(void){
#if DEBUG
int array[] = {5,1,2,4,6,8,12};
int num = sizeof(array)/sizeof(*array);
int i, diff;
#else
int array[100], i, num,diff;
printf("Enter the size of an array \n");
scanf("%d", &num);
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
#endif
int j, len, longest_len = 2, longest_i = 0;
for (i = 0; i < num - longest_len; i += len-1) {
diff = array[i+1]-array[i];
for(j = i+2; j < num && array[j-1]+diff == array[j]; ++j);
len = j - i;
if(longest_len < len){
longest_len = len;
longest_i = i;
}
}
printf("\n Numbers in a.p: ");
diff = array[longest_i+1] - array[longest_i];
printf("[ ");
for(i = 0; i < longest_len; ++i){
printf("%d", array[longest_i + i]);
if(i == longest_len-1)
printf(" ]\n");
else
printf(", ");
}
printf("\n Common difference:%d", diff);
}
Since this seems to be a homework or challenge I will only help by solving your immediate problems, caused by very strange code.
Here is code which at leat detects the progressions correctly.
You can yourself count the length, store the longest length and its index, then print that sequence after parsing all the array.
There are two assumptions here, which you might want to avoid for challenge/homework:
no identical numbers entered
no overlapping progressions,
i.e. no number is the last of one and the first of next progression
The representation of more than one sequence in the output is a little jittery (missing ")"), but that is not relevant for finding and exclusively printing the longest one.
I did not bother about your ratio output, no idea what that is supposed to be.
Code:
#include <stdio.h>
// avoid a warning
int main() {
int array[100], i, num, diff=0, lastdiff=0, first=1;
printf("Enter the size of an array \n");
// for good code, this should check the result
scanf("%d", &num);
// in case of scaf-failure, cleanup here for good code
// asking for the number of elements
// and then relying on that number to be entered
// is less elegant than checking for and end condition
// like EOF or negative input
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
// for good code, this should check the result
scanf("%d", &array[i]);
// in case of scaf-failure, cleanup here for good code
}
printf("\n Numbers in a.p: ");
for (i = 1; i < num; i++) {
lastdiff=diff;
diff = array[i]-array[i-1];
if (diff==lastdiff)
{ if(first==1)
{ first=0;
printf("(%d, %d",array[i-2], array[i-1]);
}
printf(", %d", array[i]);
} else
{ first=1;
}
}
printf(")\n Ratio:%d", diff);
// avoid a warning
return 0;
}
There are a number of ways to approach this challenge. You can either check each diff against each value in the array or work the other way around. Given you are not sorting the values, you may benefit by nesting the check of values within your loop over all possible diffs. Something similar to the following works:
#include <stdio.h>
int main (void) {
int a[] = {5, 1, 2, 4, 6, 8, 12},
n = sizeof a / sizeof *a,
startidx = 0,
maxlen = 0;
for (int d = 1; d < n; d++) { /* loop over diffs */
int idx = -1,
len = 1;
for (int i = 1; i < n; i++) /* loop over values */
if (a[i - 1] + d == a[i]) {
if (idx < 0) /* if index not set */
idx = i - 1; /* set to 1st index */
len++; /* increment length */
}
if (idx >= 0 && len > maxlen) { /* if progression found */
maxlen = len; /* save length */
startidx = idx; /* save start index */
}
}
printf ("longest progression: '%d' elements.\n", maxlen);
for (int i = 0; i < maxlen; i++)
printf (i ? ", %d" : "%d", a[startidx + i]);
putchar ('\n');
return 0;
}
Example Use/Output
$ ./bin/maxprogression
longest progression: '4' elements.
2, 4, 6, 8
Investigate several ways to approach it, and finally settle on the one that makes the most sense to you. You can work on optimizing later.
As far as the code you posted goes, always validate all user input by, at minimum, checking that the number of expected conversions to type took place, e.g.
if (scanf("%d", &num) != 1) {
fprintf (stderr, "error: input conversion failed for 'num'.\n");
return 1;
}
You would do the same in your values loop. Let me know if you have any questions. Good luck with your coding.
Following is the complete working code. You can see it working here:
#include <stdio.h>
int main()
{
int array[100], i, num,diff, resDiff, startIndx, resStartIndx, countCur, countPre;
printf("Enter the size of an array \n");
scanf("%d", &num);
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
//Now code changes
startIndx =0, resStartIndx=0, countPre=0, resDiff=0;
for (i = 0; i < num; /*No increment required here*/) {
countCur =0;
startIndx=i;
countCur++;
if(++i < num)
{
diff = array[i] - array[startIndx];
countCur++;
i++;
while((i < num) && (diff == (array[i] - array[i-1])))
{
countCur++;
i++;
}
if(countCur > countPre)
{
resStartIndx = startIndx;
countPre = countCur;
resDiff = diff;
}
}
}
countPre += resStartIndx;
printf("\n Numbers in a.p: ");
for (i = resStartIndx; i < countPre; i++) {
printf("%d, ", array[i]);
}
printf("\n Common difference:%d", resDiff);
return 0;
}
Given an unsorted array A[0...n-1] of integers and an integer k; the desired algorithm in C should calculate the maximum value of every contiguous subarray of size k. For instance, if A = [8,5,10,7,9,4,15,12,90,13] and k=4, then findKMax(A,4,10) returns 10 10 10 15 15 90 90.
My goal is to implement the algorithm as a C programm that reads the elements of A, reads k and then prints the result of the function findKMax(A,4,10). An input/output example is illustrated bellow (input is typeset in bold):
Elements of A: 8 5 10 7 9 4 15 12 90 13 end
Type k: 4
Results: 10 10 10 15 15 90 90
What I've tried so far? Please keep in mind that I am an absolute beginner in C. Here is my code:
#include <stdio.h>
void findKMax(int A[], int k, int n) {
int j;
int max;
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
}
}
int main() {
int n = sizeof(A);
int k = 4;
printf("Elements of A: ");
scanf("%d", &A[i]);
printf("Type k: %d", k);
printf("Results: %d", &max);
return 0;
}
Update March 17th:
I've modified the source code, i.e. I've tried to implement the hints of Michael Burr and Priyansh Goel. Here is my result:
#include <stdio.h>
// Returning the largest value in subarray of size k.
void findKMax(int A[], int k, int n) {
int j;
int largestValueOfSubarray;
for (int i = 0; i <= n-k; i++) {
largestValueOfSubarray = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > largestValueOfSubarray)
largestValueOfSubarray = A[i+j];
}
printf("Type k: %d", k);
}
return largestValueOfSubarray;
}
int main() {
int n = 10;
int A[n];
// Reading values into array A.
for (int i = 0; i < n; i++) {
printf("Enter the %d-th element of the array A: \n", i);
scanf("%d", &A[i]);
}
// Printing of all values of array A.
for (int i = 0; i < n; i++) {
printf("\nA[%d] = %d", i, A[i]);
}
printf("\n\n");
// Returning the largest value in array A.
int largestValue = A[0];
for (int i = 0; i < n; i++) {
if (A[i] > largestValue) {
largestValue = A[i];
}
}
printf("The largest value in the array A is %d. \n", largestValue);
return 0;
}
I guess there is not so much to code. Can anybody give me a hint how to do the rest. I need an advice how to "combine" the pieces of code into a running program.
Since you are a beginner, lets begin with the simplest algorithm.
for every i, you need to find sum of k continous numbers starting from that i. And then find the max of it.
Before that you need to see how to take input to an array.
int n;
scanf("%d",&n);
int a[n];
for(int i = 0; i < n; i++) {
scanf("%d",&a[i]);
}
Also, you will need to call the function findKMax(a,n,k);
In your findKMax function, you have to implement the algorithm that I mentioned.
I will not provide the code so that you may try on your own. If you face any issue, do tell me.
HINT : You need to use nested loops.
You find max value in window many times, but output only the last max value.
The simplest correction - add output in the end of main cycle:
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
printf("Type k: %d", k);
}
The next step - collect all local max values in a single string "10 10 10 15 15 90 90" or additional array of length n-k+1: [10,10,10,15,15,90,90] and print it after the main cycle (I don't know the best approach for this in C)
I have been figuring out how to scramble numbers from array after user enters 10 different numbers by using rand(). It crushes when it arrives to adjust() function so feel free to point out my stupid mistake. Cheers. The top part is function, the bottom part is in main().
void adjust(int z[], int size)
{
int i, n, t;
for(i = 0; i < size; i++)
{
size = rand();
t = z[size];
z[size] = z[i];
z[i] = t;
}
printf("\nYour numbers have been scrambled and here they are: \n", t);
}
.....................
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = num; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
addNum(z, 10);
adjust(z, 10);
return 0;
The rand() function returns a number between 0 and RAND_MAX.
Hence, the array index can go well beyond its range.
To get a random index within a range from 0 to N -1 , use rand() % N.
Another issue is that in your for loop, in adjust function, you are destroying the original value of 'size'. That contains the length of your array and is used to check the terminating condition of your for loop. Hence, do not modify 'size'. Use another variable to store your random index.
for(i = 0; i < size; i++)
{
n = rand() % size; // n is between 0 and size-1
t = z[n];
z[n] = z[i];
z[i] = t;
}
// For a better design move the following lines to a separate function
// that way adjust function just does the scrambling while another
// printing function prints out the array. Each function does only one thing.
printf("\nYour numbers have been scrambled and here they are: \n");
for( i = 0; i < size; i++)
{
printf("%d ", z[i]);
}
The code I have written solves the basic coin change problem using dynamic programming and gives the minimum number of coins required to make the change. But I want to store the count of each coin playing part in the minimum number.
What I am trying to do is initializing an array count[] and just like hashing it increments the number of coin[j] whenever min is found, i.e count[coin[j]]++ .
But this is not working the way I wanted because it adds the coin every time it finds min corresponding to coin[j]. Hence the number is not the final count of coin in the final answer.
Here is the code:
void makeChange(int coin[], int n, int value)
{
int i, j;
int min_coin[MAX];
int min;
int count[MAX];
min_coin[0] = 0;
for (i=1; i <= value; i++)
{
min = 999;
for (j = 0; j<n; j++)
{
if (coin[j] <= i)
{
if (min > min_coin[i-coin[j]]+1)
{
min = min_coin[i-coin[j]]+1;
count[coin[j]]++;
}
}
}
min_coin[i] = min;
}
printf("minimum coins required %d \n", min_coin[value]);
}
You have to keep an extra, two-dinemsional array to store the coin count for each value and each coin denomination.
When you assign a new minimum in your inner loop, copy all coin counts from i - coin[j] to i and then increment min_count[i][j]. The number of coins needed is then in coin_count[value].
As you already noted, the bottom-up solution adds the coin every time, not only when i == value, but if you want to know the count of coins when i == value, it depends on the the counts of coins of sub-problems, so we need store previous computations with a 2-D array:
#include <stdio.h>
#define MAX 1000
#define COIN_ARRAY_SIZE 4
void makeChange(int coin[], int n, int value)
{
int i, j, k;
int min_coin[MAX];
int count[MAX + 1][COIN_ARRAY_SIZE] = {0}; // zeroing
int min;
//int count[MAX];
min_coin[0] = 0;
for (i=1; i <= value; i++)
{
min = 999;
for (j = 0; j<n; j++)
{
if (coin[j] <= i)
{
if (min > min_coin[i-coin[j]]+1)
{
min = min_coin[i-coin[j]]+1;
for(k = 0; k < n; ++k)
{
count[i][k] = count[i-coin[j]][k]; // copy coin counts when value=i-coin[j]
}
count[i][j]++; // use a coin[j], increase the count
}
}
}
min_coin[i] = min;
}
printf("minimum coins required %d \n", min_coin[value]);
for(int i = 0; i < COIN_ARRAY_SIZE; ++i)
printf("%d: %d\n", coin[i], count[value][i]);
}
Driver program to test above function:
int main()
{
int coin[COIN_ARRAY_SIZE] = {5,3,2,1};
makeChange(coin, 4, 8);
makeChange(coin, 4, 10);
};
I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
INPUT
Input contains two lines. First line in the input indicates N,
the number of integers in the sequence. Second line contains N
integers, separated by white space.
OUTPUT
Element with the maximum frequency. If two numbers have the
same highest frequency, print the number that appears first in the
sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range
[-100,100].
And here's the test cases.
Test Case 1
Input:
5
1 2 1 3 1
Output:
1
Input:
6
7 7 -2 3 1 1
Output:
7
And here's the code that I've written.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by #zoska. Here's the working code.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
for(i = 0; i < 201; i++)
Otherwise you won't be using count[0] and you will only have a range of -99...100.
Try below code
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input >= -100 && input <= 100)
++counter[input + 100];
}
maximum = counter[0];
int index = 0;
for (i = 0; i < 201; i++) {
if (counter[i] >= maximum) {
index = i;
maximum = counter[i];
}
}
printf("number %d occured %d times\n", index-100, maximum);
return 0;
}
I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
But, there is also one condition that if the number of occurance are same for two numbers then the number which appers first in sequence should appear.