I am having some issues with my assignment, everything looks right to me, but obviously its not. I need to write a program where a person guesses a 5 - 9 digit number depending on selection, and when each number is guessed correctly it needs to show up in the order its guessed and keep asking until all numbers are correct. The number is seeded randomly with s(rand).
Here is the assignment instructions
Problem: Codebreaking!
The basic idea is this:
1) You begin by selecting a length and difficulty for the code. A set of numbers will be generated.
2) You will guess the magnitude and placement of each of the numbers.
3) Anything exactly correct will be revealed.
4) Anything with the correct value will be noted, but not revealed.
5) You can guess as many times as you want.
When the correct code is entered, the program will end.
Output Sample
Welcome to Codebreaker Training!
You will be presented with a set of hidden values. Your job is to guess these values and their correct order. After each guess you will be given feedback.
Values that are correct in magnitude and in the correct location will be revealed. These are perfect matches.
Then you will be told how many other numbers are correct in magnitude only. These are imperfect matches. No additional information will be revealed.
Choose a length for the code (5-10 numbers).
6
Choose a difficulty (1, 2, or 3).
1
There are 6 numbers ranging from 1 to 3.
- - - - - -
Enter your guess: 111111
You have 1 perfect matches and 0 imperfect matches.
- - - - 1 -
Enter your guess: 232112
You have 1 perfect matches and 2 imperfect matches.
- - - - 1 -
Enter your guess: 222113
You have 3 perfect matches and 0 imperfect matches.
- 2 - - 13
Enter your guess: 323313
You have 6 perfect matches and 0 imperfect matches.
Congratulations! You guessed all the values!
Here is the code I have
//pre-processor directives
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//Function Prototypes - do not change these
void greeting();
void setParameters(int * length, int * difficulty);
int * createHideList(int length, int difficulty);
int * createShowList(int length);
void display(int showlist[], int length);
void getGuess(int guesss[], int length);
void processGuess(int hidelist[], int showlist[], int length, int guess[]);
int solved(int hidelist[], int guess[], int length);
int PerfectMatches(int hidelist[], int guess[], int length);
int ImperfectMatches(int hidelist[], int guess[], int length);
void copyArray(int dest[], int source[], int length);
//Main function - This is the final version of main. Any changes you make while
//creating the functions should be removed prior to submission.
int main() {
//Length determines the number of hidden values that must be guessed
//Difficulty determines the range of the hidden values
int length, difficulty;
//Answer, revealed, and guess are all integer arrays
//Since length is undefined at this point, no sizes have been assigned.
//This will be done in the create...List functions.
//Answer is the correct answer of the hidden values
//Revealed is the list that is shown to the user
//Guess is the user's guess
int * answer, * revealed, * guess;
//seed the random number generator
srand(time(0));
//Begin the program by showing the initial greeting to the user
greeting();
//Ask the user for the length and difficulty
setParameters(&length, &difficulty);
//Create the initial arrays of size length
answer = createHideList(length, difficulty);
revealed = createShowList(length);
guess = createShowList(length);
printf("\nThere are %d numbers ranging from 1 to %d.\n\n", length, difficulty*3);
//Loop until the user solves the puzzle
while (!solved(answer, guess, length)) {
//Show the information gathered so far and prompt the user for their next guess
display(revealed, length);
getGuess(guess, length);
processGuess(answer, revealed, length, guess);
}
printf("Congratulations! You guessed all the values!\n\n");
//These functions are necessary because we are using memory allocation functions in create...List
free(answer);
free(revealed);
free(guess);
return 0;
}
//Functions
//Pre-conditions: none
//Post-conditions: Prints a welcome message to the screen
void greeting() {
printf("Welcome to Codebreaker Training!\n\n");
printf("You will be presented with a set of hidden values. Your job is to guess these\n");
printf("values and their correct order. After each guess you will be given feedback.\n\n");
printf("Values that are correct in magnitude and in the correct location\nwill be revealed. These are ");
printf("perfect matches.\n\nThen you will be told how many other numbers are correct in magnitude only.\n");
printf("These are imperfect matches. No additional information will be revealed.\n\n");
return;
}
//Pre-conditions: length and difficulty are valid values established by the setParameters function
//Post-conditions: create an array of size length and populate it with random
// values based on the difficulty
int * createHideList(int length, int difficulty) {
//i is a counter
//array is an integer array, allocated "length" integers
int i;
int * array = (int *)malloc(sizeof(int) * length);
//traverse the valid indices of the array
//assign each index a random value from 1 - difficulty*3
for(i=0; i<length; i++)
array[i] = rand() % (difficulty*3) + 1;
//return the beginning of the array to the main function
return array;
}
//Pre-conditions: length has a valid value established by the setParameters function
//Post-conditions: create an array of size length and initialize to zero
int * createShowList(int length){
//i is a counter
//array is an integer array, allocated "length" integers
int i;
int * array = (int *)malloc(sizeof(int) * length);
//traverse the valid indices of the array
//assign each index an initial value of 0
for(i=0; i<length; i++)
array[i] = 0;
//return the beginning of the array to the main function
return array;
}
//Pre-conditions: length and difficulty are integer pointers
//Post-conditions: length and difficulty will be set by the user
// Function should verify that these values are valid
//What to do in this function: Prompt the user for the length of the code. Remember
//that the parameter length is a pointer, so it cannot store an integer value. You will need additional
//variables. Ensure that the user gives you a value between 5 and 10, inclusive. If their
//value is invalid, continue to prompt them until they provide a valid one. Assign length the location
//of the valid integer. Repeat this process for the difficulty parameter. Difficulty
//must be 1, 2, or 3 to continue.
void setParameters(int * length, int * difficulty) {
int temp;
printf("Enter the length of code: ");
scanf("%d", &temp);
while(temp < 5 || temp > 10)
{
printf("Length should be between 5 and 10 inclusive.\n");
printf("Enter the length of code: ");
scanf("%d", &temp);
}
*length = temp;
printf("Enter the difficulty of code: ");
scanf("%d", &temp);
while(temp < 1 || temp > 3)
{
printf("Difficulty should be either 1, 2, or 3.\n");
printf("Enter the difficulty of code: ");
scanf("%d", &temp);
}
*difficulty = temp;
}
//Pre-conditions: showlist is an integer array of size length
//Post-conditions: displays the contents of showlist using - for 0
//What to do in this function: Traverse the showlist array and print a - whenever the value is 0
//If the value is not zero, print the actual value. For example, if the code is 12311 and the
//user has identified the location of the 1s, the showlist/revealed array will contain 10011
//and you should display 1--11
void display(int showlist[], int length) {
int i;
for(i=0; i < length; i++)
if(showlist[i] == 0)
printf("-");
else
printf("%d", showlist[i]);
}
//Pre-conditions: guess is an integer array of size length
//Post-conditions: reads in the guess from a user as a string and converts it to an integer array
//What to do in this function: The user will enter their values all together. For example: 12311
//Read this in as a string and then store each individual integer value in the guess array.
//Since the elements of the input will be characters, you will need to convert to integers. For example
//you would need to convert from '1' to 1. Character representations of digits start with '0' with ASCII value 48.
void getGuess(int guess[], int length) {
int i;
char string[10];
scanf("%s", &string);
for(i=0; i < length; i++)
guess[i] = string[i] - '0';
}
//Pre-conditions: both hidelist and guess are integer arrays of size length
// hidelist represents the answer the user is looking for
// guess represents the user's current guess
//Post-conditions: determines if the user has found all of the hidden values
//What to do in this function: Traverse the arrays and check to see if all of the values
//in hidelist are the same as the values in guess. If they are return 1 for true,
//return 0 for false otherwise.
int solved(int hidelist[], int guess[], int length) {
int i;
for(i=0; i < length; i++)
if(hidelist[i] != guess[i])
return 0;
return 1;
}
//Pre-conditions: hidelist, showlist, and guess are integer arrays of size length
// hidelist represents the answer the user is looking for
// showlist shows the values the user has already discovered
// guess is the user's current guess
//Post-conditions: evaluates the current guess and updates showlist
//What to do in this function: Compare hidelist to guess. If any values match exactly,
//update the showlist to reflect the information the user has discovered. Then, print out
//the number of perfect matches the user has by calling the PerfectMatches function. Print
//out the number of imperfect matches the user has by calling the ImperfectMatches function.
//Use the statement from the samples for your printf control string.
void processGuess(int hidelist[], int showlist[], int length, int guess[]) {
int i;
for(i=0; i < length; i++)
{
if(hidelist[i] == guess[i])
showlist[i] = guess[i];
}
printf("You have %d perfect matches and %d imperfect matches.\n", PerfectMatches(hidelist, guess, length), ImperfectMatches(hidelist, guess, length));
}
//Pre-conditions: hidelist and guess are integer arrays of size length
// hidelist represents the answer the user is looking for
// guess is the user's current guess
//Post-conditions: evaluates the current guess and returns the number of perfect matches
//What to do in this function: Compare hidelist to guess. Return the number of times
//the value in guess exactly matches the corresponding value in hidelist.
int PerfectMatches(int hidelist[], int guess[], int length) {
int count = 0, i;
for(i=0; i < length; i++)
if(hidelist[i] == guess[i])
count++;
return count;
}
//Pre-conditions: hidelist and guess are integer arrays of size length
// hidelist represents the answer the user is looking for
// guess is the user's current guess
//Post-conditions: evaluates the current guess and returns the number of imperfect matches
//What to do in this function: Create temporary copies of both arrays by calling the copyArray function
//twice. This is necessary because we'll need to make changes to both arrays without modifying the
//originals. Mark out the spots on the arrays that match exactly. They will be counted in the perfect
//matches instead. Use any value that won't be present in the hidelist.
//Go through the hidelist array and look for matches in the guess array. Anytime a value matches,
//regardless of location, count it as an imperfect match and mark it so it won't get counted again.
//Return the number of imperfect matches
//Hint: you will need a nested for loop.
int ImperfectMatches(int hidelist[], int guess[], int length) {
int count = 0, i, j;
int hidelistDup[length], guessDup[length];
copyArray(hidelistDup, hidelist, length);
copyArray(guessDup, guess, length);
for(i=0; i < length; i++)
if(hidelistDup[i] == guessDup[i])
hidelistDup[i] = guessDup[i] = -1;
for(i = 0; i < length; i++)
{
for(j=0; j < length; j++)
if(guess[i] == hidelist[j] && i != j && guess[i] != -1)
{
count++;
hidelist[j] = -1;
}
}
return count;
}
//Pre-conditions: dest and source are integer arrays of size length
// source represents a source array: an array to be copied
// dest represents a desitnation array: the location of the copy
//Post-conditions: dest will contain a copy of source
//What to do in this function: traverse the source array and copy each element into
//the corresponding location of the dest array
void copyArray(int dest[], int source[], int length) {
int i;
for(i=0; i < length; i++)
dest[i] = source[i];
}
My problem is the output ends up reverses the imperfect and perfect numbers, not sure why.
Enter the length of code: 5
Enter the difficulty of code: 1
There are 5 numbers ranging from 1 to 3.
-----11111
You have 0 perfect matches and 2 imperfect matches.
---11
Please if anyone can help it would be seriously much appreciated.
Related
Context: I need to write a program that will accept inputs which will be stored into the array. Before storing in to the array, the inputted number must be checked if it already exists in the array or not. If it does not exist, it is stored into the array. If it exists, another input will be asked.
Now, my code will get inputs from the user, but the code will only work for the first input. It won't work for the second until the last input. Any pointers?
This is my code:
#include<stdio.h>
#define size 5
main()
{
int i;
arr[size];
input;
printf("This program will accept ");
printf("unique inputted numbers that will be stored");
printf(" in an array\n");
for(i = 0;i < size;i++)
{
printf("Enter input: ");
scanf("%d",&input);
if (unique(arr,input,i))
arr[i] = input;
else
i--;
//decrement i because ask for input again
}
for(i = 0;i < size;i++)
printf("%d ",arr[i]);
}
int unique(int arr[],int input,int i)
{
int n, z;
n = 0;
z = 1;
while(i > n)
{
if(arr[n] == input)
{
scanf("%d",&n);
z = 0;
break;
}
else
n=1;
break;
}
return z;
}
Your code is wrong at multiple levels:
The logic in the unique function is wrong.
Doing the scanf in the unique function is extremely bad design. The only thing unique should do is return 0 if input is already in the array.
You have used implicit variable declarations here: arr[size]; input;, it should be int arr[size]; int input;.
You should use descriptive variable names which makes your code easier to understand.
This is a working example (explanations in comments).
#include <stdio.h>
#define SIZE 5 // use capitals for macros (this is a convention)
int unique(int arr[], int value, int arrsize)
{
for (int i = 0; i < arrsize; i++)
{
if (arr[i] == value)
{
return 0; // value found in array
}
}
return 1; // value not found in array
}
void Test(int arr[], int arrsize, int value, int expected)
{
if (unique(arr, arrsize, value) != expected)
printf("Test failed for value %d\n", value);
}
void runtests()
{
int arr[] = { 1,2,3 };
Test(arr, 4, sizeof(arr) / sizeof(*arr), 1);
Test(arr, 1, sizeof(arr) / sizeof(*arr), 0);
Test(arr, 3, sizeof(arr) / sizeof(*arr), 0);
}
#define size 5
int main()
{
int i;
int arr[size]; // declare int variable
int input; // declare int variable
printf("This program will accept unique inputted numbers that will be stored in an array\n");
for (i = 0; i < size; i++)
{
printf("Enter input %d: ", i + 1);
scanf("%d", &input);
if (unique(arr, input, i)) // value already in the array?
arr[i] = input; // no => put it there
else
{ // yes => ask again
printf(" >> %d is already in the array\n");
i--;
}
}
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}
There are two more functions Test and runtests in this code. They are not called by this code, but they can be very useful for debugging. As an exercise try to understand why they can be useful during the debug phase of your code.
You're close, but overcomplicating it slightly.
Let's take a step back and think about this at a high level. You want to store unique inputs in the array, up to the size of the array. In pseudocode:
while array not full
prompt for and read next input
if input not already in array
store input
else
write a message
end if
end while
What's really key is that you only need one input statement - your unique function should only check for the presence of the input value in the array and return true or false. It shouldn't do any input of its own.
So your main loop is more like
while ( i < size )
{
fputs( "Gimme a number: ", stdout );
/**
* Break out of the loop if there's an error
* on input.
*/
if ( scanf( "%d", &input ) != 1 )
break;
if ( unique( arr, i, input ) )
arr[i++] = input;
else
printf( "%d already exists in the array, try again.\n", input );
}
All your unique function needs to do is cycle through the elements of the array. By calling unique with i instead of size it will only check array elements that have been written to so far and not bother with unassigned elements. This way you don't have to make sure that all of the array elements have been initialized to some known, out-of-band value that's guaranteed to compare unequal to any valid input.
You'll need to compile against C99 or later and include stdbool.h to use the bool type and the true and false constants.
#include <stdbool.h>
...
bool unique( int *arr, size_t size, int input )
{
bool result = true;
for( size_t i = 0; i < size && result; i++ )
if ( arr[i] == input )
result = false;
return result;
}
If you want to get really terse, you could directly assign the result of the Boolean expression to result:
for ( size_t i = 0; i < size && result; i++ )
result = (arr[i] == input);
but people will hit you. It's perfectly valid code, but a little eye-stabby, and most programmers aren't used to seeing Boolean expressions outside of an if, for, while, or switch statement control expression.
Finally, some suggestions:
Fix your formatting. The compiler doesn't care, but it makes it easier for other people to understand what you're trying to do and to spot mistakes.
The presence of main() in your code suggests you're using C89 or K&R C. C99 did away with implicit int declarations. You really should define main as either int main( void ) or int main( int argc, char **argv ). Furthermore, you should move to a compiler that supports later versions of C (C11 or C18).
I first initialize 0 to counter[10], and it is OK. However, somewhere I want to re-initialize with 0 again but fail.
The error message is
[Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int digit, counter[10] = {0}; //Declare variable "digit" to store individual number to be compared and declare an array for the input numbers
bool rep_digits; //Declare a boolean variable to determine whether the input numbers has repetitive numbers or none
int n; //Declare variable "n" to store the input numbers
while (true) { //This while loop serves as a loop for the user input
printf("\nEnter a number (capped at on this compiler): ");
scanf("%d", &n);
if (n == 0) { //The user input loop terminates when the user input a 0
break;
}
printf("Repeated digits(s): \n");
while (n > 0) { //If the condition is true, execute the arguments inside
digit = n % 10; //Obtain the remainder of the input number
counter[digit]++; //Increase the counter for the obtained remainder in the array
if (counter[digit] == 2) { //If the counter of that particular remainder is equal (and only equal) to 2, print out the number
printf("%2d\n", digit);
rep_digits = true; //Set the boolean variable to true if there is a repetitive number in the input
}
n /= 10; //Divide the input number by 10 to determine the next number either repetitive or not
}
counter[10] = {0}; // re-initialize to 0
if (rep_digits == false) { //If the boolean variable stays false then display this message
printf("No repeated digits\n");
}
}
return 0;
}
counter[10] = {0}; writing beyond the array size causes undefined behavior.
suppose you have array size as int counter[10], you should write only from counter[0] till counter[9]
if you want to initialize all the array elements to 0, then you can do it two ways.
int counter[10] = {0}; \\this works only at the same place where you declare
memset(counter,0,sizeof(counter)); \\ this can be done at any other place in the program
In your program replace counter[10] = {0}; with memset(counter,0,sizeof(counter));
it should work just fine.
Instead of using int counter[10] = {0}
Use memset
int counter[10]; memset(counter,0,sizeof(counter));
The above memset line fills every value of counter array to 0.
I'm writing a code a that prompts the user to enter a string
&
create a function that is a type void that prints out the character that was used the most
(As in where it appeared more than any other ones)
&
also shows the number of how many times it was in that string.
Therefore here is what I have so far...
#include <stdio.h>
#include <string.h>
/* frequent character in the string along with the length of the string (use strlen from string.h – this will require you to #include <string.h> at the top of your program).*/
/* Use array syntax (e.g. array[5]) to access the elements of your array.
* Write a program that prompts a user to input a string,
* accepts the string as input, and outputs the most
* You should implement a function called mostfrequent.
* The function prototype for mostfrequent is: void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts);
* Hint: Consider the integer value of the ASCII characters and how the offsets can be translated to ints.
* Assume the user inputs only the characters a through z (all lowercase, no spaces).
*/
void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
int array[255] = {0}; // initialize all elements to 0
int i, index;
for(i = 0; most_freq[i] != 0; i++)
{
++array[most_freq[i]];
}
// Find the letter that was used the most
qty_most_freq = array[0];
for(i = 0; most_freq[i] != 0; i++)
{
if(array[most_freq[i]] > qty_most_freq)
{
qty_most_freq = array[most_freq[i]];
counts = i;
}
num_counts_++;
}
printf("The most frequent character was: '%c' with %d occurances \n", most_freq[index], counts);
printf("%d characters were used \n", num_counts_);
}
int main()
{
char array[5];
printf("Enter a string ");
scanf("%s", array);
int count = sizeof(array);
mostfrequent(count , array, 0, 0);
return 0;
}
I'm getting the wrong output too.
output:
Enter a string hello
The most frequent character was: 'h' with 2 occurances
5 characters were used
should be
The most frequent character was: 'l' with 2 occurances
5 characters were used
let's do it short (others will correct me if I write something wrong ^_^ )
you declare a int like this:
int var;
use it like this :
var = 3;
you declare a pointer like this :
int* pvar;
and use the pointed value like this:
*pvar = 3;
if you declared a variable and need to pass a pointer to it as function parameters, use the & operator like this :
functionA(&var);
or simply save its address in a pointer var :
pvar = &var;
that's the basics. I hope it will help...
The function prototype you are supposed to use seems to include at least one superfluous parameter. (you have the total character count available in main()). In order to find the most frequently appearing character (at least the 1st of the characters that occur that number of times), all you need to provide your function is:
the character string to be evaluated;
an array sized so that each element represents on in the range of values you want to find the most frequent (for ASCII characters 128 is fine, for all in the range of unsigned char, 256 will do); and finally
a pointer to return the index in your frequency array that holds the index to the most frequently used character (or the 1st character of a set if more than one are used that same number of times).
In your function, your goal is to loop over each character in your string. In the frequency array (that you have initialized all zero), you will map each character to an element in the frequency array and increment the value at that element each time the character is encountered. For example for "hello", you would increment:
frequency['h']++;
frequency['e']++;
frequency['l']++;
frequency['l']++;
frequency['o']++;
Above you can see when you are done, the element frequency['l']; will hold the value of 2. So when you are done you just loop over all elements in frequency and find the index for the element that holds the largest value.
if (frequency[i] > frequency[most])
most = i;
(which is also why you will get the first of all characters that appear that number of times. If you change to >= you will get the last of that set of characters. Also, in your character count you ignore the 6th character, the '\n', which is fine for single-line input, but for multi-line input you need to consider how you want to handle that)
In your case, putting it altogether, you could do something similar to:
#include <stdio.h>
#include <ctype.h>
enum { CHARS = 255, MAXC = 1024 }; /* constants used below */
void mostfrequent (const char *s, int *c, int *most)
{
for (; *s; s++) /* loop over each char, fill c, set most index */
if (isalpha (*s) && ++c[(int)*s] > c[*most])
*most = *s;
}
int main (void) {
char buf[MAXC];
int c[CHARS] = {0}, n = 0, ndx;
/* read all chars into buf up to MAXC-1 chars */
while (n < MAXC-1 && (buf[n] = getchar()) != '\n' && buf[n] != EOF)
n++;
buf[n] = 0; /* nul-terminate buf */
mostfrequent (buf, c, &ndx); /* fill c with most freq, set index */
printf ("most frequent char: %c (occurs %d times, %d chars used)\n",
ndx, c[ndx], n);
}
(note: by using isalpha() in the comparison it will handle both upper/lower case characters, you can adjust as desired by simply checking upper/lower case or just converting all characters to one case or another)
Example Use/Output
$ echo "hello" | ./bin/mostfreqchar3
most frequent char: l (occurs 2 times, 5 chars used)
(note: if you use "heello", you will still receive "most frequent char: e (occurs 2 times, 6 chars used)" due to 'e' being the first of two character that are seen the same number of times)
There are many ways to handle frequency problems, but in essence they all work in the same manner. With ASCII characters, you can capture both the most frequent character and the number of times it occurs in a single array of int and an int holding the index to where the max occurs. (you don't really need the index either -- it just save looping to find it each time it is needed).
For more complex types, you will generally use a simple struct to hold the count and the object. For example if you were looking for the most frequent word, you would generally use a struct such as:
struct wfreq {
char *word;
int count;
}
Then you simply use an array of struct wfreq in the same way you are using your array of int here. Look things over and let me know if you have further questions.
Here is what I came up with. I messed up with the pointers.
void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
*qty_most_freq = counts[0];
*most_freq = 'a';
int i;
for(i = 0; i < num_counts_; i++)
{
if(counts[i] > *qty_most_freq)
{
*qty_most_freq = counts[i];
*most_freq = 'a' + i;
}
}
}
/* char string[80]
* read in string
* int counts[26]; // histogram
* zero counts (zero the array)
* look at each character in string and update the histogram
*/
int main()
{
int i;
int num_chars = 26;
int counts[num_chars];
char string[100];
/*zero out the counts array */
for(i = 0; i < num_chars; i++)
{
counts[i] = 0;
}
printf("Enter a string ");
scanf("%s", string);
for(i = 0; i < strlen(string); i++)
{
counts[(string[i] - 'a')]++;
}
int qty_most_freq;
char most_freq;
mostfrequent(counts , &most_freq, &qty_most_freq, num_chars);
printf("The most frequent character was: '%c' with %d occurances \n", most_freq, qty_most_freq);
printf("%d characters were used \n", strlen(string));
return 0;
}
I have an integer array like int a[50];. Now I want to store values entered by the user in the integer array as integers.
The problem is that I don't know the number of elements the user is going to input and hence I am unable to traverse the entire array.
So is there any method for the user to input the values dynamically and store it in the integer array and display it.
For this take a input from user for number of element to have in an array. Then malloc that memory and store the inputs in the array.
You can use realloc and make a specific input as end of the input
int readinput(int *value)
{
int status;
//function returns 0 on conversion -1 if exit keywoard entered
return status;
}
int value, *table = NULL,size = 0;
while (!readinput(&value))
{
table = realloc(table, (size++ + 1) * sizeof(int));
if (table == NULL)
{
break;
}
table[size] = value;
}
example converting function you can find here:
How to get Integer and float input without `scanf()` in c? in my answer
This code should work well, you can change BUFFER_SIZE to whatever you want, after these steps array will realloc to arr size + BUFFER_SIZE.
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 50
int main(void)
{
int * userInputBuffer = malloc(sizeof(int) * BUFFER_SIZE);
int userInput;
int counter = 0;
int reallocCounter = 1;
while ((scanf(" %d", &userInput)) == 1)
{
if ((counter % BUFFER_SIZE) == 0)
{
userInputBuffer = realloc(userInputBuffer, (reallocCounter++ + 1) * BUFFER_SIZE * sizeof(int));
}
userInputBuffer[counter++] = userInput;
}
for (int i = 0; i < counter; i++)
{
printf("User input #%d: %d\n", i + 1, userInputBuffer[i]);
}
free(userInputBuffer);
return 0;
}
The following solution uses the scanf() function with %d as format specifier. The while loop checks the return value so that it can detect if the conversion was successful. If anything other than a valid number is inputted the loop will break. A valid number is also beginning with space but not with any other characters.
The memory is allocated with malloc() and will be reallocated with realloc() each time the user entered a number. Note that there is no error checking about the reallocation this should be done with a temporary pointer like here.
Further this code will reallocate for every single number. You could also reallocate in bigger steps to avoid reallocation on every input. But this only matters if there is much data. In this case the speed improvement wouldn't matter.
After the memory is no longer needed you have to use free().
The user can type:
1<Enter>
2<Enter>
3<Enter>
any characters<Enter>
and will get:
Numbers entered:
1 2 3
as output.
Code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
size_t idx;
int number;
size_t count = 0;
int* numberArr = malloc(sizeof(*numberArr));
printf("Enter each number separated by <Enter>,\n"
"to abort type any other character that isn't a number!\n");
while (scanf("%d", &number) == 1)
{
numberArr = realloc(numberArr, (count + 1) * sizeof(*numberArr));
numberArr[count] = number;
count++;
}
printf("\nNumbers entered:\n");
for (idx = 0; idx < count; idx++)
{
printf("%d ", numberArr[idx]);
}
printf("\n");
free(numberArr);
return 0;
}
I need my program to read integer values into adjacent elements in the array, and set the counter to the total number of integers read. I also need another loop to print the values to the screen.
How do I go about doing this?
#include <stdio.h>
int main(void) {
int numArray[100];
int counter, value;
printf("Enter array length \n");
scanf("%d", &counter);
int i = 0;
while(i < counter) {
scanf("%d", &numArray[i]);
value = numArray[i];
i++;
}
return 0;
}
I need my program to read integer values into adjacent elements in the array, and set the counter to the total number of integers read. I also need another loop to print the values to the screen.
How do I go about doing this?
The overall program should work, however you need to initialize:
value = 0; /*Initialize Variables */
counter = 0;
In C when you enter a function like main variables like value and counter get initialized with random value -- if you don't initialize. It could cause you problems.
while(i < counter) /*Scans the values into the array */
{
scanf("%d", &numArray[i]);
value = numArray[i];
i++;
}
The scanf function here scans the value you entered into the array.
I'm not sure what you would use values for; your array stores the values for you. However, it could make your code shorter if you use it in a different way.
A loop to print the values would look similar to your original loop.
while(i < counter)
{
printf("%d", &numArray[i]); /*Prints the values in the array */
i++;
}