I wrote a short code for an Arduino connected to a button that is supposed to count the number of times the button has been pressed and print it in two forms: binary and decimal.
When writing the following source code:
int x=0;
void setup() {
pinMode(2,INPUT);
pinMode(3,OUTPUT);
Serial.begin(9600);
Serial.println("DEC");
Serial.print("\t");
Serial.print("BIN");
Serial.print("\t");
}
void loop() {
while (digitalRead(2) == 0);
x++;
Serial.print(x, DEC);
Serial.print("\t");
Serial.println(x, BIN);
Serial.print("\t");
while (digitalRead(2) == 1);
}
The monitor printed the text almost intended, but instead of it being printed as intended:
decimal < decimal num >
binary < binary num >
The monitor printed it like this:
decimal
binary< decimal num >
< binary num >
Cause you are using
Serial.println("DEC");
Not
Serial.print("DEC");
println() add a new line at the end automatic
Related
So I wrote a simple program that converts a decimal to binary, that only accepts positive whole numbers. So numbers like -2 and 1.1 would output "Sorry, that's not a positive whole number." It infinitely asks the user to input a number until the user presses ctrl + D. However when I tested it it prints out the "Sorry..." statement before it ends the program.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
void DecToBin(int userInput){
int binary[32];
int i = 0;
while (userInput > 0) {
binary[i] = userInput % 2;
userInput /= 2;
i++;
}
for (int j = i - 1; j >= 0; --j) {
printf("%d", binary[j]);
}
}
int main(void) {
double userDec;
int temp;
printf("Starting the Decimal to Binary Converter!\n\n");
while(!feof(stdin)) {
printf("Please enter a positive whole number (or EOF to quit): ");
scanf("%lf", &userDec);
temp = (int)(userDec);
if ((userDec > 0) && (temp / userDec == 1)) {
printf("\n\t%.0lf (base-10) is equivalent to ", userDec);
DecToBin(userDec);
printf(" (base-2)!\n\n");
}
else {
printf("\tSorry, that was not a positive whole number.\n");
}
}
printf("\n\tThank you for using the Decimal to Binary Generator.\n");
printf("Goodbye!\n\n");
return 0;
}
(All the tab and newlines are just how it's supposed to be formatted so don't pay attention to that)
So from what I'm understanding, my program reads ctrl + D as the else in my while loops. So, any idea why that is?
It seems like you think C-d would trigger some kind of break in the code. Like the keyword break. This is not true.
Read this post to see what's happening when you press C-d: https://stackoverflow.com/a/21365313/6699433
That does not cause anything special to happen in the C code. scanf will simply not read anything. After the scanf statement, the code will continue as usual, so the code WILL unconditionally enter the if statement.
This is also a pretty severe thing, because you'll be using userDec uninitialized. scanf returns the number of successful assignments, and you should always check the return value. So in your case you want this:
if(scanf("%lf", &userDec) != 1) { /* Handle error */ }
Because if scanf does not return 1, userDec is unassigned.
To achieve what you want, simply do this:
if(scanf("%lf", &userDec) != 1)
break;
I am new to C so I am having a little difficulty!
I want to take an integer input from the user and add 7 to each of the digit in the input. All of that works, but the digits are printing in the reverse order.
How do i make the digits print in the correct order? I checked other similar questions on Stack overflow but it does not seem to work. Thanks in advance!
int main(void)
{
int numToEncrypt;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
while (numToEncrypt > 0)
{
int digit = numToEncrypt % 10;
// do something with digit
digit = (digit + 7)%10;
numToEncrypt /= 10;
printf("number is: %d \n",digit);
}
}
)
Converting the string input to an integer and back is pointless. Just work with the data as a string. eg:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int c;
if( getenv("V") ) {
printf("Please input the number you wish to encrypt: ");
fflush(stdout);
}
while( (c = getchar()) != EOF ) {
if( isspace(c) ) {
fflush(stdout);
} else if( isdigit(c) ) {
c = '0' + (c - '0' + 7) % 10;
} else {
fprintf(stderr, "Invalid input: %c", c);
return EXIT_FAILURE;
}
putchar(c);
}
}
Note that a huge advantage of doing this is that it is easy to work with ten million digit integers. You will not be able to do that using scanf to convert the string into an integer.
One way is using a variable to specify which digit to process.
#include <stdio.h>
int main(void)
{
int numToEncrypt;
int delta = 1000; // for 4-digit number
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
while (delta > 0)
{
int digit = (numToEncrypt / delta) % 10;
// do something with digit
digit = (digit + 7)%10;
delta /= 10;
printf("number is: %d \n",digit);
}
}
As this is homework, you could use recursion:
#include <stdio.h>
void print_recursive(int num)
{
// print leading digits
if (num>9)
{
print_recursive(num/10);
}
// print last digits
printf("number is: %d\n", (num+7)%10);
}
int main(void)
{
int number;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf(" %d", &number); // note: You should check the return value!
print_recursive(number);
}
It is not limited to 4 digits.
For a simple program like this, one usually does not bother with a lot of design. However, it is also beneficial to practice software design on simple problems like this, since the knowledge extends to more complicated programs. This is an application of divide and conquer (as a problem solving strategy, not the computer algorithm). The idea being that smaller problems are simpler than larger ones.
In this case, you consider encapsulating the work of "encrypting" to a function, and have the function return the encrypted value. We'll just implement a stub for now, and fill it in later.
int encryptBy7(int input) {
int output = 0;
return output;
}
In addition, we can encapsulate the work of "printing" to a function. And, this is your actual question, if we think about it critically.
void printDigitByDigit(int num, const char *msg) {
printf("stub\n");
}
So your main program would look like:
int main(void) {
int numToEncrypt;
int numEncrypted;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
numEncrypted = encryptBy7(numToEncrypt);
printDigitByDigit(numEncrypted, "number is");
return 0;
}
So, your algorithm to encrypt seems to work, so let's just code that up in a way that it stores it as a number.
int encryptBy7(int input) {
int output = 0;
int pow10 = 1;
/* Original program didn't deal with 0 */
if (input == 0) return 0;
while (input > 0) {
int digit = input % 10;
// do something with digit
digit = (digit + 7)%10;
input /= 10;
// build output
output += digit * pow10;
pow10 *= 10;
}
return output;
}
So, now we get to the meat of your question, which is about how to print out the digits starting with the most significant digit. If we see how we built up the output in the previous function, we can reverse the same process of looking at the powers of 10 to find the most significant digit, and then work backwards from there.
void printDigitByDigit(int input, const char *msg) {
int pow10 = 1;
int x = input;
// Find the position of the most significant digit
while (x > 10) {
pow10 *= 10;
x /= 10;
}
// Divide by the input appropriate power of 10 to
// find and print the corresponding digit
while (pow10 > 0) {
int digit = (input / pow10) % 10;
printf("%s: %d\n", msg, digit);
pow10 /= 10;
}
}
Of course, you are free to choose to try to do this as a single program inside of main as you had originally attempted, and the result would probably be a shorter program. I'll leave that as an exercise. However, I would argue that breaking up the program into tasks will provide you more benefit in the long run, and itself is a problem solving tool. Each function becomes easier to think about, and thus an easier problem to solve.
I am a beginner in a C programming class, and our assignment for the third chapter of our textbook was to create an encode/decode program that takes in four digits from user input and rearranges them depending on whether or not the user wants them to be either encoded or decoded. I am also having trouble with getting the program to do both decoding and encoding in one file. However, when I fire up the program, whenever I select encode and type in my four digits, the program not only gives me a massive number that should only be four digits as the encoded result. It also gives me the "press any key to continue" prompt, signifying the end of the program, instead of starting over completely and going back to where it asks the user to either decode or encode.
The output is also attached.
I've tried looking around and changing some of the variables from int to double, as well as checking my math... I'm not 100% sure why the encryption and decryption aren't limited to anything besides four digits.
As for getting the program to start over, I've tried using a do-while loop, but it still didn't seem to work, so I deleted it.. I also tried using another if statement and then using break, but it was marked as an error.
The assignment says that, "each digit should be encrypted by adding 7 and taking the remainder after division by 10; after encrypting each digit, swap the first and third digits, and then swap the second and fourth digits. Decryption should reverse the process. Program must do encode and decode in one file.
Here is the example that my instructor posted for this, this is what the output should look like.
Enter a four digit number: 1234
Encoded Digits: 0189
Continue (1) Exit (0): 1
Encode (1) Decode (2): 2
Enter a four digit number: 0189
Decoded Digits: 1234
Continue (1) Exit (0): 0
Here is my code:
///Compiler used: Microsoft Visual Studio
///Language: C
#include <string>
#pragma warning(disable: 4996)
#include <math.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int Encodechoice = 1;
int inputdigit1 = 0;
int Decodechoice = 2;
int UserChoice = 0;
int ContinueChoice = 0;
int UserDigit1 = 0;
int UserDigit2 = 0;
int UserDigit3 = 0;
int UserDigit4 = 0;
{
printf("(1) Encode, (2) Decode\n");
printf("Make your selection.\n");//Asks user to make selection
scanf_s("%d", &UserChoice);
if (UserChoice == 1)//begin encryption
{
UserDigit1 = 0;
UserDigit2 = 0;
UserDigit3 = 0;
UserDigit4 = 0;
printf("Encode: Enter FOUR integers.\n");
scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
int EncodedIntegers1 = (UserDigit1 + 7) % 10;
int EncodedIntegers2 = (UserDigit2 + 7) % 10;
int EncodedIntegers3 = (UserDigit3 + 7) % 10;
int EncodedIntegers4 = (UserDigit4 + 7) % 10;
printf("Encoded result:\n");
printf("%d", "%d", "%d", "%d\n", EncodedIntegers3, &EncodedIntegers4, &EncodedIntegers1, &EncodedIntegers2); /// swap order of integers
}///end if
if (UserChoice == 2)///begin decryption
{
UserDigit1 = 0;
UserDigit2 = 0;
UserDigit3 = 0;
UserDigit4 = 0;
printf("Decode: Enter FOUR integers.\n");
scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
int DecodedIntegers1 = (UserDigit1 - 7) * 10;
int DecodedIntegers2 = (UserDigit2 - 7) * 10;
int DecodedIntegers3 = (UserDigit3 - 7) * 10;
int DecodedIntegers4 = (UserDigit4 - 7) * 10;
printf("Decoded result:\n");
printf("%d", "%d", "%d", "%d\n", DecodedIntegers1, &DecodedIntegers2, &DecodedIntegers3, &DecodedIntegers4); /// keep order the same to decrypt
}///end if
system("pause");
return 0;
}
}
Output:
Make your selection.
1
Encode: Enter FOUR integers.
1234
Encoded result:
11893608 Continue? (1) Yes, (0) No
Make your selection.
1
Press any key to continue . . .```
You scanf is wrong. I would rather do this
char UserInputNumber[5];
printf("Encode: Enter FOUR integers.\n");
scanf("%s", UserInputNumber);
// optional error checking the input: length is 4? All char is a number?
UserDigit1 = (UserInputNumber[0] - '0');
UserDigit2 = (UserInputNumber[1] - '0');
UserDigit3 = (UserInputNumber[2] - '0');
UserDigit4 = (UserInputNumber[3] - '0');
Also your printf should look like this:
printf("%d%d%d%d\n", EncodedIntegers3, EncodedIntegers4, EncodedIntegers1, EncodedIntegers2);
With the & you tried to print their memory address not their value, but also your format string was wrong too.
The easiest way is probably work directly on a string consisting of the four digits:
char d[5], e[5] = { 0 };
scanf("%4s", d)
This is for encoding:
for (int i = 0; i < 4; i++) e[(i+2)%4]=(d[i]-41)%10+'0';
For decoding, you have to change the magic 41 to 45. The result is in e.
I have been instructed to write a code to will perform a function and then call another function to print the results to a file. I used the "a" operator because the print function is called multiple times.
Whenever I run the function using printf, everything prints to the console perfectly. When I use fprintf, the last this to be printed ends up on the beginning of the text file.
Any idea why this may be happening and what I could do to fix it?
Code for my print function is below:
void WriteNos(int Case, int dec, long float Float) {
Output = fopen("cp2.out", "a"); /*initialize output file ins append mode so that file is not over written at every call function*/
int j; /* initialize j counter for printing Float to dec*/
switch (Case)
{
case 1:/* called from ConvertDecInt2binary */
{fprintf(Output,"The binary representation of decimal \t \t %d is %s\n", dec, DectoBinarray); } /*dec in this case is the decimal integer used for ConvertDecInt2binary. DectoBinarray is a global array*/
return;
case 2: /*Called from ConverBinary2Dec*/
{fprintf(Output,"The decimal representation of binary \t%s is\t%d\n", BinarrayPrint, dec); }/*dec in this case is a decimal integer calculated in ConvertBinary2Decimal, BinarrayPrint is a global array*/
return;
case 3:/*Called from ConvertFloatInt2Binary*/
{ fprintf(Output, "The binary representation of decimal \t \t%.6lf is %c ", Float, FloattoBinary[0]); /*Float is the Flot point number used in converDecFloat2binarynFloatBinary is a global array whole 0 location is the sign bit*/
for (j = 1; j <= 8; j++)
{
fprintf(Output,"%c", FloattoBinary[j]); /*print the exponant in binary form*/
}
fprintf(Output, " ");
for (j = 31; j >= 9; j--)/*print the mantissa in binarry form*/
{
fprintf(Output,"%c", FloattoBinary[j]);
}
fprintf(Output,"\n"); /*Print a new line */
return;
}
case 4:
{
fprintf( Output,"\n");
return;
}
}
}
Use fclosebefore returning from function.
Also check return value of fopen every time.
Or I think Output is a global variable( No local declaration found). So no need to open and close every time.
Sample pattern is given,
input : 16
output: 16 11 6 1 -4 1 6 11 16
If the input is 10, then program should print output as
10 5 0 5 10
Note: The above sequences decrement/increment by 5.
The challenge is to not declare any variables or loops. use only recursion.
I have tried with the following code.
void sequence(int input, int base){
input = input - (input > 0?5:-5); //main execution
printf("input:%d\n",input);
if(input == base)return;
sequence(input,base);
}
//for eg. input and base(initial Value) is 16. The above method recurse itself until input = base.
I can print upto this sequence (in Bold)
16 11 6 1 -4 1 6 11 16
How to complete the sequence. In the above method, in main execution line, i need to check condition as input = input - (input < 0?5:-5); to print the remaining sequence. But i am not sure how can i do this without any variables or loops. Is there any algorithm available or any other better solution.
Some example code to my comment, which would match if it doesn't have to be strictly left- or right-recursive:
void sequence(int n)
{
printf("%d ", n);
if (n > 0)
{
sequence(n-5);
printf("%d ", n);
}
}
Further notes:
1.) This seems to be about functional programming, where a key concept is that you can never assign a variable ... see how it is avoided here. (Strictly speaking, it's not functional because of the printf side effects)
2.) It's not strictly left- or right-recursive (meaning the recursion happens in the middle of evaluation), so it can't be easily transformed to something iterative.
It seems that the recursion should stop when it reaches 0 or below. So try this condition in you recursive function (reduced to only one argument):
void sequence(input) {
// print input
if (input > 0) {
// recursive call
sequence(input);
}
// print input again (sometimes...)
}
Update: Let's talks about Symmetry
For the sake of symmetry, also the reverse version of Felix's solution can be used
void sequence(int n)
{
if (n > 0) {
printf("%d ", n);
sequence(n-5);
}
printf("%d ", n);
}
Both feature a kind of asymmetry that seems not to fit to the palindromic structure of the problem, and there is another problem: the blemish of a trailing space. So let's introduce to you a obvious solution that deals with these tiny(?) flaws:
void sequence(int n)
{
if (n > 0) {
printf("%d ", n); sequence(n-5); printf(" %d", n);
} else {
printf("%d", n);
}
}
Use two different functions to cout up and down:
void down(int input, int base) {
printf("input:%d\n",input);
if(input > 0) down(input - 5, base);
else up(input + 5, base);
}
void up(int input, int base) {
printf("input:%d\n",input);
if(input == base) return;
up(input + 5, base);
}
Start the calculation by calling down.
Live Demo
The base case of your recursive code seems wrong. I think your code goes into infinite recursion the way it is. You can use a flag to achieve your sequence:
void sequence(int input, int base){
static int flag = 0;
//input = input - (input > 0?5:-5); //main execution, wrong
printf("input:%d\n",input);
input -= (flag == 0)?5:-5; //use flag for base case of sequence
if(input <= 0)
flag = 1;
if(input == base){
printf("input:%d\n",input);
return;
}
sequence(input,base);
}
#include <stdio.h>
using namespace std;
void printSequence(int input) {
printf("%d ", input);
if (input <= 0)
return;
printSequence(input - 5);
printf("%d ", input);
}
int main ()
{
int input = 0;
scanf("%d", &input);
printSequence(input);
return 0;
}