Using _getch() in a for loop - c

I'm trying to make a binary to decimal converter and I wanted to use _getch() so the user doesn't have to press enter every number he enters, but…
#include <stdio.h>
#include <conio.h>
int main() {
int intnum[8], i = 0, ris;
char charnum;
for (i = 0; i < 8; i++) {
charnum = _getch();
printf("%c", charnum);
intnum[i] = (charnum - '0');
}
ris = intnum[8] * 2^0;
for (i = 7; i > 0; i--) {
ris += (intnum[i] * 2 ^ j);
j++;
}
printf("%d", ris);
getchar();
}
…but the problem is that when they enter in the loop the user can enter only 4 numbers and not 8; can you explain why?

After debugging of code,following changes you should do with your code..
declare int j = 0.
Also instead of ris = intnum[8] * 2^0 use ris = intnum[7] * 1 since array index start with 0 in c.
Also do same for for(i = 6;i >= 0;i--) and ris += intnum[i] * 2<<j with left shift operator(<<).
Basically use of getch() is unnecessary and makes your program
non-portable,but if you want to use it,then I will suggest you to use
below codes..
For linux,use this code..
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int getch (void){
int ch;
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
int main() {
int intnum[8], i = 0, ris,j = 0;
char charnum;
for (i = 0; i < 8; i++) {
charnum = getch();
intnum[i] = (charnum-'0');
}
ris = intnum[7] * 1;
for (i = 6; i >= 0; i--) {
ris += (intnum[i] * 2<<j);
j++;
}
printf("%d", ris);
getchar();
}
For windows,use this code..
#include <stdio.h>
#include <conio.h>
int main() {
int intnum[8], i = 0, ris,j = 0;
char charnum;
for (i = 0; i < 8; i++) {
charnum = getch();
intnum[i] = (charnum-'0');
}
ris = intnum[7] * 1;
for (i = 6; i >= 0; i--) {
ris += (intnum[i] * 2<<j);
j++;
}
printf("%d", ris);
getchar();
}

Related

Program doesn't produce any output

I tried writing a code that gets up to 10 words, and if everything is a pangram it prints that it's a pangram. The thing is about this code is that even if the user enters 7 words that are a pangram, the for loop needs to stop and print that the sentence formed out of this words is indeed a pangram.
I wrote the code and it compiles just fine, the problem is the exe file, I try to execute it and it doesn't work. Can you guys help me?
my code:
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 10
#define MAX_WORD_LENGTH 10
#define TEN 10
int main(void)
{
int i = 0;
int j = 0;
int k = 0;
int p = 0;
int flag = 0;
int counter = 0;
char words[MAX_WORDS][MAX_WORD_LENGTH] = { 0 };
for(i = 0; i < TEN; i++)
{
flag = 0;
fgets(words[i], MAX_WORDS, stdin);
//inputs the name
if(words[i][strlen(words[i])-1] == '\n')
{
words[i][strlen(words[i])-1] = 0;
}
//makes sure there is no problem
for(p = 0; p <= i; p++)
{
for(k = 97; k < 123; k++)
{
for(j = 0; j < strlen(words[i]); j++)
{
if(k == words[i][j])
{
flag = 1;
}
}
}
}
if(flag)
{
counter++;
}
if(counter == 26)
{
i = 10;
printf("It's a pangram?\nYes!");
}
}
return 0;
}
As pointed out in the comments, you should try to debug the code yourself first.
For starters, I would stick a printf at the beginning of the for(i = 0; i < TEN; i++) loop to ensure the code is actually being executed. Of course you can put it in every single other loop to get some idea where the code is going.
One mistake I'm noticing is in here: fgets(words[i], MAX_WORDS, stdin);. The second parameter to fgets is expected to be the max word length and not the maximum number of words.
Here is what missing in your code. You forgot to add the break statement after setting the flag. And incrementing the counter should be part of words iterating for loop.
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 10
#define MAX_WORD_LENGTH 10
#define TEN 10
int main(void)
{
int i = 0;
int j = 0;
int k = 0;
int p = 0;
int flag = 0;
int counter = 0;
char words[MAX_WORDS][MAX_WORD_LENGTH] = { 0 };
for(i = 0; i < TEN; i++)
{
flag = 0;
fgets(words[i], MAX_WORDS, stdin);
//inputs the name
if(words[i][strlen(words[i])-1] == '\n')
{
words[i][strlen(words[i])-1] = 0;
}
//makes sure there is no problem
for(p = 0; p <= i; p++)
{
for(k = 97; k < 123; k++)
{
for(j = 0; j < strlen(words[i]); j++)
{
if(k == words[p][j])
{
flag = 1;
break;
}
}
if(flag)
{
counter++;
}
}
}
if(counter == 26)
{
i = 10;
printf("It's a pangram?\nYes!");
}
}
return 0;
}

How to convert to binary as string in code C

I am trying to convert int to binary as string but I can not.
Please help me. How to convert integer to binary, please tell me.
Input: 32
Output: 00100000
My code:
#include <stdio.h>
#include <string.h>
char converttobinary(int n)
{
int i;
int a[8];
char op;
for (i = 0; i < 8; i++)
{
a[i] = n % 2;
n = (n - a[i]) / 2;
}
for (i = 7; i >= 0; i--)
{
op = strcat(op, a[i]);
}
return op;
}
int main()
{
int n;
char str;
n = 254;
str = converttobinary(n);
printf("%c", str);
return 0;
}
I have tried to modify your solution with minimal changes to make it work. There are elegant solutions to convert Integer to Binary for example using shift operators.
One of the main issue in the code was you were using character instead of character array.
i.e char str; instead of char str[SIZE];
Also you were performing string operations on a single character. Additionally, iostream header file is for C++.
There is room for lot of improvements in the solution posted below (I only made your code work with minimal changes).
My suggestion is to make your C basics strong and approach this problem again.
#include <stdio.h>
#include <string.h>
void converttobinary(int n, char *op)
{
int i;
int a[8];
for (i = 0; i < 8; i++)
{
a[i] = n % 2;
n = (n - a[i]) / 2;
}
for (i = 7; i >= 0; i--)
{
op[i]=a[i];
}
}
int main()
{
int n,i;
char str[8];
n = 8;
converttobinary(n,str);
for (i = 7; i >= 0; i--)
{
printf(" %d ",str[i]);
}
return 0;
}
char *rev(char *str)
{
char *end = str + strlen(str) - 1;
char *saved = str;
while(end > str)
{
int tmp = *str;
*str++ = *end;
*end-- = tmp;
}
return saved;
}
char *tobin(char *buff, unsigned long long data)
{
char *saved = buff;
while(data)
{
*buff++ = (data & 1) + '0';
data >>= 1;
}
*buff = 0;
return rev(saved);
}
int main()
{
char x[128];
unsigned long long z = 0x103;
printf("%llu is 0b%s\n", z, tobin(x, z));
return 0;
}
I modify your code a little bit to make what you want,
the result of this code with
n = 10
is
00001010
In this code i shift the bits n positions of the imput and compare if there is 1 or 0 in this position and write a '1' if there is a 1 or a '0' if we have a 0.
#include <stdio.h>
void converttobinary(int n, char op[8]){
int auxiliar = n;
int i;
for (i = 0; i < 8; i++) {
auxiliar = auxiliar >> i;
if (auxiliar & 1 == 1){
op[7-i] = '1';
} else{
op[7-i] = '0';
}
auxiliar = n;
}
}
int main (void){
int n = 10;
int i;
char op[8];
converttobinary(n, op);
for(i = 7; i > -1; i--){
printf("%c",op[i]);
}
return 0;
}

Continued Power Function Message

I keep getting the error message that my I have an undefined reference to the power function, but I'm not really sure where that is occurring or why my code is coming up with that error because I have used to power function before in this way. If anyone could help me figure out why it isn't working now I would really appreciate it.
#include "stdio.h"
#include "string.h" //Needed for strlen()
#include "math.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
#define NUMBER_TWO 2
#define NUMBER_ONE 1
#define TERMINATOR '\0'
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
last_index_of == i;
}
}
return last_index_of;
}
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (i < 1) {
out_str[i] = in_str[start] + in_str[end-1];
i++;
}
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH +1]; // +1 for '\0'
int number;
double exponent;
char output[MAX_BITS];
int fraction;
sub_string(input, output, 0, TERMINATOR);
//Input from the user
printf("Enter a floating point value in binary: ");
scanf("%s", input);
//Calculates the Decimal Part
for (int i = 0; i < last_index_of(input, TERMINATOR) ; i++) {
number = number + number + input[i];
}
printf("%d", number);
exponent = -1;
//Calculates the Fractional Part
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
if (j == last_index_of) {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d/n", fraction);
}
else {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d + ", fraction);
exponent--;
}
}
return 0;
}
Some problems:
you need -lm option to linker to tell it where to find pow function
last_index_of is not correctly written, you use the function name as an internal variable, you can correct it this way:
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
ret = i;
}
}
return ret;
}
Note that you can replace your last_index_of() function by strlen()
as pointed in comment, sub_string() is not functionnal. A corrected version could be:
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (start != end) {
/* warning, bounds are still not tested...*/
out_str[i++] = in_str[start++];
}
out_str[i] = '\0'
}
Instead of calling last_index_of() in your exist for loop condition, you should take its value to re-use it:
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
/* Error here: will never be TRUE */
if (j == last_index_of) {
/* ... */
}
else {
/* ... */
}
}
would become:
int last_index = last_index_of(input, TERMINATOR);
for (int j = 0; j < last_index; j++) {
if (j == last_index) {
/* ... */
}
else {
/* ... */
}
}
Another problem, you use number variable without initializing it, you should write int number = 0 instead of int number;
After that, there is also a problem with your logic.
You have some idea of what you want to do, but it is not clear in your code.
It seems that you want
the user to input some string in the form 10010.100111
to split this string into two parts 10010 and 100111
to convert the first part into integer part 10010 -> 18
to convert the second part into fractional part 100111 -> 0.609...
This decomposition may lead you to write this kind of code:
#include "stdio.h"
#include "string.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch)
{
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if (in_str[i] == ch) {
ret = i;
}
}
return ret;
}
void sub_string(char in_str[], char out_str[], int start, int end)
{
int i = 0;
while (start != end) {
/* warning, bounds are still not tested... */
out_str[i++] = in_str[start++];
}
out_str[i] = '\0';
}
void split(char *input, char *first, char *second)
{
int idx = last_index_of(input, '.');
sub_string(input, first, 0, idx);
sub_string(input, second, idx + 1, strlen(input));
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH + 1]; // +1 for '\0'
char first[MAX_BITS];
char second[MAX_BITS];
/* Input from the user */
printf("Enter a floating point value in binary: ");
scanf("%s", input);
/* split integer and fractionnal parts */
split(input, first, second);
/* decode integer part */
printf("integer part:\n");
for (int i = strlen(first) - 1, j = 1; i > -1; --i, j <<= 1) {
if (first[i] == '1') {
printf("%d ", j);
}
}
/* decode frac part */
printf("\nfractionnal part:\n");
for (int i = 0; i < strlen(second); ++i) {
if (second[i] == '1') {
printf("1/%d ", 2 << i);
}
}
return 0;
}

Pic programming Using C counter up and down

#include <xc.h>
#include "LCD.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int a; int x = 0; char s[10000];
TRISD = 0x00; TRISB = 0x03;
Lcd_Start();
while(1)
{
Lcd_Clear();Lcd_Set_Cursor(1,1);
int x = 0;
if (PORTBbits.RB0==1)
{
Lcd_Clear();
x += 1;
Lcd_Print_String("Current Number");
Lcd_Set_Cursor(2,1);
Lcd_Print_String(x)
}
else if(PORTBbits.RB1==1)
{
Lcd_Clear();
x += -1;
Lcd_Print_String("Current Number");
Lcd_Set_Cursor(2,1);
Lcd_Print_String(x);
}
}
return 0;
}
This is Lcd_Print_String:
void Lcd_Print_Char(char data) //Send 8-bits through 4-bit mode
{
char Lower_Nibble,Upper_Nibble;
Lower_Nibble = data&0x0F;
Upper_Nibble = data&0xF0;
RS = 1; // => RS = 1
Lcd_SetBit(Upper_Nibble>>4); //Send upper half by shifting by 4
EN = 1;
for (int i=2130483; i<=0; i--) NOP();
EN = 0;
Lcd_SetBit(Lower_Nibble); //Send Lower half
EN = 1;
for (int i=2130483; i<=0; i--) NOP();
EN = 0;
}
void Lcd_Print_String(char *a)
{
int i;
for (i=0;a[i]!='\0';i++)
Lcd_Print_Char(a[i]);
}
I want to display the value of x on the screen, my Lcd_pring_String only takes string type. Is there a way convert x to a string so I can display on LCD?
I am using PIC16f877A, LCD(lm016) and two switches to take signal for +1, -1.
You probably want to use sprintf which is declared in <stdio.h>:
char buffer[20]; // char buffer
sprintf(buffer, "%d", x); // "print" x into the char buffer
Lcd_Print_String(buffer); // send buffer contents to LCD
or instead of sprintf use snprintf if available:
snprintf(buffer, sizeof buffer, "%d", x);
I'd make a new function Lcd_Print_Number out of this.

convert each digit of a decimal number to correcsponding binary

I need to convert the string "12345678" to the value 00010010001101000101011001111000 (the value in binary only without the zeroes on the left).
So I have written this code in c, the problem is that when I run it does nothing, just waits like there is an error until I stop it manually.
Any ideas?
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[4], result[4*strlen(string)];
for (i=0; i<strlen(string); i++) {
num = atoi(string[i]);
while (num != 0) {
arr[j++] = num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = 0;
tmp--;
}
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k++] = arr[j--];
}
j = 0;
tmp = 4;
}
printf("The result is: \n");
for (i=0; i<4*strlen(result); i++) {
printf("%d",result[i]);
}
printf("\n");
}
int main() {
char c[8] = "12345678";
reduce(c);
return 0;
}
Lots of small errors in your code, which makes it hard to pin-point a single error. Main problem seems to be you are confusing binary numbers (0, 1) with ASCII digits ("0", "1") and are mis-using string functions.
as mentioned elsewhere, char c[8] = .. is wrong.
atoi(string[i]) cannot work; it expects a string, not a char. Use `num = string[i]-'0';
arr[..] gets the value 'num%2, that is, a numerical value. Better to use '0'+num%2 so it's a character string.
you increment k in result[k++] inside a loop that already increments k
add result[k] = 0; at the end before printing, so strlen works correctly
4*strlen(result) is way too much -- the strlen is what it is.
you might as well do a simple printf("%s\n", result);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[5], result[4*strlen(string)+1];
for (i=0; i<strlen(string); i++) {
num = string[i]-'0';
while (num != 0) {
arr[j++] = '0'+num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = '0';
tmp--;
}
arr[j] = 0;
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k] = arr[j--];
}
j = 0;
tmp = 4;
}
result[k] = 0;
printf("The result is: \n");
for (i=0; i<strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
}
int main() {
char c[] = "12345678";
reduce(c);
return 0;
}
.. resulting in
The result is:
00010010001101000101011001111000
It seems from your example that the conversion you are attempting is to binary coded decimal rather than binary. That being the case your solution is somewhat over-complicated; you simply need to convert each digit to its integer value then translate the bit pattern to ASCII 1's and 0's.
#include <stdio.h>
void reduce( const char* c )
{
for( int d = 0; c[d] != 0; d++ )
{
int ci = c[d] - '0' ;
for( unsigned mask = 0x8; mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
}
On the other hand if you did intend a conversion to binary (rather than BCD), then if the entire string is converted to an integer, you can directly translate the bit pattern to ASCII 1's and 0's as follows:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void reduce( const char* c )
{
unsigned ci = (unsigned)atoi( c ) ;
static const int BITS = sizeof(ci) * CHAR_BIT ;
for( unsigned mask = 0x01 << (BITS - 1); mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
In your main(), do either
char c[ ] = "12345678";
or
char c[9] = "12345678";
if you want to use c as a string. Otherwise, it does not have enough space to store the terminating null character.
Here, I took the liberty to modify the code accordingly to work for you. Check the below code. Hope it's self-explanatoty.
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, count = 0; //count added, tmp removed
char arr[4], result[ (4*strlen(string) )+ 1], c; //1 more byte space to hold null
for (i=0; i<strlen(string); i++) {
c = string[i];
count = 4;
while (count != 0) { //constant iteration 4 times baed on 9 = 1001
arr[j++] = '0' + (c%2); //to store ASCII 0 or 1 [48/ 49]
c = c/2;
count--;
}
/* //not required
while (tmp >= 0) {
arr[j++] = 0;
tmp--;
}
*/
j--;
for (k=(i*4); k<((i*4) +4); k++) {
result[k] = arr[j--];
}
j = 0;
memset (arr, 0, sizeof(arr));
}
result[k] = 0;
printf("The result is: %s\n", result); //why to loop when we've added the terminating null? print directly.
/*
for (i=0; i< strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
*/
}
int main() {
char c[ ] = "12345678";
reduce(c);
return 0;
}
Output:
[sourav#broadsword temp]$ ./a.out
The result is: 00010010001101000101011001111000
Convert your string to an integer using int num = atoi(c).
Then do
int binary[50];
int q = num,i=0;
while(q != 0)
{
binary[i++] = q%2;
q = q/2;
}
Printing your binary array is reverse order will have your binary equivalent.
Full program:
#include<stdio.h>
int main(){
char c[100];
int num,q;
int binary[100],i=0,j;
scanf("%d",c);
num = atoi(c);
q = num;
while(q!=0){
binary[i++]= q % 2;
q = q / 2;
}
for(j = i -1 ;j>= 0;j--)
printf("%d",binary[j]);
return 0;
}
You can use the below reduce function.
void reduce(char string[])
{
unsigned int in = atoi(string) ;
int i = 0, result[32],k,j;
while (in > 0) {
j = in % 10;
k = 0;
while (j > 0) {
result[i++] = j % 2;
j = j >> 1;
k++;
}
while (k < 4) {
result[i++] = 0;
k++;
}
in = in/10;
}
printf("Result\n");
for(--i;i >= 0; i--) {
printf("%d", result[i]);
}
printf("\n");
}
For 12345678
the output would be 00010010001101000101011001111000, where each character is printed in its binary format.
It might need some adjustments, but it does the job as it is.
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int i;
int n;
char *str = "12345678";
const int bit = 1 << (sizeof(n)*8 - 1);
n = atoi(str);
for(i=0; i < sizeof(n)*8 ; i++, n <<= 1)
n&bit ? printf("1") : printf("0");
return 0;
}

Resources