Multiplication and Binary Conversion at same time - c

I'm trying to multiply two user inputs using Russian Multiplication and convert that result into Binary at the same time. Keep getting errors
#include <stdio.h>
int main()
{
while(1){
int i, choice;
printf("What would you like to do?\n 1. Multiplication \n 2. Exit\n\n");
if(choice == 1){
int a,b,c;
a=0;b=0;
c=0;
printf("enter your first number\n");
scanf("%d",&a);
printf("enter your second number\n");
scanf("%d",&b);
while(b>=1){
a=a*2;
b=b/2;
if(b%2==1)
c=c+a;
}
printf("Russian Multiplication result is=%d\n",c);
getchar();
{
int num, bin;
scanf("%d", &num);
bin = printbinary(num);
printf("The binary equivalent of %d is %d\n", num, bin);
}
int printbinary(int num);
if (num == 0)
{
return 0;
}
else
{
return (num % 2) + 10 * printbinary(num / 2);
}
}
if(choice ==2){
return 0;
}
else{
printf("That's not an option dude, try again\n");
}
}
}
Keep getting implicit declaration of function 'printbinary' [-Wimplicit-function-declaration]
bin == printbinary(num);
Also getting an error that states: 'num' undeclared (first use in this function) if(num == 0)

I'm not sure what you really are up to, because there are a lot of logical errors in the code. I am going to point out and give alternatives to what caused the errors which you have mentioned in the question.
implicit declaration of function 'printbinary'
[-Wimplicit-function-declaration]
This is a result of not defining the function before using or calling it. So declare it globally first as follows before main():
#include<stdio.h>
int printbinary(int);
int main() {...
And what is int printbinary(int num); supposed to do after that block of code which
so strangely enclosed in {...}(I've mentioned this in the next point)? When a function is said to have a return type which isn't void, in this case int, there should be some int variable or something which is taking it. else it's useless.
'num' undeclared (first use in this function) if(num == 0):
This is because of this code:
{
int num, bin;
scanf("%d", &num);
bin = printbinary(num);
printf("The binary equivalent of %d is %d\n", num, bin);
} //what's the point of these braces buddy??????
The variables num and bin are accessible only inside this block. So when you try to access num outside of it (i.e, after the closing bracket(}) ), it naturally says it's not not declared.

Related

No output in C program

This my first program of C programming using recursive functions, it calculates the sum of the first n natural numbers. I am not able to get an output from it, it asks for the number but after that the program doesnt respond, can someone please help me out?
int n();
int main(){
int num;
printf("Enter num:\n");
scanf("%d", &num);
n(num);
printf("The sum of %d is: %f", num, n(num));
return 0;
}
int n(int x){
if (x != 0){
return n(x) + n(x-1);
**strong text** }
else{
return x;
}
}
Firstly, in the recursive function, return n(x) + n(x-1); should have been return x + n(x-1); as in the first case, n(x) will continuously make a called to another n(x), therefore making an infinite loop, or, more formally, return a 0xC00000FD exception, a Stack Overflow exception.
Also, in the last printf() function, %f should have been %d:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %d", num, n(num));
return 0;
}
Using %f to print an integer will caused an undefined behavior, because %f is a float format specifier, as noted here.
If you really want to convert it to a float:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %f", num, (double) n(num));
return 0;
}
*Note: Ran on Code::Blocks 20.03, Windows 10 64bit.
More info on format specifiers : https://www.tutorialspoint.com/format-specifiers-in-c
It should be return x instead of calling the same function,
you can use type conversion for changing the integer into a float,
int n();
int main(){
int num,x;
printf("Enter num:\n");
scanf("%d", &num);
x=n(num);
printf("The sum of %d is: %f", num, float(x));
return 0;
}
int n(int x){
if (x != 0){
return x + n(x-1);
**strong text** }
else{
return x;
}
}

C Code exits with non-zero status

I'm making a program in C that is supposed to ask for two numbers and find their LCM and GCF. However, after asking for those two numbers the code just exits with a non-zero status. Link to code here, any help would be appreciated.
#include <stdio.h>
int main()
{
//Declare things
int i;
int num1,num2 = 0;
int foundLCM = 0;
int foundGCF = 0;
//Ask for input
printf("\nEnter a positive integer: ");
scanf("%i", &num1);
printf("\nEnter another positive integer: ");
scanf("%i", &num2);
//Set i to the bigger number
if(num1 >= num2)
{
int i = num1;
}
else
{
int i = num2;
}
//find the GCF
while(foundGCF == 0)
{
if(num1%i == 0 && num2%i == 0)
{
printf("\nGreatest Common Factor: %i\n", i);
foundGCF = 1;
}
i--;
}
//Find the LCM
while(foundLCM == 0)
{
if(i%num1 == 0 && i%num2 == 0)
{
printf("Lowest Common Multiple: %i", i);
foundLCM = 1;
}
i++;
}
//Kill
return 0;
}
You need to remove the redeclarations of i on lines 21 and 27 and simply assign the value of i to num1 and num2 respectively. As it stands, i is not initialized when it is used in increment/decrement, which results in the program crashing.
Also, you'd need to restore i to its initial value after the GCF loop and before the LCM loop. Otherwise, it'll give wrong value in cases where there's no common factor. I'd suggest storing the initial value in some other variable.
See https://repl.it/NKgR/12
Please note that this is not the optimal way to calculate GCF and LCM. You can have a look at Euclid algorithm and implementations for more info.
The variable i is not initialized.
t.c: In function 'main':
t.c:21:7: warning: unused variable 'i' [-Wunused-variable]
int i = num1;
^
t.c:27:7: warning: unused variable 'i' [-Wunused-variable]
int i = num2;
^
t.c:37:7: warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
printf("\nGreatest Common Factor: %i\n", i);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You should replace int i = num1; by i = num1; Same thing for int i = num2;

Trying to pass addresses to simple variables to a function (pointers & loops) In C

I'm trying to declare variables in my main() and then use their address and point to them in a function so that my function doesn't return any thing and all changes of the variable in the function goes straight to the main(). But every time I run this program it asks for x and then for "how many terms to use".. If I write 0 it works and goes to the if statement and if i write and bigger number than 0 than it works but if I write a negative number like -1 it moves on and ends he program??? does anyone have any idea?
Here's my basic code:
void getInput(double *,int *);
void main()
{
double x;
int n;
getInput(&x,&n);
}
void getInput(double *N, int *X)
{
N = 0;
printf("Please enter a real value for x: ");
scanf("%lf", &X);
while(N <= 0)
{
printf("How many terms to use: ");
scanf("%ld", &N);
if (N <= 0)
{
printf("The value of a must be greater than %d\n", N);
}
}
}
Change:
scanf("%lf", &X);
to:
scanf("%d", X);
Inside the getInput function, X is already a pointer.
The same for the other scanf, where you should change scanf("%ld", &N); to scanf("%lf", N);.
Also change N = 0 to *N = 0 and if (N <= 0) to if (*N <= 0).
You also mixed up the %ld and the %lf format specifiers.
Your compiler should have warned you.
And finally change:
printf("The value of a must be greater than %d\n", N);
to
printf("The value of a must be greater than 0");
If you enter e.g. -1 you don't want the text The value of a must be greater than -1 to be displayed.
Unrelated:
it's int main(), not void main().

Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)

C program containing user defined function, while loop and if/else structure

Program (in C) is to ask user to input integers one at a time (0 is quit indication) and find the number and total of the even inputs/odd inputs using while loop, if/else structure, and user defined function. I can't get the user defined function to print the statements needed.
(Code so far below)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%s", name);
int num=1, even_count=0, even_sum=0, odd_count=0, odd_sum=0;
while (num != 0)
{
printf("Enter an integer (0 to stop): ");
scanf("%d", &num);
}
if ((num % 2) == 0) {
even_count++;
}
else {
odd_count++;
}
printf("%s,your inputs are broken down as follows: \n", name);
return even_count, even_sum, odd_count, odd_sum;
}
int output_function(int even_ct, int e_sum, int odd_ct, int o_sum)
{
int count1, sum1, count2, sum2 = main();
printf("You entered %d even numbers with a total value of %d.\n", count1, sum1);
printf("You entered %d odd numbers with a total value of %d.\n", count2, sum2);
return 0;
}
You never call output_function.
Replace
return even_count, even_sum, odd_count, odd_sum;
by
output_function(even_count, eve_sum, odd_count, odd_sum);
and remove
int count1, sum1, count2, sum2 = main();
The last line to remove makes absolutely no sense.
and finally replace your printfs by this:
printf("You entered %d even numbers with a total value of %d.\n", even_ct, e_sum);
printf("You entered %d odd numbers with a total value of %d.\n", odd_ct, o_sum);
I think, first you should declare the output_function before the main:
int output_function(int even_ct, int e_sum, int odd_ct, int o_sum);
int main()
{...}
Second, the return value of the main must be a single integer value.
Third, the output_function return always a zero.
And don't forget to call the output_function.
SK
You have some nice thoughts.
You thought:
output_function is defined after main so it can call main
A function can return several variables which in order:
return even_count, even_sum, odd_count, odd_sum;
And you can get the value of them by calling the function:
int count1, sum1, count2, sum2 = main();
But C does not work like that:
main function is executed the very first, earlier than any other functions.
You cannot return several variables like that in C (in some other high level languages like Python, it is ok).
return even_count, even_sum, odd_count, odd_sum; equals to return odd_sum;
Similar above point, int count1, sum1, count2, sum2 = somethings; just bring you sum2 = somethings
Please clean these mess first and you might get the program work well.

Resources