Dynamic arrays C - c

So I am creating array and I need to find the number with highest divisors count, print the number, the count and divisors in decline order, if I create array with only 1 number my function works properly, but if I create it with 2 or more some divisors are changed into incorrect ones.
void calculate(int *data, int size){
int max;
int divisors[size][size];
int divisorssize[size];
//Checking for the divisors
for (int i = 0; i < size; i++){
divisorssize[i] = 0;
for (int j = data[i]; j >= 1; j--) {
if (data[i] % j == 0) {
divisorssize[i]++;
divisors[i][divisorssize[i]] = j;
}
}
}
//Searching for the number in the array with the highest divisors count
max = 0;
for (int i = 0; i < size; i++){
if (divisorssize[max] < divisorssize[i]){
max = i;
}
}
//divisors Output
printf("Max divisors: %d\n", data[max]);
printf("divisors count: %d\n", divisorssize[max]);
printf("divisors list: ");
for (int i = 1; i <= divisorssize[max]; i++){
printf("%d ", divisors[max][i]);
}
}
Function usage :
calculate(data, size);
So when I create array with size = 1; And input number 56 it shows all divisors: 56 28 14 8 7 4 2 1, but if for example the size is 2 and I input 56 and 1, it changes the divisors into this 56 28 1 8 7 4 2 1.

The problem is with your array sizes.
For example, with size 2
int arr[size][size];
Will be
int arr[2][2];
That is fine, as long as no number has more than two divisors...
The size of the second dimension needs to be big enough for any divisor count.
For example, find the largest number in *data, and use that
int array[size][max_number];

Related

Counting and deleting repeated digits of array elements

I need to write a program that allows user to enter an array of integers, finds the digit that appears most often in all entered numbers, and removes it from the elements of the array. If several digits appear the same number of times, the smallest of them should be deleted. If all digits of the element of the array are deleted, that element should become zero. In the end, such a modified array is printed.
Example of input and output:
Enter number of elements of the array: 5
Enter the array: 3833 8818 23 33 1288
After deleting, the array is: 8 8818 2 0 1288
Explanation: The numbers 3 and 8 appear the same number of times (6 times each), but 3 is less, so it was removed it from all members of the array. Element 33 consists exclusively of the digits 3, so that it becomes 0.
#include <stdio.h>
int main() {
int i,n,arr[100]; n;
printf("Enter number of elements of the array: ");
scanf("%d", &n);
printf("Enter the array: ");
for(i=0;i<n;i++) {
scanf("%d", &arr[i]);
}
return 0;
}
EDIT: I'm beginner to programming, and this task should be done using only knowledge learned so far in my course which is conditionals, loops, and arrays. This shouldn't be done with strings.
Divide the problem into separate tasks.
Write the code
In the code below I do not treat 0 as having digit 0. It is because it is not possible to remove 0 from 0. You can easily change this behaviour by changing while(){} loop to do{}while()
int removeDigit(int val, int digit)
{
int result = 0;
unsigned mul = 1;
int sign = val < 0 ? -1 : 1;
digit %= 10;
while(val)
{
int dg = abs(val % 10);
if(dg != digit)
{
result += dg * mul;
mul *= 10;
}
val /= 10;
}
return sign * result;
}
void countDigits(int val, size_t *freq)
{
while(val)
{
freq[abs(val % 10)]++;
val /= 10;
}
}
int findMostFrequent(const size_t *freq)
{
size_t max = 0;
for(size_t i = 1; i < 10; i++)
{
if(freq[i] > freq[max]) max = i;
}
return (int)max;
}
int main(void)
{
int table[20];
size_t freq[10] = {0,};
int mostfreq = 0;
srand(time(NULL));
for(size_t i = 0; i < 20; i++)
{
table[i] = rand();
printf("Table[%zu] = %d\n", i, table[i]);
countDigits(table[i], freq);
}
mostfreq = findMostFrequent(freq);
printf("Most frequent digit: %d\n", mostfreq);
for(size_t i = 0; i < 20; i++)
{
table[i] = removeDigit(table[i], mostfreq);
printf("Table[%zu] = %d\n", i, table[i]);
}
}
https://godbolt.org/z/PPj9s341b

How can we replace the higest 5 numbers in an array of 10 with 1 and smallest 5 into 0 in C programing?

Here's the question my teacher gave me
Write a C program to store 10 integers in an array of size 10 and
display the contents of the array. Replace the highest 5 numbers in the array by
1 and lowest 5 numbers by 0 and display the contents of the new array.
[For e.g.
Original Array
44 11 6 99 30 78 32 31 66 55
New Array
1 0 0 1 0 1 0 0 1 1
I have been struggling in this question whole day :(
There are a lot of ways to solve this problem. A good way would be sort the array into another array and then replace the 1st half with 0s and the second half with 1s like this:
#include<stdio.h>
int main(){
const int arraySize = 10;
int i, j;
int arr[arraySize];
int arrSorted[arraySize];
int temp;
// Get input from user
printf("Please enter 10 numbers!\n");
for (i = 0; i < arraySize; i++)
{
scanf("%d", &arr[i]);
// Copy array into another to sort it later
arrSorted[i] = arr[i];
}
// Print input
printf("Input: ");
for (i = 0; i < arraySize; i++)
{
printf("%3d ", arr[i]);
}
printf("\n");
//Sort the array in ascending order
for (i = 0; i < arraySize; i++)
{
for (j = i + 1; j < arraySize; j++)
{
if(arrSorted[i] > arrSorted[j])
{
temp = arrSorted[i];
arrSorted[i] = arrSorted[j];
arrSorted[j] = temp;
}
}
}
// Start replacing procedure
for (i = 0; i < arraySize; i++)
{
for (j = 0; j < arraySize; j++)
{
if (arr[j] == arrSorted[i])
{
if (i < arraySize / 2) // Replace 1st half with 0s
{
arr[j] = 0;
}
else // Replace 2nd half with 1s
{
arr[j] = 1;
}
break;
}
}
}
// Print result
printf("Result: ");
for (i = 0; i < arraySize; i++)
{
printf("%3d ", arr[i]);
}
printf("\n");
return 0;
}
Of course, you can use the C standard library qsort() function if you don't want to sort yourself.
Another solution would be, find the median number of the array then replace any number which is less than it with 0 and any number bigger than it with 1. Although with this solution there will be some challenges regarding what to do with the median number itself and what if there are multiple median numbers (duplicated)?

Function not initializing

Hi I have problem with initializing my function for printing an error message if some numbers in an array are same.
#include<stdio.h>
#include<stdlib.h>
void printRepeating(int arr[], int size)
{
int i, j;
for(i = 0; i < size; i++)
for(j = i+1; j < size; j++)
if(arr[i] == arr[j])
printf("Wrong input. Same numbers in array!\n");
}
int main()
{
int arr[200],i;
int res, num;
while((res = scanf("%d", &num)) == 1)
{
arr[i++] = num;
if(num == 0){
break;
}
}
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
printf("\n");
int arr_size = sizeof(arr[i])/sizeof(arr[0]);
printRepeating(arr, arr_size);
return 0;
}
If I scan 1 2 3 1 4 5 0, my function printRepeating wont start nevertheless I have numbers 1 1 that are same in the array, Why ? And another problem is when I type 1 2 3 1 5 0 it only prints 1 2 3 and for example I when I scan 1 2 3 4 5 6 7 8 9 0 it prints all numbers except for 0.
There are multiple issues in your code. First, initialize i to be 0, and declare a new variable j alongside i,
int arr[200], i = 0, j;
The size of your array would simply be i, which you increment every time you insert an element in the array, and change this,
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
to this
for(j = 0; j < i; j++)
printf("%d ", arr[j]);
since the size of your array is stored in variable i. Also, the way you are calculating the size of your array is wrong which returns 1 everytime since the numerator and denominator are the same. Generally, it is sizeof(array)/sizeof(array[0]), and in this case, it too, would return 200, since the size of your declared array is 200, but since you increment your i every time at insertion, simply set your arr_size to be i.
int arr_size = i;
This line
int arr_size = sizeof(arr[i])/sizeof(arr[0]);
does not do what you are expecting. You are only dividing the size of two elements of the array, which are always the same size, thus always giving 1 as result. If you want to give the number of elements to the function, give it a variable that you used to count each number as you read them.
Also this:
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
Is only printing numbers that are not larger than their indices. Again, your program is missing a variable to count the number of input values.

Maximum value of every contiguous subarray

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)

Checking the frequency of numbers throughout an array

I have the following code which I'm trying to use to show how many times a certain number appears throughout the array. I want it to print out how many times it counted a specific number. (all numbers range from 0-20, with an index of 0 - 99).
void count_frequency(int *number) {
int i;
int j;
int len = sizeof number / sizeof(int);
printf("%i\n", len);
printf("reached here");
for(i = 0; i < 99; i++){ //index{
int c = 0;
for(j = 0; j < 99; j++){
if(number[j] == number[i]){
c++;
}else{
continue;
}
}
printf("%i\n", c);
//printf("%i\n", number[i]);
}
}
int main(){
int i;
int table[MAX];
int len = sizeof table / sizeof(int);
printf("%ireached before loop\n", len);
for(i = 0; i < len; i++){
table[i] = random_in_range(0, 20);
}
count_frequency(table);
//printf("%i", sizeof(table) / sizeof(int));
return 0;
}
int len = sizeof number / sizeof(int);
will not going to give you what you are expecting. number is a pointer variable not an array. Change your function to
void count_frequency(int *number, int len) {
int i;
int j;
int index[21] = {0};
printf("%i\n", len);
printf("reached here");
for(i = 0; i < len; i++){ //index{
index[number[i]%21]++;
}
for(i = 0; i < 21; i++)
printf("%d", index[i]);
}
and your function call should be
count_frequency(table, len);
Here you are. Honestly there was some magical thinking in your code. This works - it's not "the best" but an improvement on what you had. Let me know if this isn't clear. My definition of rand_in_range is not completely accurate - it will bias very slightly towards lower numbers.
include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define random_in_range(a,b) ( rand() % ((b) - (a) + 1) + (a) )
void count_frequency(int *table, int *output, int n1, int n2) {
// n1 = number of elements in table
// n2 = number of elements in output
int i;
// int len = sizeof number / sizeof(int); <<<< meaningless!
// printf("%i\n", len);
// printf("reached here");
for(i = 0; i < n1; i++) { // loop over the elements in the table
output[table[i] %n 2]++; // using % n2 so we don't go outside bounds of array.
}
}
int main(){
int i;
int table[MAX];
int counts[21]={0}; // <<<< need a place to put the result
int len = sizeof table / sizeof(int);
for(i = 0; i < len; i++){
table[i] = random_in_range(0, 20);
}
count_frequency(table, counts, MAX, 21);
for(i = 0; i < 21; i++) {
printf("number %d - frequency %d\n", i, counts[i]);
}
return 0;
}
Output:
number 0 - frequency 3
number 1 - frequency 5
number 2 - frequency 3
number 3 - frequency 6
number 4 - frequency 6
number 5 - frequency 7
number 6 - frequency 3
number 7 - frequency 5
number 8 - frequency 6
number 9 - frequency 9
number 10 - frequency 4
number 11 - frequency 2
number 12 - frequency 6
number 13 - frequency 8
number 14 - frequency 3
number 15 - frequency 4
number 16 - frequency 5
number 17 - frequency 6
number 18 - frequency 6
number 19 - frequency 3
number 20 - frequency 0
So you're saying you have an array of 100 numbers, each ranging from 0-20, and you want to count the occurrences of a SINGLE number within that array? Then this should do:
size_t count_occurrences(int interesting_num, int* array, size_t array_size) {
size_t i, occurrences = 0;
for (i=0; i < array_size; ++i) {
if (array[array_size] == interesting_num) {
++occurrences;
}
}
return occurrences;
}
Technically, you could replace those "size_t"s with unsigned chars, for the number ranges you're talking about, but given the dynamic calculation of len that you attempted, and the use of "MAX", I suspect you may want to increase those ranges at some point. So, I'm erring on the side of a safer, more general implementation.

Resources