Alteration of variable value in C - c

[UPDATE]: The answer by Keine Lust, to explicitly declare the size of array solves the problem.
I am trying to write my own decimal to binary converter in C (posted below), which constantly is giving wrong outputs due to alteration of value of variable named a. Why is the alteration happening? And the compiler I'm using is gcc.
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void) {
int j = 0; // This variable is used to counter the iterations of while-loop
int a; // This variable holds user-input
char b[] = {}; // This is character array to hold the value of bits after operation
printf("Enter a number to convert into binary\n>>>");
scanf("%d", &a);
while(a!=0){ // Loop until the value of a is 0
printf("a before modulus: %d \n", a); // printing a for debugging
int bit = a % 2; // represents binary digit
printf("a after modulus:%d \n", a); // print a for debugging
switch(bit){ // switch-case to identify the bit
case 1:
b[j] = '1';
break;
case 0:
b[j] = '0';
break;
}
printf("a after switch-case:%d \n", a); // the value of a is altered after switch-case, check output.
a = (int) floor((float)(a/2));
j += 1;
}
printf("\n");
return 0;
}
OUTPUT: (input: 2)
a before modulus:2
a after modulus:2
a after switch-case:48
a before modulus: 24
a after modulus:24
a after switch-case:12312
a before modulus: 6156
a after modulus:6156
..... continues
COMPLETED CODE THAT WORKS: [UPDATE]
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void) {
const int MAX_SIZE = sizeof(char) * 10000; // Will hold 10000 characters
int j = 0; // This variable is used to counter the iterations of while-loop
int a,temp; // This variable holds user-input
char b[MAX_SIZE]; // This is character array to hold the value of bits after operation will hol
printf("Enter a number to convert into binary\n>>>");
scanf("%d", &a);
temp = a;
int bits = log(a)/log(2);
bits += 1;
while(a!=0){ // Loop until the value of a is 0
int bit = a % 2; // represents binary digit
switch(bit){ // switch-case to identify the bit
case 1:
b[j] = '1';
break;
case 0:
b[j] = '0';
break;
}
a = a/2;
j += 1;
}
printf("The %d in binary is: ",temp);
for (int c=(bits-1);c>=0;c--) {
printf("%c", b[c]);
}
printf("\n");
return 0;
}

Related

Digit Frequency calculating code in C not working

So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
// takes string input
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//turns the string to int
int x = atoi(s);
int temp = x, len = 0;
//calculates string length
while (x != 0) {
x = x / 10;
len++;
}
x = temp;
//parses through the string and matches digits with each number
for (int j = 0; j < 10; j++){
int count = 0;
for(int i = 0; i < len; i++){
if(x % 10 == j){
count++;
}
x = x / 10;
}
x = temp;
printf("%d ", count);
}
return 0;
}
To write a correct and reasonable digit-counting program:
Do not allocate any buffer for this.
Create an array to count the number of times each digit occurs. The array should have ten elements, one for each digit.
Initialize the array to zero in each element.
In a loop, read one character at a time.
Leave the loop when the read routine (such as getchar) indicates end-of-file or a problem, or, if desired, returns a new-line or other character you wish to use as an end-of-input indication.
Inside the loop, check whether the character read is a digit. If the character read is a digit, increment the corresponding element of the array.
After the loop, execute a new loop to iterate through the digits.
Inside that loop, for each digit, print the count from the array element for that digit.
Your approach is way to complicated for a very easy task. This will do:
void numberOfDigits(const char *s, int hist[10]) {
while(*s) {
if(isdigit(*s))
hist[*s - '0']++;
s++;
}
}
It can be used like this:
int main(void) {
char buf[1024];
int hist[10];
fgets(buf, sizeof buf, stdin);
numberOfDigits(s, hist);
for(int i=0; i<10; i++)
printf("Digit %d occurs %d times\n", i, hist[i]);
}
This can also be quite easily achieved without a buffer if desired:
int ch;
int hist[10];
while((ch = getchar()) != EOF) {
if(isdigit(ch))
hist[ch - '0']++;
}
#include <stdio.h>
int main(void) {
int input = 1223330;
int freq[10] = {0};
input = abs(input);
while(input)
{
freq[input%10]++;
input /= 10;
}
for(int i=0; i<10; ++i)
{
printf("%d: %.*s\n", i, freq[i], "*************************************************");
}
return 0;
}
Output:
Success #stdin #stdout 0s 5668KB
0: *
1: *
2: **
3: ***
4:
5:
6:
7:
8:
9:
This app is currently limited by the size of an int (approximately 9 or 10 digits).
You can update it to use a long long easily, which will get you to about 19 digits.

Unable to extract full number from string in C program

Program to calculate the average of n numbers given by the user.
Okay so I have this program whose purpose is what you have read above. Its output is not quite right. I figured out what the problem is but couldn't find the solution as I am not a leet at programming (newbie actually). Here is the code:
#include <stdio.h>
int main(void) {
char user_data[100];
long int sum = 0;
double average;
unsigned int numbers_count = 0;
for (int i = 0; i <= 99; ++i)
user_data[i] = 0;
unsigned int numbers[100];
for (int i = 0; i <= 99; ++i)
numbers[i] = 0;
printf("Please enter the numbers:");
fgets(user_data, sizeof(user_data), stdin);
int i = 0;
while (user_data[i] != 0) {
sscanf(user_data, "%u", &numbers[i]);
++i;
}
i = 0;
while (numbers[i] != 0) {
sum += numbers[i];
++i;
}
i = 0;
while (numbers[i] != 0) {
++numbers_count;
++i;
}
average = (float)sum / (float)numbers_count;
printf("\n\nAverage of the entered numbers is: %f",average);
return 0;
}
Now here comes the problem.
When I enter an integer say 23, it gets stored into the user_data in two separate bytes. I added a loop to print the values of user_data[i] to figure out what was wrong.
i = 0;
while (i <= 99) {
printf("%c\n",user_data[i]);
++i;
}`
and the result was this
user_data insight
This was the first problem, here comes the second one.
I added another loop same like the above one to print the numbers stored in numbers[100] and figure out what was wrong and here is the output. Here's a sample
numbers stored in numbers[]
Now my main question is
How to extract the full number from user_data?
I believe it could be helpful to layout user_data after the fgets() of "23" (assuming Linux or Mac new line):
+-----+-----+----+----+
| '2' | '3' | \n | \0 | .....
+-----+-----+----+----+
0 1 2 3
Note that user_data[0] does not contain 2 (the number 2)! It contains '2' (the character '2') whose code is (again, assuming Linux) 0x32 (in hex or 50 in decimal).
This is why your attempt to print the values of user_data[] have not been fruitful: you were trying to print the representation of the number, not the number itself.
To convert that string to the integer it represents, you can do something like:
num = atoi(user_data)
The function atoi() does the work for you. A more flexible function is strtol() which does the same but for long int (and also can handle string that represents numbers in a base that is not 10).
I hope this answers to your question: How to extract the full number from user_data?
There are some other points where you should clean up and simplify your code, but you can open another question in case you need help.
Try this:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int i;
char user_data[100];
long int sum = 0;
double average;
unsigned int numbers_count = 0;
for( i=0; i<= 99; ++i)
user_data[i] = 0;
unsigned int numbers[100];
for( i=0; i<= 99; ++i)
numbers[i] = 0;
printf("Please enter the numbers:");
fgets(user_data,sizeof(user_data),stdin);
//int p=0;//use with strtol(see further code)
i = 0;
int j;//this will store each number in numbers array.. so this is also the count of numbers stored - 1
for(j=0;;){
for(i=0;i<strlen(user_data);i++)
{
if(user_data[i]=='\n'){
break;
}
if(user_data[i]==' '){
j++;
i++;
//p=i;//to be used with strtol
}
numbers[j]=(numbers[j]*10)+((user_data[i]-48));//alternatively use => numbers[j]=strtol(user_data+p,NULL,10);
}
break;
}
i = 0;
while( i<=j)
{
sum += numbers[i];
++i;
}
average = (float)sum/(j+1);
printf("\n\nAverage of the entered numbers is: %f",average);
return 0;
}
Sample input
10 11 12
Sample output
11.00000000
I have shown two approaches to solve this:
One is straight-forward, subtract 48 from each char and add it to numbers array(ASCII manipulation) .
Other is to use strtol. Now strtol converts the number pointed by the char pointer(char array in this case) until the next char is not a number. So use pointer arithmetic to point to further numbers(like here I have added p(yeah I know p is not a good variable name, so does i and j!)).
There are more ways to solve like using atoi library functions.
regarding the posted code:
what happens if one of the numbers is zero?
What happens if the sum of the numbers exceeds the capacity of 'sum'
#include <stdio.h> // sscanf(), fgets(), printf()
#include <stdlib.h> // strtol()
#include <string.h> // strtok()
// eliminate the 'magic' number by giving it a meaningful name
#define MAX_INPUTS 100
int main(void)
{
// the array can be initialized upon declaration
// which eliminates the 'for()' loop to initialize it
// char user_data[100];
// and
// initialization not actually needed as
// the call to 'fgets()' will overlay the array
// and 'fgets()' always appends a NUL byte '\0'
char user_data[ MAX_INPUTS ];
long int sum = 0;
double average;
// following variable not needed
// unsigned int numbers_count = 0;
// following code block not needed when
// 'user_data[]' initialized at declaration
// for (int i = 0; i <= 99; ++i)
// user_data[i] = 0;
// not needed, see other comments
//unsigned int numbers[100];
// not needed, as 'numbers' is eliminated
// for (int i = 0; i <= 99; ++i)
// numbers[i] = 0;
printf("Please enter the numbers:");
// should be checking the returned value
// to assure it is not NULL
// And
// this call to 'fgets()' is expecting
// all the numbers to be on a single input line
// so that could be a problem
fgets(user_data, sizeof(user_data), stdin);
// the following two code blocks will not extract the numbers
// for a number of reasons including that 'sscanf()'
// does not advance through the 'user_data[]' array
// int i = 0;
// while (user_data[i] != 0) {
// sscanf(user_data, "%u", &numbers[i]);
// ++i;
// }
// i = 0;
// while (numbers[i] != 0) {
// sum += numbers[i];
// ++i;
// }
// suggest the following,
// which also eliminates the need for 'numbers[]'
// note: the literal " \n" has both a space and a newline
// because the user is expected to enter numbers,
// separated by a space and
// 'fgets()' also inputs the newline
int i = 0;
char *token = strtok( user_data, " \n");
while( token )
{
// not everyone likes 'atoi()'
// mostly because there is no indication of any error event
// suggest using: 'strtol()'
//sum += atoi( token );
sum += strtol( token, NULL, 10 ) // could add error checking
i++;
token = strtok( NULL, " \n" );
}
// the value assigned to 'numbers_count'
// is already available in 'i'
// suggest eliminate the following code block
// and
// eliminate the 'numbers_count' variable
// i = 0;
// while (numbers[i] != 0) {
// ++numbers_count;
// ++i;
// }
// 'average' is declared as a 'double',
// so the casting should be to 'double'
// and
// if incorporating the prior comment about 'numbers_count'
// average = (float)sum / (float)numbers_count;
average = (double)sum / (double)i'
// to have the text immediately displayed on the terminal
// place a '\n' at the end of the format string.
// without adding the '\n' the text only displays
// as the program exits
// printf("\n\nAverage of the entered numbers is: %f",average);
printf("\n\nAverage of the entered numbers is: %f\n",average);
return 0;
} // end function: main

My program doesn't manipulate a string's values correctly

I need to code a program that gets input values for a string, then it ignores the characters that are not digits and it uses the digits from the string to create an integer and display it. here are some strings turned into integers as stated in the exercise.
I wanted to go through the string as through a vector, then test if the each position is a digit using isdigit(s[i]), then put these values in another vector which creates a number using the digits. At the end it's supposed to output the number. I can't for the life of it figure what's wrong, please help.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char *s;
scanf("%s", s);
printf("%s\n", s);
int i, n=0, v[100], nr=0;
for(i=0; i<strlen(s); i++)
{
if (isdigit(s[i]) == 1)
{
v[i] = s[i];
n++;
}
}
for(i=0;i<n;i++)
{
printf("%c\n", v[i]);
}
for(i=0; i<n; i++)
{
nr = nr * 10;
nr = nr + v[i];
}
printf("%d", nr);
return 0;
}
The pointer s is unintialized which is your major problem. But there are other problems too.
isdigit() is documented to return a non-zero return code which is not necessarily 1.
The argument to isdigit() needs to be cast to unsigned char to avoid potential undefined behaviour.
Your array v is also using the same index variable i - which is not right. Use a different variable to index v when you store the digits.
You need to subtract '0' to get the each digits integer equivalent.
scanf()'s format %s can't handle inputs with space (among other problems). So, use fgets().
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char s[256];
fgets(s, sizeof s, stdin);
s[strcspn(s, "\n")] = 0; /* remove trailing newline if present */
printf("%s\n", s);
int i, n = 0, v[100], nr = 0;
size_t j = 0;
for(i = 0; i < s[i]; i++)
{
if (isdigit((unsigned char)s[i]))
{
v[j++] = s[i];
n++;
}
}
for(i = 0;i < j; i++)
{
printf("%c\n", v[i]);
}
if (j) { /* No digit was seen */
int multiply = 1;
for(i= j-1 ; i >= 0; i--) {
nr = nr + (v[i] - '0') * multiply;
multiply *= 10;
}
}
printf("%d", nr);
return 0;
}
In addition be aware of integer overflow of nr (and/or multiply) can't hold if your input contains too many digits.
Another potential source of issue is that if you input over 100 digits then it'll overflow the array v, leading to undefined behaviour.
Thanks a lot for your help, i followed someone's advice and replaced
v[i] = s[i] -> v[n] = s[i] and changed char *s with char s[100]
now it works perfectly, i got rid of the variable nr and just output the numbers without separating them through \n . Thanks for the debugger comment too, I didn't know I can use that effectively.
Firstly, you did not allocate any memory, I changed that to a fixed array.
Your use of scanf will stop at the first space (as in the first example input).
Next, you don't use the right array index when writing digits int v[]. However I have removed all that and simply used any digit that occurs.
You did not read the man page for isdigit. It does not return 1 for a digit. It returns a nonzero value so I removed the explicit test and left it as implicit for non-0 result.
I changed the string length and loop types to size_t, moving the multiple strlen calls ouside of the loop.
You have also not seen that digits' character values are not integer values, so I have subtracted '0' to make them so.
Lastly I changed the target type to unsigned since you will ignore any minus sign.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char s[100]; // allocate memory
unsigned nr = 0; // you never check a `-` sign
size_t i, len; // correct types
if(fgets(s, sizeof s, stdin) != NULL) { // scanf stops at `space` in you example
len = strlen(s); // outside of the loop
for(i=0; i<len; i++) {
if(isdigit(s[i])) { // do not test specifically == 1
nr = nr * 10;
nr = nr + s[i] - '0'; // character adjustment
}
}
printf("%u\n", nr); // unsigned
}
return 0;
}
Program session:
a2c3 8*5+=
2385
Just use this
#include <stdio.h>
#include <ctype.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '\n':
putchar(c); break;
}
}
return 0;
} /* main */
This is a sample execution:
$ pru_$$
aspj pjsd psajf pasdjfpaojfdapsjd 2 4 1
241
1089u 0u 309u1309u98u 093u82 40981u2 982u4 09832u4901u 409u 019u019u 0u3 0ue
10890309130998093824098129824098324901409019019030
Very elegant! :)

Decimal to Binary conversion using recursion with while loop

my binary conversion doesn't work after it recurs a second time, it seems to work only during the first time through. The purpose of the is have a user input a number to convert to Hex, Octal, and brinary from a integer and keep on asking and converting until the user inputs 0. Please help!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
long toBinary(int);
int main(void) {
int number = 0;
long bnum;
int zero = 0;
while(number != zero) {
puts("\nPlease enter a number you would like to convert to");
puts("\nHexadecimal, octal, and binary: ");
scanf("%d", &number);
if(number != zero) {
printf("\nThe Hexadecimal format is: %x", number);
printf("\nThe Octal format is: %o", number);
bnum = toBinary(number);
printf("\nThe binary format is: %ld\n", bnum);
}
else {
puts("\nI'm sorry you have to enter a number greater than 0.\n");
puts("\nOr have enter an invalid entry.");
}
}
return 0;
}
long toBinary(int number) {
static long bnum, remainder, factor = 1;
int long two = 2;
int ten = 10;
if(number != 0) {
remainder = number % two;
bnum = bnum + remainder * factor;
factor = factor * ten;
toBinary(number / 2);
}
return bnum;
}
You just need a function to convert an integer to its binary representation.
Assuming the int is 32 bits then this should work:
#include <stdio.h>
int main()
{
char str[33];
str[32] = 0;
int x = 13, loop;
for (loop = 31; loop >= 0; --loop) {
str[loop] = (x & 1) ? '1' : '0';
x = x >> 1;
}
printf("As %s\n", str);
return 0;
}
You can make this into a function, read x etc...
EDIT
For octal/hex - printf will do this for you
EDIT
Here goes recursively
#include <stdio.h>
void PrintBinary(int n, int x) {
if (n > 0) {
PrintBinary(n - 1, x >> 1);
}
printf("%c",(x & 1) ? '1' : '0');
}
int main()
{
PrintBinary(32,12);
return 0;
}
First of all I am surprised it even works once. Firstly, your while condition is while number does not equal zero. But right off the bat, number equals 0 and zero equals 0. Therefore the while should never run. If you want to keep this condition for the main loop, change it to a do-while loop: do { //code } while (number != zero);. This will run the code at least once, then check if the inputted number doesn't equal zero. That brings me to the next issue; your scanf for number is scanning for a double and placing it in a regular integer memory spot. Quick fix: scanf("%i",&number);. Also I am finding some functions called puts.. I find it best to keep with one printing function, printf. Now, I am finding afew errors in your toBinary function, but if it works than I guess it works. These are all the errors i could find, I hope this helped. But for future reference there is no need to declare a variable for a const number like 2 or 10 at this level.
#include <stdint.h>
char* toBinary(int32_t number, int index){
static char bin[32+1] = {0}, *ret;
if(index == 32){
memset(bin, '0', 32);
return toBinary(number, 31);
} else if(number & (1<<index))
bin[31-index] = '1';
if(index)
(void)toBinary(number, index-1);
else
for(ret = bin; *ret == '0';++ret);
return ret;
}
...
int number = -1;
...
printf("\nThe binary format is: %s\n", toBinary(number, 32));

Displaying hex values inside an array to stdout, and comparing input to those hex values

This is my current code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int target;
char array[] = {'AC', 'EE', '88', '0D', '87'};
printf("Enter the target byte as a hex value: \n");
scanf("%x", &target);
int i = 0;
for (i; i < 5; i++)
{
printf("Value of array[%d] is %x \n", i, array[i]);
}
int i = 0;
for (i; i < 5; i++)
{
if (memcmp(target, array, sizeof(target) == 0))
{
printf("Found a match!");
}
}
}
(1) I want to be able to display to stdout the exact values inside of my char array[]. Things I've tried that do not work: displaying the array as %c, %x, %d.
(2) After I get the input from the user, I want to be able to compare that input to the characters inside of the array - figured memcmp would be the way to go, but how do I traverse through the entire array? I tried doing if (memcmp(target, array[i], sizeof(target) == 0)) but I'd get a runtime error because of the array[i] part, but if I don't add that part, how will it go through the entire array comparing the values stored in each array memory location to the value stored in the target variable? I basically want to compare bytes inside each array location to the bytes the input by the user.
You should store the hex values in your array as 0xAC etc, not 'AC' (which is a multi character constant and not at all what you want).
Store your hex values as unsigned char because on platforms where char defaults to signed you're going to get some values (negative ones) being cast to int and sign-bit padded accordingly, which is then displayed.
Your memcmp is call wrong and using it is unnecessary anyway.
Your example code won't compile because you have two declarations of int i in the same scope. If you aren't using C89 why aren't you writing your for loops as for(int i = 0;...) anyway?
Don't forget your return value for main.
Example:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int target;
const unsigned char array[] = { 0xAC, 0xEE, 0x88, 0x0D, 0x87 };
const int len = sizeof array;
printf("Enter the target byte as a hex value: \n");
scanf("%x", &target);
for (int i = 0; i < 5; ++i)
{
printf("Value of array[%d] is 0x%x\n", i, array[i]);
}
for (int i = 0; i < len; ++i)
{
if (target == array[i])
{
printf("Found a match!\n");
}
}
return EXIT_SUCCESS;
}
This question was part of a bigger program, but it was just this small portion that I couldn't figure out to begin with. In the end, I got everything worked out. Below is the final code of the actual program, and at the bottom are the function definitions I wrote with the help of a couple of users. Again, thank you!
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
// defined constants
#define MAX_WIDTH 20
#define NUMELEMS 50
// typedefs and function prototypes
typedef unsigned char Byte;
void DispBytes(void *voidArray, int totalBytes);
int CountMatchBytes(void *voidArray, int totalBytes, int targetHex);
// ==== main ==================================================================
//
// ============================================================================
int main(void)
{
auto double myDoubles[NUMELEMS];
auto int myInts[NUMELEMS];
auto char myChars[NUMELEMS];
auto int target;
auto int numMatches;
// process the char array
puts("Here's the array of chars as bytes: ");
DispBytes(myChars, sizeof(myChars));
printf("\nEnter the target byte as a hex value: ");
scanf("%x", &target);
numMatches = CountMatchBytes(myChars, sizeof(myChars), target);
printf("There %s %d matching byte%s.\n\n", (1 == numMatches ? "is" : "are")
, numMatches
, (1 == numMatches ? "" : "s"));
// process the int array
puts("\nHere's the array of ints as bytes: ");
DispBytes(myInts, sizeof(myInts));
printf("Enter the target byte as a hex value: ");
scanf("%x", &target);
numMatches = CountMatchBytes(myInts, sizeof(myInts), target);
printf("There %s %d matching byte%s.\n\n", (1 == numMatches ? "is" : "are")
, numMatches
, (1 == numMatches ? "" : "s"));
// process the double array
puts("\nHere's the array of doubles as bytes: ");
DispBytes(myDoubles, sizeof(myDoubles));
printf("Enter the target byte as a hex value: ");
scanf("%x", &target);
numMatches = CountMatchBytes(myDoubles, sizeof(myDoubles), target);
printf("There %s %d matching byte%s.\n\n", (1 == numMatches ? "is" : "are")
, numMatches
, (1 == numMatches ? "" : "s"));
return 0;
} // end of "main"
void DispBytes(void *voidArray, int totalBytes)
{
// Sets startingPtr to the base address of the passed array
auto unsigned char *startingPtr = voidArray;
// Sets endingPtr to one address past the array
auto unsigned char *endPtr = voidArray + totalBytes;
auto int counter = 0;
// Loop while the address of startingPtr is less than endPtr
while (startingPtr < endPtr)
{
// Display the values inside the array
printf("%x ", *startingPtr);
counter++;
if (counter == MAX_WIDTH)
{
printf("\n");
counter = 0;
}
// Increment the address of startingPtr so it cycles through
// every value inside the array
startingPtr++;
}
}
int CountMatchBytes(void *voidArray, int totalBytes, int targetHex)
{
// Sets startingPtr to the base address of the passed array
auto unsigned char *startingPtr = voidArray;
// Sets endingPtr to one address past the array
auto unsigned char *endingPtr = voidArray + totalBytes;
auto int counter = 0;
// Loop while the address of startingPtr is less than endPtr
while (startingPtr < endingPtr)
{
// If the input value is the same as the value inside
// of that particular address inside the array,
// increment counter
if (targetHex == *startingPtr)
{
counter++;
}
// Increment the address of startingPtr so it cycles through
// every value inside the array
startingPtr++;
}
// Return the number of times the input value was found
// within the array
return counter;
}

Resources