Typecasting in division in C - c

#include <stdio.h>
int main(void) {
int t;
long long int a[100000], n, i;
scanf("%d\n", &t);
while(t){
t--;
scanf("%d", &n);
printf("%ld\n", n);
n = n * (n-1);
printf("%ld\n", n);
n = n/2;
printf("%ld\n", n);
}
return 0;
}
Can't figure out the problem in division. It's returning garbage value in the third printf statement. Can you please help me identify where the problem is?

The format specifier for long long int is lld, not ld.
That's especially important in the scanf as using the wrong specifier may end up putting the data in the wrong bytes within the variable.

Related

Program stops after loop in function

My prog doesn't reach outArray function. it stops after loop of fillArray function. Why this happens. It looks strangely, cause it's simple void function and shouldn't return anything. This should continue run commands in main. And that stops as usual program without any problems and bugs
#include <stdio.h>
#define N 100
int enterNofArray();
void fillArray(int n, float arr[N]);
void outArray(int n, float arr[N]);
int main()
{
float arr[N], sum = 0.0, average;
int n;
//input
n = enterNofArray();
//compute
fillArray(n, &arr[N]);
//output
outArray(n, &arr[N]);
return 0;
}
int enterNofArray()
{
int n;
printf("Enter amount of array...\n");
scanf("%d", &n);
while (n < 1 || n > N)
{
printf("Incorrect!!\n");
printf("Enter in range 1 - 100...\n");
scanf("%d", &n);
}
return n;
}
void fillArray(int n, float arr[N])
{
int num;
for(int i = 0; i < n; i++)
{
printf("Enter number for array[%d times left]...\n", n - i);
scanf("%d", &num);
arr[i] = num;
}
}
void outArray(int n, float arr[N])
{
for(int i = 0; i < n; i++)
{
printf("%f ", arr[i]);
}
}
&arr[N] refers to the memory location (or lvalue) that contains the N-th (out of index!!!) element in the array.
That code invokes Undefined Behavior (UB).
So, you weren't actually passing the whole array to your functions, you were just attempting to pass the N-th element of that array... Read more about that expression here.
Change this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
to this:
fillArray(n, arr);
outArray(n, arr);
Live Demo
The problem was that with your code n was corrupted, containing garbage value after the call to fillArray function. As a result, when outArray function was called, n had a garbage value, which resulted in an uncontrolled for-loop that ended in looping far further than the limits of your array, eventually accessing memory that you didn't own, thus causing a Segmentation Fault.
Not the cause of your problem, but I suggest you do scanf("%f", &num); in your fillArray function (after declaring num as a float of course), since you want to populate an array of floats.
Because you're send double pointer when you do this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
Looks like:
fillArray(n, **arr);
outArray(n, **arr);
This happends so much when you work with Structures.

I am getting an Memory fault(coredump) error message in my c program?

I am not able to understand why it is showing this error.
I have never encountered such an error before.
Here is my code, can you identify the mistake or the cause of it :
#include<stdio.h>
#include<math.h>
void dec2bin(int n,int bin[1000]){
int num = 0, index = 0, i;
while (n != 0){
bin[index] = n%2;
index++;
n = n/2;
}
}
int Sub(int a[100],int b[1000],int ac[100],int siz){
int i=siz-1,k=0;
for(;i>=0;i--){
if(b[i]){
a[k++]=ac[siz-i-1];
}
}
return k;
}
int sum(int a[100],int s){
int i,sum=0;
for(i=0;i<s;i++)
sum+=a[i];
return sum;
}
main(){
int b[1000],sub[100],a[100],n,i,s,count=0;
printf("Enter n: ");
scanf("%d",n);
for(i=0;i<n;i++){
printf("Enter number %d",i+1);
scanf("%d",&a[i]);
}
printf("Enter S: ");
scanf("%d",s);
int no=(int)pow(2.0,(float)n);
for (i=0;i<1000;i++)
b[i]=0;
for(i=0;i<no;i++){
dec2bin(i,b);
int siz=Sub(sub,b,a,n);
if(sum(sub,siz)==s)
count++;
}
printf("Subsets: %d",count);
}
And this code shows memory fault error immediately after entering the value of n.
You're using scanf slightly incorrectly.
The arguments following the format string need to be pointers to your objects, not the objects themselves.
scanf("%d", &n);
Do remember though, that scanf is very dangerous to use. Behavior is undefined for instance if the integer would overflow. Better to read a line safely then use strtol to parse it, since you can detect errors properly.
when taking input for n.
scanf("%d", &n);
You forgot a &

Int array to store large numbers (over 20 digits)

I have an assignment that requires me to first set up integer arrays to store arbitrarily large numbers. By using each element of an int array, I can hold one digit per element because int variable types are 32 bits and can only reach up to about 2 billion before failing. I know that there are other libraries using BigInt but I wanted to make my own arrays instead.
I tested my code out, but it doesn't seem to be accepting values past 9 digits until it starts to fail.
int * toArray(int, int);
int main()
{
int n, *res, counter, i;
printf("Input: ");
scanf("%d", &n);
while(n>0){
n/=10;
counter++;
}
res = toArray(n, counter);
for(i=1;i<=counter;i++){
printf("%d", *(res)+i);
}
printf("\n");
}
int * toArray(int n, int counter)
{
int i;
int *numberArray = malloc(sizeof(int) * counter);
for(i=0; i< counter; i++)
{
numberArray[i] = n % 10;
}
return numberArray;
}
I want to be able to accept close to twenty digits at the very least. I know this can be done with int arrays, although char arrays (or strings) are also a possibility. But I wanted to use int arrays instead. Any help in understanding why it fails around 9 digits and suggestions for going past that would be very much appreciated. Thank you.
The problem is that you are reading an int from keyboard
scanf("%d", &n);
so therefore no matter how many digits you enter, you still will only get 9 digits.
In order to be able to enter an arbitrary number you would have to read it as a string instead, then convert it to your int array.
EDIT:
this way (for instance) would allow for 20 digits
char ch;
int digits[20];
int i = 0;
do
{
ch = fgetc(stdin);
if ( isdigit(ch) )
{
digits[i++] = ch - 48; // convert ASCII to int
}
}
while (isdigit(ch) && i < sizeof(digits)/sizeof(digits[0]));
#include<stdio.h>
#include<stdlib.h>
int *toArray(long long int n, int counter); int main() {
long long int n=0,copy_of_n=0;
int counter=0, i=0;
int *res=NULL;
printf("Input: ");
scanf("%lld", &n);//Refer note in the answer
copy_of_n=n;//see the while loop why use this.
while(n>0){
n/=10;//Good, but you are not storing it. copy_of_n does that.
counter++;//You didn't initialize this
}
res=toArray(copy_of_n, counter);
for(i=counter-1;i>=0;i--){//This ensures you get the numbers in a proper order and since index starts from 0 in the toArray function
printf("%d", res[i]);
}
printf("\n");
free(res);//You forgot this
return 0; }
int *toArray(long long int n, int counter) {
int i=0;
int *numberArray = malloc(sizeof(int) * counter);
memset(numberArray,0x00,counter*sizeof(int));//Good to do this
//Check for memory allocation
for(i=0; i< counter; i++)
{
numberArray[i] = n % 10;
n=n/10LL;//You have to remove the digits too
}
return numberArray; }
NOTE: Read in a while loop the integers in small parts because long long has limits of how many digits it can store. Another approach would be to store in a string and send split the string into exactly the max. no. of digits that can be stored in long long in the n variable and send it to the function, part by part.
long long size is implementation dependent, hence ensure you check the max. no. of digits it can accomodate.(It will ofcourse bypass your 9-digit limit as asked in question)

scanf infinite loop

This program takes the first number in a file and indicates how many numbers are going to be after it, then does various other things with the numbers that follow.
It seems like scanf is causing an infinite loop when trying to read from the file. WHen I run the program not even the check at 1 works
Here is the code:
#include <stdio.h>
int main(void) {
int N, a, n;
int x=0;
int t=0;
printf("1"); //Check
scanf("%d", &N);
printf("2"); //Check
int nums[N];
int i;
printf("%d", &N); //Check
for (i=0; i<N; i++)
{
scanf("%d", &nums[i]);
t+=nums[i];
if (nums[i] > x) x=nums[i];
if (i=0 || nums[i] < n) n = nums[i];
}
a = t/N;
printf("Number Processed: \t%d\n", &N);
printf("Maximum: \t%d\n", &x);
printf("Minimum: \t%d\n", &n);
printf("Total: \t%d\n", &t);
printf("Average: \t%d\n", &a);
}
The way i run the program is
gcc -lab16
./a.out <in1
where in1 is text and has the numbers
7
6
-30
90
3903
-934
443
445
Thanks for your time.
if (i=0 || nums[i] < n) n = nums[i];
you are assigning i = 0, so the loop never realy advances! You probably wanted i == 0. This is causing the infinite loop.
Other issue: int nums[N]; - if you want an array of dynamic [determined in run-time] size, you will probably need to malloc() it.
Update: note that int nums[N] is valid in C99, so if your assigment is assuming C99 you should not worry about this issue. Otherwise - malloc() will be needed:
int* nums = (int*) malloc(sizeof(int) * N)
And don't forget to free(nums) before the program ends, or you will get memory leak.
if (i=0 || nums[i] < n) n = nums[i];
This is the culprit. You are making an assignment i=0 when you should do a comparison : i==0
Your loop goes to infinity because everytime you are i to 0.
Moreover, the code you gave us, gave me an error, because you were creating new variables during runtime.
#include <stdio.h>
#include "stdlib.h"
int main(void) {
int N, a, n;
int x=0;
int t=0;
int i;
int *nums;
printf("1"); //Check
scanf("%d", &N);
printf("2"); //Check
nums = malloc(N*sizeof(int));
....
There are numerous problems with this code.
You mistook assignment for comparison:
i=0
sets i to zero. You probably meant
i==0
which checks whether i is equal to zero.
You should check the value returned by scanf(). When data read by scanf() doesn't fit the format you specified it leaves the data in the buffer and the next call to scanf() sees the same data again.
The reason that the first printf() doesn't print anything is most likely that you are not printing any newline. Note that on some output devices like terminals output is line-buffered.
You are passing a pointer to a variable to printf(), but your format specifies %d. You probably meant the variable itself, not a pointer to it.
Also, if you need an array of length dependent on a value known only at runtime, you need to allocate it on the heap, e.g. using malloc().

I'm trying to fill an Array with user input, I've already prompted the user now I'm trying to write a fillArray function

#include <stdio.h>
#include <stdlib.h>
#define MAX 25
int readTotalNums();
void fillArray (int nums[], int total);
void sortIt (int nums[], int total);
int findMean (int nums[], int total);
int findMedian (int nums[], int total);
int findMode (int nums[], int total);
void printResults (mean, median, mode);
int goAgain ();
int main()
{
int nums[MAX];
int total;
double mean, median, mode;
do
{
total=readTotalNums();
fillArray(total,nums);
sortIt(nums, total);
mean= findMean (nums,total);
mode=findMode(nums,total);
median=findMedian(nums, total);
printResults(mean,mode, median);
}while(goAgain());
return 0;
}
int readTotalNums()
{
int total;
do
{
printf("How many numbers would you like to enter? (1-25)\n");
scanf("%i",&total);
while(getchar()!='\n');
}while (total<1 || total>MAX);
return total;
}
void fillArray (int nums[], int total)
{
int x;
for (x=0; x<total; x++)
{
printf("enter your numbers\n");
scanf("%i", &nums[x]);
while(getchar()!='\n');
}
}
So I decided to just put up what I have already... because maybe the problem comes before my fillArray function...
I keep getting a "This program has stopped working" message, which, I know you usually get if you don't strip your carriage return. I'm very much a newbie, just trying to make it though my only programming class I have to take for my major, so any help would be appreciated!!
You should pass to scanf a pointer to the location it should store the input, not the value that is already there. scanf("%i", &nums[x]);
The second argument to scanf should be a pointer. Here you are passing an integer. Since this is homework I won't give you the exact code, but that is the problem as far as I can tell.
The scanf function expects pointers, not integers. Didn't you get a compiler warning when you compiled? Try this:
scanf("%i", nums + x);
or equivalently
scanf("%i", &nums[x]);

Resources