How to find a certain number in an Array C Programming? - c

If I have an array and I need to display how many times the number '12' is created. I'm using a function to go about this. What resources should I look into to find how to exactly tease out this one number and display how many times it is in the array/list? Any help would be greatly appreciated.

You can do it by walking through the array, while keeping a tally.
The tally starts at 0, and every time you reach the number you want to track, add one to it. When you're done, the tally contains the number of times the number appeared.
Your function definition would probably look something like this:
int count_elements(int pElement, int pArray[], size_t pSize);

Simply create a counter variable, and examine each element in the array in a loop, incrementing the counter variable every time an element is equal to 12.

If you have a plain C-array, you have to iterate over all elements in a loop and count yourself with a variable.

int arr[20];
int twelves = 0;
int i;
/* fill here your array */
/* I assume your array is fully filled, otherwise change the sizeof to the real length */
for(i = 0; i < sizeof(arr)/sizeof(int);++i) {
if(arr[i] == 12) ++twelves;
}
After this, the variable twelves will contain the number of twelves in the array.

Related

developing a function that returns number of distinct values that exist in array

I want to create a function that can return the number distinct values present in a given array. If for eg the array is
array[5] = { 1 3 4 1 3}, the return value should be 3(3 unique numbers in array).
I've so far only got this:
int NewFucntion(int values[], int numValues){
for (i=0; i<numValues; i++){
Im a new coder/New to C language and im stuck on how to proceed. Any guidance would be much appreciated. Thanks
Add elements from the array to the std::set<T> and since the set is not allowing duplicate elements, you can then only get the number of elements from the set which gives you the number of distinct elements.
For example:
#include<set>
int NewFucntion(int values[], int numValues){
std::set<int> set;
for(int i=0; i<numValues; i++){
set.insert(values[i]);
}
return set.size();
}
int distinct(int arr[], int arr_size){
int count = arr_size;
int current;
int i, j;
for (i = 0; i < arr_size; i++){
current = arr[i];
for (j = i+1; j < arr_size; j++) // checks values after [i]th element.
if (current == arr[j])
--count; // decrease count by 1;
}
if (count >= 0)
return count;
else return 0;
}
Here's the explanation.
The array with its size is passed as an argument.
current stores the element to compare others with.
count is the number that we need finally.
count is assigned the value of size of the array (i.e we assume that all elements are unique).
(It can also be the other way round)
A for loop starts, and the first (0th) element is compared with the elements after it.
If the element reoccurs, i.e. if (current==arr[j]), then the value of count is decremented by 1 (since we expected all elements to be unique, and because it is not unique, the number of unique values is now one less than what it was initially. Hence --count).
The loops go on, and the value is decremented to whatever the number of unique elements is.
In case our array is {1,1,1,1}, then the code will print 0 instead of a negative value.
Hope that helps.
Happy coding. :)
I like wdc's answer, but I am going to give an alternative using only arrays and ints as you seam to be coding in c and wdc's answer is a c++ answer:
To do this thing, what you need to do is to go through your array as you did, and store the new numbers you go over in a different array lets call it repArray where there wont be any repetition; So every time you add something to this array you should check if the number isn't already there.
You need to create it and give it a size so why not numValues as it cannot get any longer than that. And an integers specifying how many of it's indexes are valid, in other words how many you have written to let's say validIndexes. So every time you add a NEW element to repArray you need to increment validIndexes.
In the end validIndexes will be your result.

Delete duplicate in an array and insert first occurrence in a new array in C

I have to do a function which, taken as parameters a pointer (int *vect) and the dimension (dim) of the array allocated, returns a new array which contains all the elements of the old array not repeated and all the first occurrence of repeated elements, this is the code where i put the elements not repeated of the first array, but i don't know how to proceed to put the first occurrence of repeated elements (e.g. INPUT : vect={1;2;3;3;4;5;5} OUTPUT : {1;2;3;4;5})
int* deleteDup(int *vect,int dim){
int* vect2,int dim2;
vect2=malloc(sizeof(int)*dim2);
int i,j,temp;
int count=0;
for(i=0;i<dim-1;i++){
temp=vect[i];
for(j=i+1;j<dim;j++){
if(temp==vect[j]){
count++;
}
}
if(count==0){
dim2++;
vect2=realloc(vect2,dim2*sizeof(int));
vect2[dim2]=temp;
}
*dim_nodup=dim2;
return vect2;
}
This looks like homework to me.
You need to first count the number of unique elements, then allocate an array of that size, and then move one instance of each unique element to the new array.
This can be optimised various ways.
I prefer not to give you code or even pseudo code, as you should figure this out yourself when solving the problem.
i don't know how to proceed to put the first occurrence of repeated elements
To do this you must move elements one by one into the array you are returning, and for each item check if it is already in the array.
Good luck! :)

Counting the times numbers occur in an array using (count_numbers(int [], int, int)) C

So what I have is an array that's size is decided by me and then the elements in the array are randomly generated. It's supposed to take an integer array,its size, and an integer number
and find how many times the number is present in the array and return that count at the end.I keep trying stuff and nothing seems to be getting me anywhere close to an answer. I was just trying to see if someone could point me in the right direction on where to start
count_numbers(int array[], int size, int z)
Hhave you tried running a loop through the array and trying a match expression to the array value in another loop. This seems like a logic question rather than actual code related. Maybe a search around the internet looking at how to count in arrays could help you.
This should point you in the right direction...
for (int i = 0; i < arraySize; i++) {
if (array[i] == z /*z being your search value**/) {
you may have to alter this a little
//dosomething
// e.g. increment a count here
}
else
do-nothing essentially.
There is a method for checking array size - so don't worry about defining it's size. have a look at the java method for this and use it.
Hope this helps

Using arrays in C

I have a troubling homework assignment and would like pointers in the correct direction.
The task is to develop a C program that accomplishes the following:
In the main(), create an a 2D array named qqqqq that can hold 48 integers (6 rows, 8 columns)
Populate qqqqq with randomly generated integer values between 1 and 15.
Calculate the total for each row.
Calculate the total for each column.
Display the contents of the 2D array in tabular format with the row totals to the right of the rows and the column totals at the bottom of the columns.
Where to start after main?
Here is what I have so far:
int main (void)
{
int qqqqq [6] [8];
int r;
int c;
srandom ((unsiged) time (NULL));
for (r=0; r <=6; r++)
{
for(c=0; c <=8; c++)
{
qqqqq[r][c] = random ( )
What do I do next?
I appreciate any help or guidance.
Thanks
-James
Algorithmic Thinking
Here is how I would tackle this problem:
Write the algorithm in my own words.
Find out how to generate random numbers in the C language.
Learn how to print information on the screen.
Algorithm
The algorithm is the set of steps you need to solve the problem. The task at hand already describes the problem, but it is often good practice to re-write it in your own words. (As a practical point, you can then take your words to your client -- in this case, your teacher -- and confirm that your understanding of the problem is correct.)
Create a 2D array
Populate the array with random numbers.
Calculate the sum of each row of numbers (need a row sum counter).
Calculate the sum of each column of numbers (need a column sum counter).
Print the 2D array to the screen.
Print the sum of each row at the end of each row.
Print the sum of each column at the end of each column.
Assumption: Neither sum of sums are printed. (For example, the sum of the column sum.)
Generate Random Numbers
Google is helpful here. Try a Google search for:
generate random integers C
You will find lots of help, especially tips about the rand() function. Modify the Google search:
generate random integers C rand()
This search finds a great resource: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Print Information
Again, a Google search can help here:
print information on the screen in C
This yields: http://www.daniweb.com/software-development/c/threads/9688
The printf function seems handy. Find out more about it:
printf C
This yields a familiar site: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Development
If you really want to "wow" your professor:
Identify the parts of your program that are most likely to change and make them constants.
Separate your program into logical areas (called functions).
Use meaningful variable names. Yes r and c likely represent rows and columns, but for the amount of time it takes to spell out row and column, it will save anyone reading your code from having to either make a guess or read the code to discover its true use.
Tell your professor that qqqqq could use a better name. Suggest one, even.
For example:
#include <stdio.h>
/* Subject to change; only change it in one spot. */
#define MAX_ROWS 6
#define MAX_COLS 8
#define MIN_RANDOM_NUMBER 1
#define MAX_RANDOM_NUMBER 15
/** Returns a number between MIN_RANDOM_NUMBER and MAX_RANDOM_NUMBER. */
int randomNumber() {
return 0; /* FIX ME to use rand() and the modulus operator. */
}
int main( int argc, char *argv[] ) {
int qqqqq[MAX_ROWS][MAX_COLS];
/* FIX ME: Move these variables into the display function. */
int sumRows = 0;
int sumCols = 0;
/* Use different random numbers each time the program runs. */
seedRandomNumber();
/* Initialize the array with random numbers. */
for( int row = 0; row < MAX_ROWS; row++ ) {
for( int col = 0; col < MAX_COLS; col++ ) {
qqqqq[row][col] = randomNumber();
}
}
/* Display the array to the screen along with the sum totals. */
display( qqqqq );
}
Note that you have a choice to make.
You could pass the sumRows variable into the display function, or you could code the display function to call calculateSumRows itself. My preference is to always simplify the function prototypes. That is, reduce the number of parameters. It makes things easier to change in the future.
So write display as something like:
void display( int randomValues[MAX_ROWS][MAX_COLS] ) {
int sumCols = 0;
for( int row = 0; row < MAX_ROWS; row++ ) {
/* FIX ME: Write the calculateSumCols function. */
sumCols = calculateSumCols( randomValues, row );
for( int col = 0; col < MAX_COLS; col++ ) {
/* FIX ME: Use printf here to display the value at this row/column. */
}
}
/* FIX ME: Use printf here to display sumRows. */
for( int col = 0; col < MAX_COLS; col++ ) {
/* FIX ME: Use printf here to display the value of the rows. */
printf( "%d ", calculateSumRows( randomValues, col ) );
}
}
That should get you started.
Note that there are a number of simplifications and optimizations you could make here. Forget them. Get the code so that it actually works first. Once the code works, save it. Make a back up copy, even.
Then start to change it. See if you can remove variables. Perhaps you can even remove some of the for loops. If you make a mistake, you can always reference your back up copy. Eventually your "back up" copy will become a "source code repository".
That's a pretty good start! Note, though, that the valid indices for an arrayof dimension X are 0...(X-1). Your loops should look like
for (r=0; r <6; r++)
(Note that "<6" rather than "<=6".
Now you need another array to hold the row totals, and an array to hold the column totals, and then some more loops to calculate those and store them in the arrays.
Some key things:
What does random() return?
What is the total of a row/column?
This is just adding up all the
numbers in the row/column. Try
writing a function to add up all the
values in one given row or column.
Think of how to print out a row
of a matrix. Then do this for every
row in the matrix.
There are 6 rows and 8 columns, and you need a total for each of those. Start by making some more arrays as places to store those totals.

Escaping loop whilst adding to dynamic array - C

Currently my program allows the user to enter 5 integers which are used to create an average number. This is set to five as after the fifth number is entered the loop is broken.
I am trying to implement a method which will let the user continue to add as many numbers as they like to an array from which i can then use to create an average without a limit on the amount of numbers that can be entered.
I have come across a few problems, firstly i cannot create an array which is dyamic as i have no idea how many numbers the user may wish to enter which means i can't give it a definitive size.
Secondly the way my program currently creates the average is by looping through the elements in the array and adding the consecutively to an integer, from which the the average is made. I cannot specify the limit for the loop to continue running if i cannot determine the array.
Hopefully my example explains this better.
#include <stdio.h>
#include <string.h>
void main()
{
int i = 0;
int arrayNum[5];
int temp = 1;
int anotherTemp = 0;
int answer = 0;
printf("Enter as many numbers as you like, when finished enter a negative number\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &temp);
arrayNum[i] = temp;
anotherTemp = anotherTemp + arrayNum[i];
}
answer = anotherTemp / 5;
printf("Average of %d,%d,%d,%d,%d = %d",arrayNum[0],arrayNum[1],arrayNum[2],arrayNum[3],arrayNum[4],answer);
}
Although this may not be the best way to implement it, it does work when the amount of numbers are specified beforehand.
What would be the best way to get around this and allow the user to enter as many number as necessary?
Edit: Although i needed to use an array I have decided that it is not necessary as the solution is much simpler without being restricted to it.
In terms of code simplicity, you might want to check out the realloc() function; you can allocate an initial array of some size, and if the user enters too many numbers call realloc() to get yourself a bigger array and continue from there.
You don't, however, actually need to keep the numbers as you go along at all, at least if you only care about the average:
int input;
int sum = 0;
int count = 0;
int average;
while (1) {
scanf("%d", &input);
if (input < 0) {
break;
}
sum += input;
count++;
}
average = sum / count;
If you're trying to compute an average, then you don't need to save the numbers. Save yourself the work of worrying about the array. Simply accumulate (add) each number to a single total, count each number, then divide when you're done. Two variables are all that you need.
With this method, you aren't in any risk of overflowing your array, so you can use a while loop... while (temp != -1)
Basically you start with a dynamically allocated array with a fixed size, and then allocate a new array that is bigger (say, twice as big as initial size) and copy the stuff from the old array to the new one whenever you run out of space.
For the second part of the problem, keep a counter of the number of items the user entered and use it when averaging.
Something like this.
Use a dynamic array data structure, like Vector in Java (java.util.Vector).
You can implement such a dynamic array yourself easily:
allocate array of size N
as soon as you need more elements than N, allocate a new bigger array (e.g. with size N+10), copy the content of the old array into the new array and set your working reference to the new array and your array size variable N to the new size (e.g. N+10). Free the old array.

Resources