Cannot re-initialize after first initialize value to integer array - c

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.

Related

How to print random even numbers "n" times? Print the number many times mentioned in the output

Can someone help me with this? I want to write a code that will print random even number "i" times. Here "i" is variable and input (i is always greater than 0). Example: Input (4) I want output to be (4,4,4,4), Input (2) I want output to be (2,2). I want to print the number many times mentioned in the input. Here is the question
Here, the term "random" may not be appropriate.
In order to achieve this, you can:
get the numerical representation of the user input. To do so you can use strtol which returns a number.
use a for-loop print the N occurrences using the standard printf function along with the number formatter %d.
For instance:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int number;
int i;
/* `argc` contains the total number of arguments passed to the
* application. There is always at least one argument (i.e.: the
* application name). Here, we ensure the user has given a argument
* which we expect to be the number (i).
*
* If there are less than two arguments given then the user has
* not passed anything => the command line was "$ ./a.out". */
if (argc < 2) {
goto usage;
}
/* Get the user input number by parsing the user given argument.
* As arguments are string of characters, this function transforms
* the string "1234" into 1234. The result is a number we will be
* able to manipulate (add, sub, mul, div, etc.). */
char *endptr;
number = strtol(argv[1], &endptr, 10);
/* We want to ensure the input was really a number.
* The `strtol` function provides a way to verify whether the
* given string is correctly formatted by giving the last character
* of the string. In case the number is not formatted correctly,
* then the last char is not the NULL terminating char. */
if (*endptr != '\0') {
goto usage;
}
/* Ensure the number is positive. */
if (number < 0) {
goto usage;
}
/* This for loop executes "number" of times. We have a counter
* `i` which value will be incremented from [ 0 to "number" [.
* Each time we execute the loop, we print the number. */
for (i = 0; i < number; i++) {
printf("%d ", number);
}
printf("\n");
return 0;
usage:
// TODO
return 1;
}
The easiest way is to read input from the user and just display the number "n" times. Here's an example:
#include <stdio.h>
int main(int argc, char **argv) {
int user_input, is_correct; // user_input is a number to be displayed
// scanf reads input from the user, %d is an integer
is_correct = scanf("%d", &user_input);
// check if user entered a number
if(!is_correct) {
printf("Incorrect input, enter number!");;
return -1;
}
// check if number is even
if(user_input % 2 != 0) {
printf("Number is not even, try again!");
return -1;
}
// display number
for(int i = 0; i < user_input; ++i) {
printf("%d ", user_input);
}
return 0;
}

C: How can I split the user input of a number and store it into an array of elements?

I have a number, 321197186 which the user inputs. How can I store this number into an array one element at a time. Basically, I am trying to store the 1st digit into 0th element and so on. And then I have to do some computation on that number.
Represent your number as a string, where every character of that string will be the corresponding digit of your number.
There are a plethora of method to read a string, but I suggest you use fgets() like this:
#include <stdio.h>
#include <string.h>
#define MAX_LEN 10
int main (int argc, char *argv[])
{
char number[MAX_LEN];
printf("Enter a number: \n");
fgets(number, MAX_LEN , stdin);
printf("%s\n", number);
return 0;
}
With a for loop, you access the characters (digits) of the string (number) one by one, if you like.
I suggest you also eat the trailing newline that fgets() leaves in the input array, as already explained in Removing trailing newline character from fgets() input.
Alternative solution proposed by bruno#:
scanf("%9s", number);
Read more in C - scanf() vs gets() vs fgets().
Assume you have
int num;
if (scanf("%d", &num) != 1)
{
// Input error
exit(1);
}
// Now the user input is available in num
then you do
#define MAX_DIGITS 32
int digits[MAX_DIGITS] = { 0 };
int index = 0;
while(num != 0 && index < MAX_DIGITS)
{
digits[index] = num % 10;
++index;
num = num / 10;
}
// Now the array digits holds the individual digits
// and index holds the number of valid digits
You can consider this logic in C -
number = 321197186
while(number> 0) - leave if number becomes 0
{
int last_digit = number % 10; - Last digit from the number
printf("%d",last_digit);
number = number / 10; - to get the remaining number.
}
This can be also done in Python as -
number = 321197186
list1 = []
for i in str(number):
list1.append(i)
print(list1)
store this number into an array one element at a time.
Let us take advantage of the input process to have a convenient way to determine the length of input including leading zeros (but not input with a sign, leading spaces) by using "%n" to record the offset of the scan.
Use % 10 to exact the least significant decimal digit of the number.
int number;
int offset;
if (scanf("%d%n", &number, &offset) == 1) {
int a[offset]; // VLA
while (offset > 0) {
a[--offset] = number % 10;
number /= 10;
}
for (int i = 0; i < sizeof a/sizeof a[0]; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
}
Output
a[0] = 3
a[1] = 2
a[2] = 1
a[3] = 1
a[4] = 9
a[5] = 7
a[6] = 1
a[7] = 8
a[8] = 6
But as bruno points out, you just have to check it as a string as an user input with fgets is an array of characters (even if we are talking about numbers).
For more detail:
for(i=0;i<sizeof(array_input);i++){
//Store the char into another array
}

C: Using arrays to show guessed numbers

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.

While loop to read interger values from standard input

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++;
}

How to count Integer array elements like char based strlen() in C?

I would like to count the number of elements in an integer array(sized, like: array[1000]) after input without counting manually while inputting(using scanf() which is = number of arguments passed to scanf).Though int arrays are not null terminated as well as scanf() cannot be used like getchar() or gets() and no availale function like strlen() for int arrays,is it possible to write a C program to prompt the user to input as many numbers as he wishes and the program will count them(total arguments passed to scanf()) and print the maximum using arrays or pointers?
Without having a termination value, you will have to count the inputs as they are made. You could do this by defining a struct to hold the array. Your program does not know how many integers you will enter, and this code allocates more memory when the array is full, keeping track of the array size and elements used.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_STEP 10 // increment in array size
typedef struct {
int maxlen; // capacity of array
int length; // elements used
int *array; // the array pointer
} istruct;
int main(void) {
istruct intarr = {0}; // empty array
int i;
printf ("Enter some integers:\n");
while (scanf("%d", &i) == 1) {
if (intarr.length >= intarr.maxlen) {
intarr.maxlen += ARRAY_STEP; // increase array size
intarr.array = realloc(intarr.array, intarr.maxlen * sizeof(int));
if (intarr.array == NULL) {
printf("Memory allocation error\n");
exit (1);
}
}
intarr.array[intarr.length++] = i;
}
printf ("You entered:\n");
for (i=0; i<intarr.length; i++)
printf ("%-10d", intarr.array[i]);
printf ("\n");
if (intarr.array)
free(intarr.array);
return 0;
}
strlen() iterates on the character array until the C string termination character (ASCII \0) is encountered. So it is COUNTING the elements. If you want to do that for an int array I guess you could also have a reserved 'terminator' value for your array, make room for it (allocate one more int in your array for the terminator) and implement your own int_array_len() similar to strlen. However, in your case counting the elements while inputting them seems like a much better way to go.
Smart vertion:
#include <stdio.h>
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
/*for(i=0;i<100000;i++)
a[i]=0;*/
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}
It's pretty simple.
just declare of your desired "initial size". And keep checking if input is a valid integer or not.
if((scanf("%d",&a[i]))==1) this would be true if and only if the input is a valid integer. hence the moment the input is not an int, it exits the loop. You can count the number of input values within the same loop and also the max values.
Here is the code:
#include <stdio.h>
#include<limits.h>
int main()
{
int a[100],max = INT_MIN;
int i,j,count=0;
printf("Start Entering the integers... Give any non-integer input to stop:\n");
for(i=0;i<100;i++)
{
if((scanf("%d",&a[i]))==1) {
count++;
if(a[i]>max) {
max = a[i];
}
}
else
break;
}
printf("number of input values: %d;\nThe maximum input value: %d",count,max);
return 0;
}

Resources