I need to make a function that sums my array, which is filled with random values. My function only returns 0 and not an actual summation of the array. I don't have much experience with arrays or random values, how can I code my arrSum function to give me the sum of the array when called?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
int arrSum(int arr[SIZE], int b) {
if (b < 0) {
return 0;
} else {
return arr[b] + arrSum(arr, b - 1);
}
}
int main() {
int inputNum;
int i;
int arr1[SIZE];
int sum;
srand(time(0));
printf("Enter an integer between 0 and 1000: ");
scanf("%d", &inputNum);
sum = arrSum(arr1, inputNum);
printf("sum: %6d\n\n", sum );
printf(" Pos | Val\n");
printf("-------------\n");
for (i = 0; i < inputNum; i++) {
printf("%4d |%4d\n", i, rand() % 1001);
}
return 0;
}
The reason is initially there are no values in the array. But only 0.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
int arrSum(int arr[SIZE], int b){
if (b < 0) return 0;
else return arr[b] + arrSum(arr, b-1);
}
int main(){
int inputNum;
int i,q;
int arr1[SIZE] = {0};
int sum;
srand(time(0));
printf("Enter an integer between 0 and 1000: ");
scanf("%d",&inputNum);
for(q=0;q<inputNum;q++){
arr1[q] = rand() % 1001;
}
sum = arrSum(arr1, inputNum);
printf("sum: %6d\n\n", sum );
printf(" Pos | Val\n");
printf("-------------\n");
for (i = 0; i < inputNum; i++){
printf("%4d |%4d\n", i,arr1[i]);
}
return 0;
}
The logic behind finding the sum inside the function is correct, assuming that b is within the range of the array indices. The real problem is that your array is not filled with random numbers - it is filled with zeros.
When you do
int arr1[SIZE] = {0};
you are initializing each element to 0, and are not changing it at any point during the program. So, your function returns the sum from indices 0 to b, but this turns out to be 0.
Related
The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}
This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.
can you help me with code which returns partial sum of 'X' numbers in array in c?
Complete :
int arr_sum( int arr[], int n )//Recursive sum of array
{
if (n < 0) //base case:
{
return arr[0];
}
else
{
return arr[n] + arr_sum(arr, n-1);
}
}
void sum_till_last (int *ar,int si )
{
**int sum,i;// the problem some where here
ar=(int*) malloc(si*sizeof(int));
for (i=0; i<si;i++)
{
sum=arr_sum(ar,i);
ar [i]=sum;
}
free (ar);**
}
void main ()
{
int i;
int a [5];
for (i = 0; i < 5; i++)
scanf_s("%d", &a[i]);
sum_till_last(a,5);
printf("%d\n",a[5]);
}
\i want to create new array with this this legality:
My input :
4
13
23
21
11
The output should be (without brackets or commas):
4
17
40
61
72
Now when we can see the full code, it's quite obvious that the problem is in the sum_till_last function where you overwrite the pointer you pass to the function with some new and uninitialized memory you allocate.
Drop the allocation (and the call to free of course). And fix the logical bug in arr_sum that causes you to get arr[0] + arr[0] when i is zero.
Here you go:
#include <stdio.h>
int main () {
int in_arr[5] = {4,13,23,21,11};
int out_arr[5];
int p_sum =0;
int i;
for ( i=0;i<5;i++){
out_arr[i] = in_arr[i]+p_sum;
p_sum=p_sum+in_arr[i];
}
for (i=0;i<5;i++){
printf("%d", out_arr[i] );
}
}
Fix according to your policy
#include <stdio.h>
#include <stdlib.h>
int arr_sum(int arr[], int n){
if (n == 0){//Change to this
return arr[0];
} else {
return arr[n] + arr_sum(arr, n-1);
}
}
void sum_till_last(int *ar, int si){
int sum,i;
int *temp = malloc(si * sizeof(int));//variable name ar is shadowing parameter name ar.
for(i = 0; i < si; i++){
temp[i] = arr_sum(ar, i);
if(i)
putchar(' ');
printf("%d", temp[i]);//need print out :D
}
free(temp);
}
int main(void){
int i, a[5];
for (i = 0; i < 5; i++)
scanf_s("%d", &a[i]);
sum_till_last(a, 5);
//printf("%d\n",a[5]);<-- this print only one element. and It's out of bounds element XD
}
I just made it simple so it´s easy to understand :)
I´m assuming "n" is always equal or less then array element number. Then you just print the SUM.
#include <stdio.h>
int arr_sum( int arr[], int n ){
int i=0,SUM=0;
for(; i < n;i++){
SUM= SUM+ arr[i];
printf("%d ",SUM);
}
}
int main(void) {
int array[] = {4, 13, 23, 21, 11};
arr_sum(array,5);
return 0;
}
I need in c code that generates two numbers in horizontally...so that i can get token numbers for my login system.
I need that i get this:
token=0.152644,0.429187
so in example i have token= and random generated numbers that have at beginning 0. and then 6 random generated numbers separated with , sign.
How to get get this in C?
I have try this code but it does not give me what i want_
#include <stdio.h>
#include <string.h>
typedef
union
{
char tmp[sizeof(unsigned long long)];
unsigned long long myll;
} ll_t;
unsigned long long llrand(void)
{
FILE *in=fopen("/dev/urandom", "r");
ll_t ll_u;
fread(ll_u.tmp, sizeof(ll_u.tmp), 1, in);
fclose(in);
return ll_u.myll;
}
int main()
{
char tmp1[64]={0x0};
char working[64]={0x0};
int i=0;
for(i=0; i< 1; i++)
{
while(strlen(tmp1) < 6)
{
sprintf(working, "%lu", llrand() );
strcat(tmp1, working);
}
tmp1[6]=0x0;
printf("%s\n", tmp1);
*tmp1=0x0;
}
return 0;
}
From output i get this:
747563
102595
Can code be simple and short?
You can use rand() function:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int randomNumber(int min, int max)
{
/* generate secret number between min and max: */
int res = rand() % (max-min+1) + min;
return res;
}
int main()
{
int i = 0;
srand (time(NULL));
for (i=0; i<100; i++)
printf("%d ", randomNumber(10, 1000000));
return 0;
}
That is full detail for rand():
http://www.cplusplus.com/reference/cstdlib/rand/
Here is the code that is working perfect:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n1, n2;
time_t t;
srand((unsigned) time(&t));
n1 = rand() % 1000000 + 1;
n2 = rand() % 1000000 + 1;
printf("token=0.%d,0.%d\n", n1, n2);
return 0;
}
And output is:
token=0.289384,0.930887
A propose a different approach. Instead of generating 2 numbers and format them into the output string, generate 12 different digits and put them directly in place.
srand(time(0));
char output[] = "taken=0.XXXXXX,0.YYYYYY";
for (int n = 0; n < 2; n++) {
for (int k = 0; k < 6; k++) {
output[9 * n + 8 + k] = rand() % 10 + '0';
// you might want to write a function that deals with rand() bias
}
}
puts(output);
I want to write a code for making square-root not using pow().
here is what i have tried:
#include <stdio.h>
#include <stdlib.h>
int main(){
int a,I,sum=0,cnt=0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
}
printf("answer is:%d",cnt);
return 0;
}
for numbers like 4,9,16,... it works but for numbers like 10,17,21,.. it does not work and the result is more than it shoud be.
what is the problem?
for(I=1;;I+=2){
sum+=I;
if(sum>a)
break;
cnt++;
}
#include <stdio.h>
#include <stdlib.h>
int main(){
int a,I,sum=0,cnt=0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
}
if(sum==a)
printf("answer is:%d",cnt);
else
printf("answer is:%d",cnt-1);
return 0;
}
You can try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,I,cnt=0;
int sum = 0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
if(sum > a) //add this if statement to decrement cnt by 1 when sum exceeds a.
cnt--;
}
printf("answer is:%d",cnt);
}
Input:
21
Output:
4
Use the Babylonian method:
double babyl_sqrt(double x)
{
double i;
for (i = x / 2; fabs(i * i - x) > 0.000001f; i = (i + x / i) / 2)
;
return i;
}
To get a rounded to nearest int, adjust the limit a little bit.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int sqrt_round(int a) {
int I;
int sum = 0;
int cnt = 0;
// for(I=1;sum<a;I+=2){
for (I = 1; (sum + I / 2) < a; I += 2) {
sum += I;
cnt++;
}
return cnt;
}
int main() {
int a;
printf("enter number");
scanf("%d", &a);
printf("answer is:%d\n", sqrt_round(a));
printf("answer is:%g\n", sqrt(a));
return 0;
}
#include<stdio.h>
int main()
{
float i,x=10;
int lp;
scanf("%f",&i);
for(lp=0;lp<5;lp++)
x=(x-((((x*x)-i))/(2*x)));
printf("sqaure root of %f=%f\n",i,x);
return 0;
}
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
public int mySqrt(int x) {
long start = 1;
long end = x;
while(start + 1< end) {
long mid = start + (end - start) / 2 ;
if(mid * mid == x) {
return (int)mid;
}else if(mid * mid < x) {
start = mid ;
}else {
end = mid;
}
}
if(end * end == x) {
return (int)end;
}
return (int)start;
}