why is my function outputting incorrectly? - c

I created a factorial function and my output for integer b is incorrect when it is set at 5, any ideas as to why? b should be equal to the integer 120 and I am getting the number -95449088 after I compile and run it.
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
x *= i;
return x;
}
int main() {
int a=5, b;
b = factorial(a);
printf("%d\n", b);
}

Here you are using the same x value in the condition check of for-loop which is a mess up. Instead you can store the variable x to a variable temp and use this temp variable for checking the condition.
Please see below the corrected code
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i,temp=0;
temp = x; //store the x to temp
for(i=1; i < temp; i++){
x *= i;
}
return x;
}
int main() {
int a=5, b;
b = factorial(a);
printf("%d\n", b);
}

Other have explained that you should avoid mixing input and output variables. This is good advice, and as a beginner you should try to observe it.
But this is a special case, and here you can re-use the input value, provided you use a decreasing loop:
int factorial(int x)
{
int i;
for (i = x-1; i >1; i--)
x *= i;
return x;
}
It works because it implicitly initializes the return value with x and then multiplies it by all numbers below it, which is a possible definition for the factorial.

Related

C: give 2D array to function but the identifier "a" is not defined

I want to create 2 matrices and fill them with reandom numbers 0-9.
I just don't understand why my function doesn`t work like this.
If I define a and b with e.g. #define a = 3 it works.
So the problem occurs at:
void fillM(int array[a][b])
and
void printM(int array[a][b])
Original code
#include <stdio.h>
#include <float.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
//fill random
void fillM(int array[a][b]) {
for (int x=0; x < a; x++) {
for (int y=0; y < b; y++) {
array[x][y] = rand()%10;
}
}
}
//print
void printM(int array[a][b]){
for (int x=0; x < a; x++){
for (int y=0; y < b; y++) {
printf("%d ", array[a][b]);
}
printf("\n");
}
}
int Main(){
//do I really need this?
srand (time(NULL));
//set size
int n;
printf("please set size of n x n Matrix: \n");
scanf("%d", &n);
int m = n;
//initialise
int m1[n][m];
int m2[n][m];
fillM (m1);
fillM (m2);
return 0;
}
Revised code
#include <float.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
//fill random
void fillM(size_t a, size_t b, int array[a][b]) {
for (int x=0; x < a; x++) {
for (int y=0; y < b; y++) {
array[x][y] = rand()%10;
}
}
}
//print
void printM(size_t a, size_t b, int array[a][b]){
for (int x=0; x < a; x++){
for (int y=0; y < b; y++) {
printf("%d ", array[a][b]);
}
printf("\n");
}
printf("\n");
}
int main(){
srand (time(NULL));
//set size
int n;
printf("please set size of n x n Matrix: \n");
scanf("%d", &n);
printf("\n");
int m = n;
//initialise
int m1[n][m];
int m2[n][m];
fillM (n, m, m1);
fillM (n, m, m2);
printM (n, m, m1);
printM (n, m, m2);
return 0;
}
But one more question. If I run the program now, it doesn´t fill the matrix with random numbers everywhere. It puts the same random number in every place. Do you know how to fix this?
At the point where you use a and b, they are not defined. You need something more like:
void fill(size_t a, size_t b, int array[a][b]
Your calls will pass the array size as well.
In your revised code, you get the same answer for every printed value because you attempt to print the same element of the array, array[a][b] — except that it isn't an element of the array but is a long way out of bounds because the array indexes run from 0..a-1 and 0..b-1. Use array[x][y] instead.

f(&a) is possible to run in C?

The explanation below confused me:
When an argument is pointer to a variable x, we normally assume that x will be modified :
f(&x);
It is possible, though, that f merely needs to examine the value of x, not change it.
I tired to understand and the code below can't work.
#include <stdio.h>
void function(int& a)
{
a = 5;
}
void func(int b)
{
b = 5;
}
int main(void)
{
int x = 0;
function(x);
printf("%d", function(x));
func(x);
printf("%d", func(x));
return 0;
}
Code refer from the second answer:
int f(int &a){
a = 5;
}
int x = 0;
f(x);
//now x equals 5
int f2(int b){
b = 5;
}
int y = 0;
f2(y);
//y still equals 0
An example actually using f(&x):
#include <stdio.h>
void f(int *p) {
*p = 4;
}
int main(void) {
int x;
f(&x); // Provide a pointer to `x`.
printf("%d\n", x); // 4
return 0;
}
Both of your program use int &a, which isn't a valid C declaration. That is why they don't even compile.

Sum of array in C

I'm working on a small program for school and can't get my array of doubles to sum properly. The specific error I'm getting is
warning C4244: 'return': conversion from 'double' to 'int', possible loss of data
on the line where sum is returned. And the sum displayed is gibberish.
The code is intended to:
fill an array of doubles with user input,
print the doubles on the screen in a column,
add up all the doubles in the array, and
print the sum onto the screen.
Code
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAX_SIZE 15
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
SumArray(double a[], int *i);
int main()
{
double input[15];
int input_size;
double sum;
FillArray(input, &input_size);
PrintArray(input, input_size);
sum = SumArray(input, &input_size);
printf("The sum is %f\n", sum);
return 0;
}
void FillArray(double a[], int *i)
{
int k;
printf("Filling an array of doubles\n");
printf("How many doubles do you want to enter (<15)\n");
scanf(" %d", i);
for (k = 0; k <*i; k++)
{
printf("Enter double:\n");
scanf("%lf", &a[k]);
}
}
void PrintArray(double a[], int i)
{
int k;
printf("Printing an array of integers:\n");
for (k = 0; k<i; k++)
{
printf("%f\n", a[k]);
}
printf("\n");
}
SumArray(double a[], int *i)
{
int k;
double sum = 0;
for (k = 0; k<*i; k++);
{
sum +=a[k];
}
return (sum) ;
}
You need to specify double SumArray(...) instead of merely SumArray(...) where you declare and define the function. If you do not specify a return type, int is assumed. Specifically:
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
double SumArray(double a[], int *i);
/*^^^^^^-- add return type*/
int main()
and
double SumArray(double a[], const int numElements)
/*^^^^^^- same deal*/ /* also ^^^^^ ^^^^^^^^^^^ */
{
int k;
double sum = 0.0; /* Edit 3: 0.0 rather than 0 for clarity */
for (k = 0; k < numElements; ++k) /* no ; here! --- Edit 3: ++k for speed and good practice */
{ /* ^^^^^^^^^^^ */
sum +=a[k];
}
return (sum) ;
}
Edit Also, you can use const int numElements instead of int *i in SumArray. You don't need to modify the value inside SumArray, so you don't need the * and you can specify const. And it's a good practice to give your variables descriptive names, e.g., numElements instead of i. That will help you understand your own code when you have to maintain it later! (Ask me how I know. ;) )
To use this, you also need to change the call in main to remove the &:
sum = SumArray(input, input_size);
/* ^ no & here */
Edit 2 As #BLUEPIXY pointed out, the trailing ; on the for loop was misplaced. As a result, the {} block ran once, after the loop had completed. That would be a significant cause of the "gibberish" you saw: the effect was to set k=numElements and then set sum=a[numElements], which was a non-existent element. So the sum was being set to whatever random memory contents happened to be after a.

Convert a printed number using printf as a variable

I have
int main ()
{
int x=69057;
int y=23
printf("%d", x);
printf("%d", y);
return 0;
}
And it prints 6905723. How can I convert the printed number into an integer? I can't do
int z=6905723
since in the original program I don't know what value x and y have.
What you essentially want to do here is multiply x by the smallest power of 10 that's larger than y, and then add y to it.
Assuming x and y are small enough to not overflow the long result, you could do something like this:
int x = 69057;
int y = 23
int temp = y;
long result = x;
while (temp > 0) {
result *= 10;
temp /= 10;
}
result += y;
printf("%ld\n", result);
Here's how you can get the answer into int z. It works even if you don't know x and y before. You just need to make sure that the answer will actually fit into an int.
int main ()
{
int x=69057;
int y=23
char buff[512];
sprintf(buff, "%d%d", x, y);
int z = atoi(buff); /* Now z is equal to 6905723 */
return 0;
}
You will run into a problem if y is a negative number, but it isn't clear from your question what you'd like to happen in that situation.
try this. very easy and simple
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int x,y,z,a,b;
x=69057;
y=23;
printf("x=%d y=%d\n",x,y);
a = log10(y) + 1;
for (b=0;b<a;b++)
{
x*=10;
}
z=x+y;
printf("z=%d",z);
return 0;
}
You can write a function to do it for you:
#include <stdio.h>
int my_function(int x, int y);
int main()
{
int x = 69057;
int y = 23;
int z = my_function(x, y);
printf("%d\n", z);
return 0;
}
int my_function(int x, int y)
{
int tmp = y;
do {
x *= 10;
} while (tmp /= 10);
return x + y;
}

C++ uint64_t bitwise AND check for even number

I have the following code that simply checks if a uint64_t is even, I intended on using a bitwise AND operation to check but it doesn't seem to be working.
This is the code I thought would work first:
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++){
uint64_t s,d;
scanf("%llu %llu",&s,&d);
//try for x
uint64_t x;
bool stop = false;
x = s + d;
printf("%llu",x&1ULL); \\ This prints 0 when the number is even but
if(x&1ULL==0ULL){ \\ This check always returns false
printf("%llu",x);
x/= 2;
This code always prints out 0 or 1 if the the number is odd or even but the if statement always returns false. What am I doing wrong? Thanks
x&1ULL==0ULL is equivalent to x&(1ULL==0ULL). You need (x&1ULL)==0ULL.
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <stdint.h>
int main()
{
int n;
scanf_s("%d", &n);
for (int i = 0; i < n; i++) {
uint16_t s, d;
scanf_s("%llu %llu", &s, &d);
//try for x
uint16_t x;
bool stop = false;
x = s + d;
printf("%llu", x & 1ULL);
if ((x & 1ULL) == 0ULL) {
printf("%llu", x);
x /= 2;
}
}
return 0;
}
I think this should work anyway for me it works

Resources