Recursive Function of Characters To Binary (ASCII) - c

I bought a Programming book at a yard sale for $2 because I've always wanted to learn how to code but don't have the money and resources for school. I've gotten through the first few chapters just fine, but I've also had the solutions to the problems I was working on. But the chapter is missing a few of the pages after the chapter summary when they start listing problems. I was wondering if you guys could help me out.
Here is the problem. Note: Needs to use a recursive function.
#include <stdio.h>
#include <stdlib.h>
void binaryPrinter(int value, int *numberOfOnes);
void print(char c);
//You do not need to modify any code in main
int main()
{
char value;
int result = 1;
while(result != EOF)
{
result = scanf("%c",&value);
if(result != EOF && value != '\n')
{
print(value);
}
}
}
//#hint: This is called from main, this function calls binaryPrinter
void print(char c)
{
}
//#hint: this function is only called from print
void binaryPrinter(int value, int *numberOfOnes)
{
}

void print(char c)
{
int n = CHAR_BIT;
binaryPrinter((unsigned char)c, &n);
putchar('\n');
}
void binaryPrinter(int value, int *numberOfOnes)
{
if((*numberOfOnes)--){
binaryPrinter(value >> 1, numberOfOnes);
printf("%d", value & 1);
}
}

Related

Error with the array returning through function

I need to read a word from main function and convert the characters in UCASE if the first character is LCASE and vice versa using the user defined function.I tried ways for returning the array from function but still I am lacking some core ideas. Please debug this program and explain the way it works.
#include <stdio.h>
#include <string.h>
int* low (char str)
{
int i;
for (i=1; i<strlen(str);i++)
{
if(str[i]<91)
{
str[i]=str[i]+32;
}
else
{
}
}
return &str;
}
int* high (char str[50])
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>91)
{
str[i]=str[i]-32;
}
else
{
}
}
return &str;
}
void main()
{
char str[50];
char* strl;
printf("Enter any string....\n");
scanf("%s",str);
if (str[0]<91)
{
*strl=low(str);
}
else
{
*strl=high(str);
}
printf("Converted string is %s.",*strl);
}
There is already a problem here:
So if you are saying this code is perfect and you want us to debug it and explain how (on earth) this works, then here you go.
In function int* low (char str), you have if(str[i]<91). Thats a problem right there. str is a char received as an argument, and hence str[i] is a straight compile-time error.
Another one to deal with is the return statement.
You have a statement:
return &str;
which would return the address of str, which by the way is a char, whereas function low is supposed to return a pointer to an int.
The same is applicable to high function as well.
Suggestion: Leave aside this bad code and get a beginner level C programming book first. Read it and the try some codes out of it.
A few inputs for improvement: (Which you may not comprehend)
change
void main()
to
int main(void)
Why? Refer this legendary post: What should main() return in C and C++?
Secondly, int both functions you are using strlen() in loop which will always return a fixed value. So, instead of
for (i=0; i<strlen(str);i++)
I'd suggest,
size_t strlength = strlen(str);
for (i=0; i < strlength; i++)
You can try the code and method as below:
#include <stdio.h>
#include <string.h>
char* caseConverter (char *str)
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>=65 && str[i]<=90)
{
str[i]=str[i]+32; //To lower case
}
else if((str[i]>=97 && str[i]<=122))
{
str[i]=str[i]-32; //To upper case
}
else
printf("%c is not an alphabet \n",str[i]);
}
return str;
}
void main()
{
char inputStr[50]= "Stubborn";
char* opStr= caseConverter(inputStr);
printf("Converted string is %s",opStr);
}

Stack calculator altering the value of a variable

For my programming class I have to program a calculator that functions with a stack.
Here's the code I made for the stack itself:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
double stk[MAXSIZE]; //Stack array
int top=-1; //Top position in stack
void push(double n);
double pop(void);
void display(void);
/* Add an element to the stack */
void push(double n) {
if (top == (MAXSIZE - 1)) {
printf ("Stack is full\n");
}
else {
//s.top++;
//stk = (double *) malloc(MAXSIZE*sizeof(double));
stk[++top] = n;
}
return;
}
/* Remove and return the top element from the stack */
double pop() {
double num;
if (top == -1) {
printf ("Stack is empty\n");
return (top);
}
else {
num = stk[top--];
printf ("Pop:%f\n", num); //Debugging line
return (num);
}
}
/* Prints all elements in the stack */
void display() {
int i;
if (top == -1) {
printf ("Stack is empty\n");
return;
}
else {
for (i = top; i >= 0; i--) {
printf ("%f\n", stk[i]);
}
}
}
And this is the the calculator (which is in a different file, I'm using makefile to compile):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int isNumber(const char *s);
void insert(double num);
void sum(void);
int main(int argc, char *argv[]) {
int loop = 1;
char input[10];
/* Main Loop */
while (loop == 1) {
printf("> ");
scanf(" %[^\n]", input);
if (isNumber(input)) {
double nu = atof(input);
insert(nu);
}
else if (strcmp(input, "+") == 0)
sum();
else if (strcmp(input, "l") == 0)
list();
else if (strcmp(input, "exit") == 0) //exit
loop = 0;
} //end while
} //end main
int isNumber(const char *s) {
while (*s) {
if((*s<'0' || *s>'9') && *s!='-' && *s!='.')
return 0;
s++;
}
return 1;
}
void insert(double num) {
push(num);
}
/* This function is called when the user enters a '+' instead of a number into the command line. It takes the top two numbers from the stack and adds them together */
void sum() {
double num1, num2, res;
num1 = pop();
num2 = pop();
res = num1+num2;
printf("num1:%f num2:%f sum:%f\n", num1, num2, res); //Debug
}
int list() {
display();
}
The program compiles fine. When I run it I test it by entering a 5 followed by a 6 followed by a + and I get this output:
Pop:6.000000
Pop:4.000000
num1:13.000000 num2:13.000000 sum:26.000000
So apparently the number that the pop() function returns is correct but when assigning it to variables in the calculator function it changes it into a 13 for some reason. It's not always 13, for larger numbers it's higher; entering 500 returns 14, 1000 returns 15, 10000 returns 16 and so on.
I initially made my stack with a array of ints and it actually worked perfectly (it still does if I change all the doubles to ints). Also the stack itself seems to be working fine since the display() function correctly prints all the values the user entered).
I'm really confused as to where the error is coming from and I'm actually thinking of rewriting the whole stack as a linked list instead but I wanted to give this a last shot.
Thanks in advance for your help.
EDIT: I added an #include "Stack.h" (Changed Stack.c to Stack.h) in my calculator file and disposed of the makefile and it now works. I have no idea what was happening originally but I'm just glad it works.
I put all your logic in one file, and add simple main:
int main()
{
push(4.0);
push(3.8);
sum();
return 0;
}
Then compile all as gcc main.c. And it works fine:
Pop:3.800000
Pop:4.000000
num1:3.800000 num2:4.000000 sum:7.800000
Are you sure that you really normally link your project (and break your code to some modules)? Can you put more information about how you compile your version?
P.S. You have all good in program logic
Update
You need to add Stack.h file with the same text:
#include <stdio.h>
#include <stdlib.h>
void push(double n);
double pop(void);
void display(void);
In Stack.c remove this code and add #include "Stack.h" in the first line.
In Main.c only add #include "Stack.h" in the 6 line (just after system #include directives).
Don't change your makefile. It's not required.
With regards,
AJIOB

Coding printf with array of function pointers

I am trying to code the printf function. The problem is that my code is getting very messy and I need some help to try to make it organized and working (hopefully). I have been told that I should use "array of function pointers" so I tried below (ft_print_it) as you can see but I do not know how to how to structure my code so that I can use a big array of function pointer to put every function like int_decimal_octal and friends. Can you help me on that? Where can I call them from?
Also, I realized the little function below (cast_in_short) is giving me the same result as printf if I write the output with my ft_putnbr. My second question is thus: Can I make my printf work with little functions like this? Thank you so much.
int cast_in_short(int truc)
{
truc = (short)truc;
return (truc);
}
/*
here in the main I noticed that I get the same behaviour
between my putnbr and printf thanks to my little function
cast_in_short. This is the kind of function I want to use
and put into an array of pointer of functions in order
to make my printf work
*/
int main()
{
int n = 32769;
n = cast_in_short(n);
ft_putnbr(n);
printf("\n");
return (0);
}
/* function to launch ft_print_it */
int ft_print_str_spec(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putstr(va_arg(ap, char *));
else
{
ft_nbzero(ap, flag, 0);
ft_putstr(va_arg(ap, char *));
}
return (1);
}
int ft_print_oct(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putnbr(decimal_octal((va_arg(ap, int))));
else
{
ft_nbzero(ap, flag, 1);
ft_putnbr(decimal_octal((va_arg(ap, int))));
}
return (1);
}
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
char *ft_strjoin2(char const *s1, char const c);
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
int decimal_octal(int n) /* Function to convert decimal to octal */
{
int rem;
int i;
int octal;
i = 1;
octal = 0;
while (n != 0)
{
rem = n % 8;
n /= 8;
octal += rem * i;
i *= 10;
}
return (octal);
}
I think the best way to organize your code to avoid the function like your "flag_code" is to use an array of structure. With structure that contain a char (corresponding to the flag) and a function pointer.
For example :
typedef struct fptr
{
char op;
int (*ptr)(va_list);
} fptr;
And instatiate it like that (with { 'flag', name of the corresponding function} ) :
fptr fptrs[]=
{
{ 's', ft_print_nb_spec },
{ 'S', ft_print_nb_up },
{ 0, NULL }
};
Then when you know have char after the % (the flag) you can do something like this :
int i = -1;
while (fptrs[++i].op != flag && fptrs[i].op != 0);
if (fptrs[i].op != 0)
{
fptrs[i].ptr();
}
For exemple if flag = 'S' the while loop will stop when i = 1 and when you call fptrs[1].ptr() you will call the corresponding function in the structure.
I think instead of making your code messy by using function pointers, because in the end you cannot specialize printf function without providing the format, in C there is no function overloading or template functions. My suggestion is to special printf function by type.
// print seperator
void p (int end)
{ printf(end?"\n":" "); }
// print decimal
void pi (long long n)
{ printf("%lld",n); }
// print unsigned
void pu (unsigned long long n)
{ printf("%llu",n); }
// print floating point
void pf (double n)
{ printf("%g",n); }
// print char
void pc (char n)
{ printf("%c",n); }
// print string
void ps (char* n)
{ printf("%s",n); }
Test try here
pi(999),p(0),pf(3.16),p(0),ps("test"),p(1);
Output
999 3.16 test
Another option
In theory you can define polymorphic print function in a struct, in case you can do something like this. I haven't tested this yet.
struct Node
{
enum NodeType {Long,Double,Char,String} type;
union {long l,double d,char c,char* s};
};
void p(Node* n)
{
switch (n->type)
{
case Node::NodeType::Long: printf("%ld", n->l);
case Node::NodeType::Double: printf("%g",n->d);
case Node::NodeType::Char: printf("%c",n->c);
case Node::NodeType::String: printf("%s",n->s);
}
}

Calculate with 2 functions

I am a Beginner in Functions.I wanna integrate that Functions in my main program. The program should scan a int number and then square it(sum=b*b). Then the program should output the result.
#include <stdio.h>
#include <stdlib.h>
void funktion(int);
void out(int);
int main(int)
{
int sum,b,v,w,z;
{
funktion();
calculator();
out();
printf("%i",sum);
}
return 0;
}
void funktion(int v)
{
printf("Enter any number that is to be squared!");
}
void calculator(int w) //calculate b*b
{
scanf("%i",&b);
sum=b*b;
}
void out(int z)
{
printf("Sum:");
}
Please give me some tips. ;)
Thx & Best regards!
Are you looking for this kind of solution: i just made little changes. you may need to do some initializing things if u gonna use this code
#include <stdio.h>
#include <stdlib.h>
void funktion(int);
void out(int);
int main()
{
int sum,b;
{
printf("Enter any number that is to be squared!");
scanf("%i",&b);
sum = funktion(b);
out(sum);
}
return 0;
}
int funktion(int b)
{
return b*b;
}
void out(int sum)
{
printf("Sum:%d",sum);
}
void funktion(int);
void out(int);
These two functions need not contain any arguments as you declared to be int's, because you are not performing any computation on sum, since they are just prints inside those functions.
So make them as,
void funktion(void);
void out(void);
and call those routines as,
funktion();
out();
void funktion(int)
{
printf("Enter any number that is to be squared!");
}
void out(int)
{
printf("Sum:");
}
to call these functions you are passing some value so you receive them with parameters.
void funktion(int a)
{
printf("Enter any number that is to be squared!");
}
void out(int b)
{
printf("Sum:");
}
You can make use of the passed value in functions using these variables, a nd b in corresponding functions.
If you dont want to access those passed values in the called functins then you dont need to pass the value. So change the functions to receive nothing, it can be
#include <stdio.h>
#include <stdlib.h>
void funktion();
void out();
int main()
{
int sum,b;
{
funktion();
scanf("%i",&b);
sum=b*b;
out();
printf("%i",sum);
}
return 0;
}
void funktion()
{
printf("Enter any number that is to be squared!");
}
void out()
{
printf("Sum:");
}
make the call to function without passing arguments. you can even specify void as type to indicate that function doesn't take any parameters.
To calculate in other function and return the value use return statement.
int calculator() //calculate b*b
{
scanf("%i",&b);
sum=b*b;
return sum;
}
change the function call statement to,
sum=calculator();

The showbits() function

While reading a book called "Let us C" I read that a function showbit() exists which can show you the bits of the number. There wasn't any special header file mentioned for it. Searched for it on the internet and didn't found anything useful. Is there such a function? I want this to print the binary of decimal numbers. Else please give me a replacement function. Thanks
All integers are actually in binary in your computer. Its just that it is turned into a string that is the decimal representation of that value when you try to print it using printf and "%d". If you want to know what it looks like in some other base (e.g. base 2 or binary), you either have to provide the proper printf format string if it exists (e.g. "%x" for hex) or just build that string yourself and print it out.
Here is some code that can build the string representation of an integer in any base in [2,36].
#include <stdio.h>
#include <string.h>
char digits[]="01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void reverse(char* start, char* end)
{
for(end--;start<end;start++,end--)
{
char t=*start;
*start=*end;
*end=t;
}
}
int base_change(int n, int base,char* buffer)
{
int pos=0;
if (base>strlen(digits))
return -1;
while(n)
{
buffer[pos]=digits[n%base];
n/=base;
pos++;
}
buffer[pos]='\0';
reverse(buffer,buffer+pos);
return 0;
}
int main()
{
char buffer[32];
int conv=base_change(1024,2,buffer);
if (conv==0) printf("%s\n",buffer);
return 0;
}
You can also try this snippet which uses bit-shifting:
EDIT: (I've made it more portable)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BITS_IN_BYTE 8
#define INTEGRAL_TYPE unsigned int
void showBits(INTEGRAL_TYPE x) {
int i;
static int intSizeInBits = sizeof(INTEGRAL_TYPE) * BITS_IN_BYTE;
static char symbol[2] = {'0','1'};
char * binary = (char*) malloc(intSizeInBits + 1);
memset(binary, 0, intSizeInBits + 1);
for (i=0; i< intSizeInBits; i++) {
binary[intSizeInBits-i-1] = symbol[(x>>i) & 0x01];
}
printf("%s\n", binary);
free(binary);
}
int main() {
showBits(8698513);
return 0;
}
HTH!
This is a very simple solution for printing the bits of an integer
int value = 14;
int n;
for (n=8*sizeof(int)-1;n>=0;n--) {
printf("%d",(value >>n)&1);
}
The book "Let Us C" doesn't define it as a built-in function. The showbits() function is defined in later part of the book as a complete user defined function as I personally went through it. This answer is to anyone who haven't reached that later part of the book and are stuck at the first appearance of the function in the book.
you need to look here
#downvoter It works fine in c also. You just need to reformat your code in c-style.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char buffer[20];
int i = 3445;
_itoa( i, buffer, 2 );
printf("String of integer %d (radix 2): %s",i,buffer);
return 0;
}
*you need to save your file as .c in MSVC++ for _itoa() to work.*
this is the header file for showbits
void showbits(unsigned int x)
{
int i;
for(i=(sizeof(int)*5)-1; i>=0; i--)
(x&(1u<<i))?putchar('1'):putchar('0');
printf("\n");
}
No there is no pre built function and you do not need to include any specific header file.
You will have to provide implementation for function showbits(int).
#include <stdio.h>
void showbits(int);
int main()
{
int j,k;
for(j=0;j<=11;j++)
{
printf("\nBinary value of decimal %d is :",j);
showbits(j);
}
return 0;
}
showbits(int n){
int i,k,andmask;
for(i = 15;i>=0;i--){
andmask = 1<<i;
k = n & andmask;
k==0 ? printf("0"):printf("1");
}
}
If you want to print out the bits of a float, for example you could do something like:
float myFloat = 45.2;
for (int n=0;n<8*sizeof(float);n++) {
printf("%d",(myFloat>>n)&1);
}

Resources