modulo of a certain number and printing the answer in division statement - modulo

#include <iostream>
using namespace std;
int main(){
int num;
cout<<"Number: ";
cin>>num;
int answer;
answer = num%2;
cout<<"\n"<<answer;
}
i have the problem of printing the answer in my division statement.

Fix your recursive function, display output at time of unwinding i.e. after recursive calls
void DecimalToBinary(int n){
int r;
if (n != 0)
{
r = n%2;
DecimalToBinary(n/2); // recurse
cout <<r; // Then simple print r, as its either 0 or 1
}
// Your else if is not stopping the recursion and its not required
}

Try the following function instead of your's-
void DecimalToBinary(int n){
static int i=31; //(i=31 for 32 bit integers)
if(i>=0){
if (n&(1<<i--)){ //if the answer in r is 1 it will print 1
cout<<"1";
}
else{
cout<<"0"; //if the answer in r is 0 it will print 0
}
DecimalToBinary(n);
}
}

Related

I am trying to find the distance of a node from the root of a binary tree

I am trying to find the distance of a node from the root of a binary tree but I am getting right answer up to only 3 branches only. like for the node(4) I am getting 3 and for the node (9) and node(10) I am getting 3
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
int find_node(node* root,int n)
{
static int length=1;
if (root== NULL)
{
return 0;
}
if (root->data==n)
{
return length;
}
length=length+(find_node(root->left,n)||find_node(root->right,n));
// find_node(root->left,n);
// find_node(root->right,n);
return length;
}
int main ()
{
struct node* root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->left = new node(6);
root->right->right = new node(7);
root->right->right->right = new node(9);
root->right->right->right->right = new node(10);
cout <<find_node(root,10);
return 0;}
When your code reaches the first leaf node (with data 4), the following assignment will assign 1:
length=length+(find_node(root->left,n)||find_node(root->right,n));
Because the expression resolves to 1+(0||0), i.e. 1. And so 1 is returned.
The caller (at the node with data 2) will thus receive this 1, and so the above statement will yield 2, since it resolves to 1+(1||......), which is 2 -- the second operand of || is not evaluated.
The parent caller (at the node with data 1), will thus receive this 2. The assignment there resolves to 1+(2||.....), which is again 2 -- realise that || is a logical operator, so it can only evaluate to a boolean value (i.e. 0 or 1).
The issues
In summmary:
You should not use || as it can only evaluate to 0 or 1, losing the actual value from recursion that you need.
You should not use a static variable. For one, it would not reset if you would make a second call to this function from the main program code. Instead, every recursive call should just "mind its own business" and return the depth of n from the given root. The caller should add 1 to that if n was found.
Correction
int find_node(node* root, int n)
{
if (root == NULL)
{
return 0;
}
if (root->data == n)
{
return 1;
}
int length = find_node(root->left, n);
if (!length)
{
length = find_node(root->right, n);
}
if (!length)
{
return 0;
}
return 1 + length;
}

How do I pass a "C" string from a "C" routine to a GO function (and convert it to a GO string?)

This must be something really silly and basic, but the cgo docs (and google fu) have left me stranded. Here's what I am trying to do: I want a GO function to call a "C" function using 'import "C"'. Said "C" function needs to store the address of a "C" string (malloc or constant - neither has worked for me) into an argument passed to it as *C.char. The GO function then needs to convert this to a GO string. It actually does work, except I get this:
panic: runtime error: cgo argument has Go pointer to Go pointer
If I run with GODEBUG=cgocheck=0, it all works fine. If I leave as default:
strptr = 4e1cbf ('this is a C string!')
main: yylex returned token 1
yylval.tstrptr 4e1cbf
stringval token "this is a C string!"
The problematic line seems to be:
yylval.stringval = C.GoString(yylval.tstrptr)
What little I can find about C.GoString, it left me with the impression that it allocates a GO string, and fills it in from the "C" string provided, but that seems to not be the case, or why am I getting a complaint about 'Go pointer to Go pointer'? I've tried a number of other approaches, like having the "C" function malloc the buffer and the GO function do C.free() on it. Nothing has worked (where worked == avoiding this runtime panic).
The GO source:
package main
import (
"fmt"
"unsafe"
)
// #include <stdio.h>
// int yylex (void * foo, void *tp);
import "C"
type foo_t struct {
i int32
s string
}
var foo foo_t
func main() {
var retval int
var s string
var tp *C.char
for i := 0; i < 2; i++ {
retval = int(C.yylex(unsafe.Pointer(&foo), unsafe.Pointer(&tp)))
fmt.Printf("main: yylex returned %d\n", retval)
fmt.Printf("tp = %x\n", tp)
if retval == 0 {
s = C.GoString(tp)
fmt.Printf("foo.i = %d s = %q\n", foo.i, s)
} else {
foo.s = C.GoString(tp)
fmt.Printf("foo.i = %d foo.s = %q\n", foo.i, foo.s)
}
}
}
The "C" source
#include <stdio.h>
int yylex (int * foo, char ** tp)
{
static num;
*foo = 666;
*tp = "this is a C string!";
printf ("strptr = %x ('%s')\n", *tp, *tp);
return (num++);
}
What's interesting is that if the GO func stores into foo.s first, the 2nd call to yylex bombs with the panic. If I do s and then foo.s (depending on whether I check retval as 0 or non-zero), it doesn't fail, but I'm guessing that is because the GO function exits right away and there are no subsequent calls to yylex.

what does Caret sign do in Dart

I am looking at some Flutter projects and I notice this codes:
#override
int get hashCode => todos.hashCode ^ isLoading.hashCode;
What is this ^ sign doing here? This line of code is found in the AppState of Flutter projects. Is this used to compare the before and after State?
It is the bitwise XOR operator
https://www.dartlang.org/guides/language/language-tour#operators
Below is the way to use XOR operator. I think this is not useful to you but it is helpful to some one who searching for XOR operation
Call below method encryptDecrypt("123456") . you will get output as abcdef
String encryptDecrypt(String input) {
int xorKey = "P".codeUnitAt(0);
String output = "";
int length = input.length;
for (int i = 0; i < length; i++) {
output = (output + String.fromCharCode((input[i].codeUnitAt(0) ^ xorKey)));
}
return output;
}

How do i get this queue to work for the palindrome?

I resolved my bool issue, but now the output is not printing the whole word front and backwards. only partially. I posted the output down below. I am pretty stuck on this. I have tried numerous ways of trying to fix it. I know there are some c++ guru's out there that might be willing to lend a hand and tips?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "Queue.h"
void print(string s1, string q1)
{
cout << s1 << " ";
cout << q1 << endl;
}
int main()
{
bool isPalin= true;
string word;
//string temp;
Stack s1;
Queue q1;
void print(string, string);
cout<< " Enter a word you would like to see if it is a palindrome: \n";
getline(cin, word);
cout<< "The word you entered is: "<< word<< endl;
for ( int i = 0; i<(word.size()-1); i++)
{
string temp(word, i, 1);
s1.push(temp);
}
for (int i = 0; i<(word.size()-1); i++)
{
string temp(word, i,1);
q1.enqueue(temp);
}
while (!s1.empty())
{
print(s1.top(), q1.front());
if( s1.top() != q1.front())
{
isPalin = false;
s1.pop();
q1.dequeue();
}
cout<< " Lets check if this word is a palindrome" << boolalpha<< isPalin<<endl;
}
Output:
Enter a word you would like to see if it is a palindrome:
hello
The word you entered is: hello
l h
Lets check if this word is a palindromefalse
l e
Lets check if this word is a palindromefalse
e l
Lets check if this word is a palindromefalse
h l
Lets check if this word is a palindromefalse
Queue created.
It seems that you forgot to declare bool isPalin; somewhere before using it.
It is obviously my for loops and my while. I am trying to think of the logic. Stacks are FIFO and Queues are LIFO. but it is starting to confused me on how I would fix this. Maybe I should take one of the for loops away and make it push, enqueue and then dequeue?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "Queue.h"
void print(string s1, string q1)
{
cout << s1 << " ";
cout << q1 << endl;
}
int main()
{
bool isPalin= false;
string word;
//string temp;
Stack s1;
Queue q1;
void print(string, string);
cout<< " Enter a word you would like to see if it is a palindrome: \n";
getline(cin, word);
cout<< "The word you entered is: "<< word<< endl;
for ( int i = 0; i<=(word.size()-1); i++)
{
string temp(word, i, 1);
s1.push(temp);
}
for (int i = 0; i<=(word.size()-1); i++)
{
string temp(word, i, 1);
q1.enqueue(temp);
}
while (!s1.empty())
{
print(s1.top(), q1.front());
if( s1.top() != q1.front())
{
isPalin = true;
s1.pop();
q1.dequeue();
}
cout<< " Lets check if this word is a palindrome" << boolalpha<< isPalin<<endl;
}
Output:
Enter a word you would like to see if it is a palindrome:
word
The word you entered is: word
d w
Lets check if this word is a palindrometrue
r o
Lets check if this word is a palindrometrue
o r
Lets check if this word is a palindrometrue
w d
Lets check if this word is a palindrometrue

How to work with char types in Dart? (Print alphabet)

I am trying to learn the Dart language, by transposing the exercices given by my school for C programming.
The very first exercice in our C pool is to write a function print_alphabet() that prints the alphabet in lowercase; it is forbidden to print the alphabet directly.
In POSIX C, the straightforward solution would be:
#include <unistd.h>
void print_alphabet(void)
{
char c;
c = 'a';
while (c <= 'z')
{
write(STDOUT_FILENO, &c, 1);
c++;
}
}
int main(void)
{
print_alphabet();
return (0);
}
However, as far as I know, the current version of Dart (1.1.1) does not have an easy way of dealing with characters. The farthest I came up with (for my very first version) is this:
void print_alphabet()
{
var c = "a".codeUnits.first;
var i = 0;
while (++i <= 26)
{
print(c.toString());
c++;
}
}
void main() {
print_alphabet();
}
Which prints the ASCII value of each character, one per line, as a string ("97" ... "122"). Not really what I intended…
I am trying to search for a proper way of doing this. But the lack of a char type like the one in C is giving me a bit of a hard time, as a beginner!
Dart does not have character types.
To convert a code point to a string, you use the String constructor String.fromCharCode:
int c = "a".codeUnitAt(0);
int end = "z".codeUnitAt(0);
while (c <= end) {
print(String.fromCharCode(c));
c++;
}
For simple stuff like this, I'd use "print" instead of "stdout", if you don't mind the newlines.
There is also:
int char_a = 'a'.codeUnitAt(0);
print(String.fromCharCodes(new Iterable.generate(26, (x) => char_a + x)));
or, using newer list literal syntax:
int char_a = 'a'.codeUnitAt(0);
int char_z = 'z'.codeUnitAt(0);
print(String.fromCharCodes([for (var i = char_a; i <= char_z; i++) i]));
As I was finalizing my post and rephrasing my question’s title, I am no longer barking up the wrong tree thanks to this question about stdout.
It seems that one proper way of writing characters is to use stdout.writeCharCode from the dart:io library.
import 'dart:io';
void ft_print_alphabet()
{
var c = "a".codeUnits.first;
while (c <= "z".codeUnits.first)
stdout.writeCharCode(c++);
}
void main() {
ft_print_alphabet();
}
I still have no clue about how to manipulate character types, but at least I can print them.

Resources