I'm new to C.
I've made some code which creates an array, allows for user input to initialise the indexes of the array, and finally the inputs are checked against some parameters.
When I was originally testing the code, the function which contained the verification process was a 'void' function, but since I want this verification function to be the gatekeeper as to whether other functions run in my program, I changed it to an 'int' function so it could return a value which determined whether or not the rest of the program would run.
However, now it returns the printf statement in about invalid inputs twice. When it was a void function it would only display it once. How do I only get the printf statement in 'int verify' to display once?
Expected Input & Output:
1 2 1 3 4 5 } Input
Invalid input: 6 integers 1..9 in sorted order must be supplied. } Output
Current Output:
1 2 1 3 4 5 } Input
Invalid input: 6 integers 1..9 in sorted order must be supplied.}
Invalid input: 6 integers 1..9 in sorted order must be supplied.} Output
#define SIZE 6 //Size of array
void input(int selection[SIZE]);
int verify(int selection[SIZE]);
int main (void){
int selection[SIZE] = {0};
input(selection);
verify(selection);
if (verify(selection) == 1) {
printf("Correct!\n");
}
return 0;
}
//Function which assigns user input into array
void input(int selection[SIZE]){
int i = 0;
while (i < SIZE) {
scanf("%d", &selection[i]);
i++;
}
}
//Function to verify that user's input stays within the bounds
int verify(int selection[SIZE]){
int ver1 = 0;
int ver2 = 0;
int para = 1;
//Checks if inputted numbers are in desired range.
while (ver1 < SIZE) {
if (selection[ver1] > 9 || selection[ver1] < 1) {
printf("Invalid input: 6 integers 1..9 ");
printf("in sorted order must be supplied.\n");
ver2 = SIZE; //Prevents other checks from running as to have duplicate text
ver1 = SIZE; //Prevents other checks from running as to have duplicate text
para = 0;
}
ver1++;
}
//Loops through each value inputed into the function and verifies that
//they are in sorted order
while (ver2 < (SIZE-1)) {
if (selection[ver2] > selection[ver2+1]){
printf("Invalid input: 6 integers 1..9");
printf(" in sorted order must be supplied.\n");
ver2 = SIZE;
para = 0;
}
ver2++;
}
return para;
}
Change this code:
verify(selection);
if (verify(selection) == 1) {
printf("Correct!\n");
}
to this:
if (verify(selection) == 1) {
printf("Correct!\n");
}
Basically, verify was producing output twice because you were calling it twice.
Your code was calling verify twice, causing 'invalid input' to be printed twice.
You called it once before the if, and once inside the if.
If you want to check what the verify function returned, without calling it again, you can write something like this:
int checkResult = verify(selection);
if ( checkResult == 1) {
printf("Correct!\n");
Related
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;
}
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 a college student in my first year of software engineering. I am in the fourth week of my semester and am having trouble in my programming class. Currently, I was given this assignment in which I was given a function called "getNum()" and I had to use it in another function where the program user, would input a number and the function that I program (must be named isOdd()) would determine if the number is odd or even. Then the main function would print whether the number is odd or even. This is the way that my professor worded it:
" Write a program that uses the getNum() function provided to you in Assignment 2 to get anumber from the user (prompting them first, as always). Create and use a function called isOddwith parameters (the number) and return values (1 ifthe number is odd, 0 if the number is evenOR use a bool or boolean data type, your choice) to determine if thenumber is odd. In main(), tell the user (by displaying using printf()or cout) whether the number is evenor odd."
Now, the problem I am having is understanding programming as I am fairly new to it and some words confuse me, such as parameter and return value. To give you and idea of what I have written so far,
#include <stdio.h>
int isOdd(int numInput);
int getNum(void);
int main(void)
{
int number = 0;
while (number > -1)
{
if (isOdd(0))
{
printf("The number is even.\n");
}
else if (isOdd(1))
{
printf("The number is odd.\n");
}
}
return 0;
}
int isOdd(int numInput)
{
int myNumber = 0;
printf("Please enter a number: ", numInput);
myNumber = getNum();
if (myNumber % 2 == 0)
{
myNumber == 0;
}
else
{
myNumber == 1;
}
return myNumber;
}
#pragma warning(disable: 4996)
int getNum(void)
{
/* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
char record[121] = { 0 }; /* record stores the string */
int number = 0;
/* NOTE to student: indent and brace this function consistent with your others */
/* use fgets() to get a string from the keyboard */
fgets(record, 121, stdin);
/* extract the number from the string; sscanf() returns a number
* corresponding with the number of items it found in the string */
if (sscanf(record, "%d", &number) != 1)
{
/* if the user did not enter a number recognizable by
* the system, set number to -1 */
number = -1;
}
return number;
}
This is what I have written, trying to do things accordingly to my professor's instructions, as I do not yet know how to properly use booleans. As you can see, at the bottom is the getNum() function that my professor has said is mandatory for this assignment. As of now, everything I input, I am told is even. I am not asking for you guys to solve and do everything for me but I want to understand what I am doing wrong, what my thinking is doing wrong and to overall better my understanding for future programming. Thank you
It's hard to help you without knowing why you did what you did. A lot of the code is just baffling:
if (isOdd(0))
Why are you passing a zero to isOdd?
printf("Please enter a number: ", numInput);
myNumber = getNum();
Is numInput supposed to be the number they enter or is myNumber supposed to be?
if (myNumber % 2 == 0)
{
myNumber == 0;
}
The statement myNumber == 0 compares myNumber to zero to see if they're equal. It does nothing useful here since you ignore the result of the comparison.
The function:
int getNum(void)
Takes no parameters (void), and returns an integer (int) value. The function itself accepts input from the standard input (stdin) stream - this is normally from the keyboard.
To complete your assignment you should write a function:
int isOdd( int value ) ;
Where value is an integer parameter and the return value is 1 if value is odd and 0 if it is even. Alternatively you are allowed to use the Boolean type:
#include "bool.h"
bool isOdd( int value ) ;
In which case you would return true for odd, and false for even.
Your isOdd() includes the getNumber() call and user prompt code. Not only is that not specified in the assignment, it is poor design making isOdd() difficult to use in more general situations. The assignment explicitly requires you to pass the value to be tested as a parameter.
The assignment does not require you to iterate the test (the while loop is not needed). The user input prompt and acceptance should be in main as follows:
int main(void)
{
printf( "Please enter a number: " ) ;
fflush( stdin ) ; // you'll may this on some platforms
int myNumber = getNum();
if( isOdd( myNumber ) )
{
printf("The number is odd.\n");
}
else
{
printf("The number is even.\n");
}
}
return 0;
}
Note that there are only two possible outcomes, so you do not need an else if( !isOdd( myNumber ) ... - if it is not odd it is implicitly even.
Your isOdd() function will work, but is over complicated. You are required to return a Boolean (a type with two possible values true/false - or an integer 1/0 which can be implicitly converted to a Boolean), and (myNumber % 2 == 0) is a Boolean expression (an expression with two possible results true or false). Anywhere you see the pattern:
if( <boolean expression> )
{
b = true ;
}
else
{
b = false ;
}
you can simply write:
b = <boolean expression> ;
In your case the Boolean determination of odd-ness is simply value % 2 != 0. You can return that directly:
bool isOdd( int value )
{
return value % 2 != 0 ;
}
Hello! I am trying to create a program (school assignment) that asks the user to enter a sequence of integer numbers between 0 - 1000. The sequence stops when the user enters a negative integer or more than 100 integers.
Actually entering, saving and creating a "counter" array with the amount of times the integers have been entered is accomplished. However, a part of the assignment is creating a void function that uses pointer variables to return what integer occurred the most times and how many times it occurred.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SEQ 100
void analyzeFrequencies(int mainArray[], int counter[], int* mOI, int* numOfOccurences);
int main()
{
int i=0, *mOI=0, *numOfOccurences=0, tempNum=0, mainArray[MAX_SEQ] = {0}, counter[MAX_SEQ] = {0};
printf("Please enter a integer between 0-1000.\nSequence will stop when you enter negative integer of after MAX_SEQ integers.\n\n");
do
{
if( scanf("%d", &tempNum) == 1)
{
if (tempNum <= 1000)
{
if (tempNum < 0)
{
printf("You decided to exit the sequence. Your array entered is:\n");
}
else
{
mainArray[i] = tempNum;
counter[tempNum]++;
++i;
}
}
else
printf("Please enter a number between 0-1000. Exit sequence by entering negative number.\n");
}
else
printf("\nError.\n");
} while(tempNum > 0 && i < MAX_SEQ);
analyzeFrequencies(mainArray, counter, mOI, numOfOccurences); //This is where the problem occurs.
if (i == 0)
{
printf("You entered no sequence.");
}
else
{
printf("\nSequence:\n");
for(int j=0; j<i; j++)
{
printf("[%d] %d\n", j, mainArray[j]);
}
printf("Most occurred item: %d\nOccurred %d times!", *mOI, *numOfOccurences);
}
return 0;
}
When I run my code, everything works fine until I execute the analyzeFrequencies() function. The program then stops working.
void analyzeFrequencies(int mainArray[], int counter[], int* mOI, int* numOfOccurences)
{
for(int i=0; i<MAX_SEQ; i++)
{
if(counter[i] > *numOfOccurences)
{
*mOI = i;
*numOfOccurences = counter[i];
}
}
}
I expect the function "void analyzeFrequencies" to return a pointer variable value through "mOI" and "numOfOccurences". mOI is the most occurred integer.
Instead, the program just stops working. I've been looking at my code for a while but can't seem to find what causes this. I might have been sitting for too long with my code and gone blind. Would appriciate any help to realize where I am going wrong!
P.S! I realize the code is not optimized at all and I would gladly receive any feedback, my main priority is however making the analyzeFrequencies function to start working!
int i=0, *mOI=0, *numOfOccurences=0, tempNum=0,
mainArray[MAX_SEQ] = {0}, counter[MAX_SEQ] = {0};
In your main funciton, you have mOI and numOfOccurences declared as pointer variables, both of which are initialized to 0, meaning they are NULL pointers. You then pass those NULL pointers into your function and dereference them. Dereferencing a NULL pointer invokes undefined behavior.
Declare these two variables as int instead of int * and pass their addresses to analyzeFrequencies.
So declare them like this:
int i=0, mOI=0, numOfOccurences=0, tempNum=0,
mainArray[MAX_SEQ] = {0}, counter[MAX_SEQ] = {0};
And call your function like this:
analyzeFrequencies(mainArray, counter, &mOI, &numOfOccurences)
This code has to get coordinates and write them to the coords array, and also return the number of coordinates that have been entered.
The code has to stop once the user enters 0 0 but the code should not save it.
For example if I enter 1 2 3 4 0 0 the code will set the array to (1,2) (3,4).
But in this code when I enter 0 0 it show me error, and once I enter the numbers at first the print show me just zeros.
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
++row;
}
printf("%.3lf %.3lf", coords[row][0], coords[row][1]); /* TEST */
}
return row+1;
}
The problem is that when you print coords[row][0] and coords[row][1] you are actually sending to stdout the next coordinates which are not still entered by the user. You are sending to stdout undefined values and not the values you entered. The line printf("%.3lf %.3lf", coords[row][0], coords[row][1]); should be printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); And add the next to line \n otherwise the information printed is illisible.
Try this code
#include <stdio.h>
#include <stdlib.h>
#define DIM 2
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
row++;
}
printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); /* TEST */
}
return row+1;
}
int main(void)
{
double cords[5][2];
int n = 5;
coordinatesread(cords, n);
return 0;
}
Okey, let's see. The problem in your code is that you are incrementing the value of row before printing the values in coords[row][0]=columnin
You are not going to print a line if the values are both zero, so you can move this line:
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
Right before this one:
++row;
The new code should look like this:
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
++row;
}
}
return row+1;
}
PD:
Notice that your code does not work fine if you want to scan N valid coordinates, because the last one will be ignored. The problem is here:
while(row!=n-1)
If you have decided to use while loop instead of for, you should iterate until row = N. Let's suppose N = 3. If you want to scan 3 valid coordinates, the loop will iterate while N != 2. This will scan only two of them (when row = 0 and row = 1). Change it to:
while(row!=n)
In addition, when you are iterating over an array (or a table in this case), using for is better than while. Both are correct, but for is more stylized. If you change it, the code look like this:
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
for(int row = 0; i < n; i++)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
}
}
return row;
}