Subtracting a sequence of numbers using for loop in C Programming - c

int myfunc(int a, int b)
{
int result = a;
for(int index = a - 1; index >= b; index--)
{
result -= index;
}
return result;
}
How to make this function subtract numbers from the smallest number to the greatest number depending on the values of a and b that I choose ? (e.g. if a = 5 and b = 8 , then the program would type 5-6-7-8 = -16)

You're going the "wrong direction". Look at what you want to do:
5-6-7-8 = -16
^ ^ ^ ^
a | | |
a+1| |
a+2|
a+3
So start at a+1 and count up to b
int result = a;
for(int index = a + 1; index <= b; index++)
{
result -= index;
}
// result = -16 for a=5, b=8
Demo

For starters the variable index is redundant.
To avoid an overflow (at least in most cases) the variable result should have the type long long int instead of int. For example if you will run your function like
myfunc( INT_MIN , INT_MIN + 3 );
(provided that you have included the header <limits.h>) when if the type of the variable result is int then the function will return the value -6 (actually the behavior is undefined in this case) while if the variable result has the type long long int then you will get the correct result 4294967290.
The function can look the following way
long long int myfunc( int a, int b )
{
if ( b < a )
{
int tmp = b;
b = a;
a = tmp;
}
long long int result = a;
while ( a < b )
{
result -= ++a;
}
return result;
}
Here is a demonstrative program.
#include <stdio.h>
long long int myfunc( int a, int b )
{
if ( b < a )
{
int tmp = b;
b = a;
a = tmp;
}
long long int result = a;
while ( a < b )
{
result -= ++a;
}
return result;
}
int main(void)
{
printf( "%lld\n", myfunc( 8, 5 ) );
return 0;
}
The program output is
-16

Related

Reference data from a array to another array in C

I want to reference new array to address from another array in C code like this:
int main()
{
int a[6] = {1,2,3,4,5,6};
int b[6];
unsigned long long int *c = &a[5];
unsigned long long int *d = &b[5];
int size = 6;
for(;size>0;size--,c--,d--){
*d = *c;
}
return 0;
}
but my code didn't work. can you tell me whats wrong in this code?
The data type of your pointer doesn’t match the data type of the array
These declarations
unsigned long long int *c = &a[5];
unsigned long long int *d = &b[5];
are incorrect because the declared objects have the type unsigned long long int * but are initialized by expressions of the type int *. Thus dereferencing the declared pointers you can get unexpected results.
If you want to use the pointer arithmetic in a for loop for example to copy the first array into the second array in the reverse order then the program can look the following way.
#include <stdio.h>
int main(void)
{
enum { N = 6 };
int a[N] = { 1, 2, 3, 4, 5, 6 };
int b[N];
for ( int * c = a + N, *d = b; c != a; )
{
*d++ = *--c;
}
for ( const int *d = b; d != b + N; ++d )
{
printf( "%d ", *d );
}
putchar ( '\n' );
return 0;
}
The program output is
6 5 4 3 2 1

sum of the array using pointers in c

Finding sum of the array elements using pointers using following code.
i dont know why program is not ending at the end of the array!!
#include <stdio.h>
#define LEN(a) (int) (sizeof(a)/sizeof(a[0]))
int sum_array(int * , int);
int main(void){
int a[] = {1,2,3,4,5,6,7,8,9};
printf("Array length %d\n",LEN(a));
int sum = sum_array(a,LEN(a));
printf("Sum of array is %d\n",sum);
return 0;
}
int sum_array( int * p , int n){
int sum = 0;
while ( p < p+n ){
printf("Sum of array is %d\n",sum);
sum += *p++;
}
return sum;
}
`
SOLVED GUYS thanks!!
int sum_array( int * a , int n){
int sum = 0, *p=a;
while ( p < a+n ){
printf("Sum of array is %d\n",sum);
sum += *p++;
}
return sum;
getting address boundary error!!
How can p < p + n ever be 1 for a non-negative n?
You need to store the initial value of p somewhere if you want to bound the loop that way.
For an easy life use for (int i = 0; i < n; ++i) in place of while (p < p + n) and adopt, if you must and against any professional advice, a flashy version once you have the basics correct.
The problem is that within the condition of the loop you are using the pointer that is changed within the loop.
while ( p < p+n ){
printf("Sum of array is %d\n",sum);
sum += *p++;
}
So the condition never will be equal to false except when n is equal to 0.
The function can be declared and defined the following way
long long int sum_array( const int *p , size_t n );
Pay attention to that within the function the array is not changed. So the first parameter should have the qualifier const.
And
long long int sum_array( const int *p , size_t n )
{
long long int sum = 0;
for ( const int *q = p; q < p + n; ++q )
{
sum += *q;
}
return sum;
}
If you want to use the while loop then the pointer q need to be defined outside the loop
const int *q = p;
while ( q < p + n )
{
sum += *q++;
}
Also do the following changes
#define LEN(a) (sizeof(a)/sizeof(a[0]))
and
printf("Array length %zu\n",LEN(a));
long long int sum = sum_array(a,LEN(a));
printf( "Sum of array is %lld\n",sum);
The type long long int is used for the variable sum because in general there can be an overflow.
Consider for example the following demonstrative program
#include <stdio.h>
#include <limits.h>
#define LEN(a) (sizeof(a)/sizeof(a[0]))
int sum_array( const int * , size_t );
int main(void)
{
int a[] = { INT_MAX, 1 };
printf("Array length %zu\n",LEN(a));
int sum = sum_array( a, LEN( a ) );
printf("Sum of array is %d\n",sum);
return 0;
}
int sum_array( const int *p , size_t n )
{
int sum = 0;
const int *q = p;
while ( q < p + n )
{
sum += *q++;
}
return sum;
}
Its output is
Array length 2
Sum of array is -2147483648
It is evident that the result is not what you are expecting.
If to make the type of the variable sum long long int then the result will be correct.
#include <stdio.h>
#include <limits.h>
#define LEN(a) (sizeof(a)/sizeof(a[0]))
long long int sum_array( const int * , size_t );
int main(void)
{
int a[] = { INT_MAX, 1 };
printf("Array length %zu\n",LEN(a));
long long int sum = sum_array( a, LEN( a ) );
printf("Sum of array is %lld\n",sum);
return 0;
}
long long int sum_array( const int *p , size_t n )
{
long long int sum = 0;
const int *q = p;
while ( q < p + n )
{
sum += *q++;
}
return sum;
}
The program output is
Array length 2
Sum of array is 2147483648

Hexadecimal comparison for big number in c program

#include<stdio.h>
long long int A = 0xAABBCCDDBBCCFFEE;
long long int B = 0xAACCCCDDBBDDFF00;
int array[8] = {'\0'};
int byte_compare(int A, int B)
{
int i = 0;
long long int j = 0xFF;
long long int C = A;
long long int D = B;
while(i < 8)
{
C = (j & A);
D = (j & B);
printf("C = %x\n",C);
printf("D = %x\n",D);
printf("j = %x\n",j);
if(C == D)
{
array[i] = 1;
}
else
{
array[i] = 0;
}
i++;
j = j << 8;
}
}
main()
{
int i = 0;
byte_compare(A,B);
while(i < 8)
{
printf("array[%d] - %d\n",i, array[i]);
i++;
}
}
long long int A = 0xAABBCCDDBBCCFFEE;
long long int B = 0xAACCCCDDBBDDFF00;
result = 10111010
when A and B byte number matches with each other it should print 1 otherwise 0.
for my above program it is printing output
C = ee
D = 0
j = ff
C = ff00
D = ff00
j = ff00
C = cc0000
D = dd0000
j = ff0000
C = bb000000
D = bb000000
j = ff000000
C = 0
D = 0
j = 0
C = 0
D = 0
j = 0
C = 0
D = 0
j = 0
C = 0
D = 0
j = 0
array[0] - 0
array[1] - 1
array[2] - 0
array[3] - 1
array[4] - 1
array[5] - 1
array[6] - 1
array[7] - 1
Not able to compare after first four byte please help me what datatype I should use instead above.
You have many problems in your code
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
void byte_compare(uint64_t C, uint64_t D, int *array)
{
int i = 0;
while (i < 8)
{
printf("C = %"PRIx64"\n" , (C&0xFF));
printf("D = %"PRIx64"\n\n", (D&0xFF));
if ((C&0xFF) == (D&0xFF))
{
array[i] = 1;
}
else
{
array[i] = 0;
}
i++;
C >>= 8;
D >>= 8;
}
}
int main(void)
{
int i = 0;
uint64_t A = UINT64_C(0xAABBCCDDBBCCFFEE);
uint64_t B = UINT64_C(0xAACCCCDDBBDDFF00);
int array[8] = {0};
byte_compare(A, B, array);
while (i < 8)
{
printf("array[%d] - %d\n", i, array[i]);
i++;
}
}
Correct type for your variables must be unsigned long long due to the literals: bit 63 is set to 1 so assign it to a signed variable causes overflow which invoke UB. Using stdint.h standard header you can use uint64_t that is clearer.
byte_compare function definition is wrong, you must pass parameters with correct type: unsigned long long (uint64_t). Moreover the function does not return an int so should be void.
printf with %x format specifier wants an unsigned int, not a uint64_t. Best thing to do is to use defined in inttypes.h standard header where all format specifier are well reported: in your case PRIx64 is the right one.
In your version of code you are left shifting a long long int that is used as mask to "select" the byte to check. It is plain wrong because last shift causes an overflow on a signed value that is UB as for point 1.
stdint.h has also macros that append the correct suffix to literals.
Another example using a mask:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
void byte_compare(uint64_t C, uint64_t D, int *array)
{
uint64_t mask = UINT64_C(0xFF00000000000000);
while (mask > 0)
{
printf("C = %"PRIx64"\n" , (C&mask));
printf("D = %"PRIx64"\n\n", (D&mask));
if ((C&mask) == (D&mask))
{
*array = 1;
}
else
{
*array = 0;
}
mask >>= 8;
array--;
}
}
int main(void)
{
int i = 0;
uint64_t A = UINT64_C(0xAABBCCDDBBCCFFEE);
uint64_t B = UINT64_C(0xAACCCCDDBBDDFF00);
int array[8] = {0};
byte_compare(A, B, &array[7]);
while (i < 8)
{
printf("array[%d] - %d\n", i, array[i]);
i++;
}
}

How to switch 2nd and 4th digit(before comma) in a double? C programming

So lets say the input is 45392.56, the output has to be 49352.56.
How can i program this in C?
#include <stdio.h>
#include <stdlib.h>
int dotPos(char arr[]) {
int i = 0;
while (arr[++i] != '.');
return i;
}
int main() {
double d = 45392.56;
int MAX = 100;
char arr[MAX];
sprintf(arr, "%f", d);
if (dotPos(arr) > 3) {
char aux = arr[1];
arr[1] = arr[3];
arr[3] = aux;
}
d = atof(arr);
printf("%.2f\n", d);
}
Output:
49352.56
Convert the number to a character array. Look at the sprintf function.
Swap the positions of the characters.
Convert the character array to double. Look at the atof function.
Avoiding conversion to string and back, take the integral part of the number, find the two values in position 1 and 3 (in decimal notation), and compute the value to add or substract to/from the original double.
this is (a-b) *pow(10,hipos) - (a-b) * pow(10,lopos)
#include <stdio.h>
long finddiff(unsigned long val, unsigned lpos, unsigned rpos);
int main(void) {
double d = 45392.56;
unsigned long u;
long dif;
u = d;
dif = finddiff(u,3,1);
d += dif;
printf("%.2f\n", d);
return 0;
}
long finddiff(unsigned long val, unsigned lpos, unsigned rpos)
{
long res;
unsigned pos, ll, rr;
if (lpos < rpos) return finddiff(val, rpos,lpos);
for (pos=0; pos < rpos; pos++) { val /= 10; }
rr = val %10;
for (; pos < lpos; pos++) { val /= 10; }
ll = val %10;
// fprintf(stderr, "%u,%u\n", ll,rr);
res = rr-ll;
for (; pos > rpos; pos--) { res *= 10; }
res -= rr-ll;
for (; pos > 0; pos--) { res *= 10; }
// fprintf(stderr, "%u,%u,%ld\n", ll,rr, res);
if (ll > rr) res = -res;
else if (rr > ll) {;}
else res = 0;
return res;
}
BTW: this will fail miserably for values whose integer part is larger than the maximum log int, eg 6.3E23 .
For negative numbers some additional logic should be added.

Stack frame size of a function

Simple question: Is there a way to determine the stack size of a function?
int stackframe_size(int run) {
int i ;
if(!run) {
return ((int)(&i) - stackframe_size(++run));
}
return (int)(&i);
}
int main() {
int x, y;
double d;
char c;
int a = 4;
int b = 5;
int we = 6;
int e = 123123;
int hmm = 34453;
int lol = 45;
int asd = 23;
x = 1;
y = g(x);
d = f(x, y, x-y);
c = 'a';
printf("%d", stackframe_size(0));
}
I am running the function I obtained from another thread to find the call stack size and it always seems to return 48...is there another way to find out or is this the only way?

Resources