Converting a string into an array of characters - c

Am trying to convert user's input of at least 17 characters into an array. Say for example the user's input is 25281582252, by using x = arr[1] , 5 is assigned to variable x.
I've not had success yet. I get a "undefined reference to log10" with gcc on linux. Here is my code
#include <stdio.h>
#include <math.h>
int main(){
int x;
printf("enter x");
scanf("%d",x);
int numOfDigits = log10(x) + 1;
char* arr = calloc(numOfDigits, sizeof(char));
for(int i=0;i<numOfDigits;i++,x/=10){
arr[i] = x % 10;
}
printf("first num: %d",arr[0]);
return 0;
}
Thanks in advance

I get a "undefined reference to log10"
You need to link your program with the math library using -lm.
But this is just a start. Fix the following issues:
a) allocate extra character for null string terminator if you want your string to be properly terminated.
b) scanf("%d",x); requires pointer to x
c) int variable cannot store 17 numbers, use long int
d) you cannot store int into char array, your digit has to be converted to ASCII char.
f) your algorithm stores characters in a reverse order, you need to reverse your string
e) allocated memory has to be freed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void reverse_in_place(char * str, size_t len) {
size_t i, j;
for (i = 0, j = len - 1; i < j ; i++, j--) {
char a = str[i];
char z = str[j];
str[i] = z;
str[j] = a;
}
}
int main(void){
long int x;
int i;
printf("enter x:\n");
scanf("%ld",&x);
int numOfDigits = (int) (log10(x) + 1);
printf("numOfDigits = %d\n", numOfDigits);
char* arr = calloc(numOfDigits + 1, 1);
for(i=0; i < numOfDigits; i++){
arr[i] = (char) ((x % 10) + '0');
printf(" %c", arr[i]);
x /= 10;
}
reverse_in_place(arr,strlen(arr));
printf("\nFirst num is: %c in string %s",arr[0], arr);
free(arr);
return 0;
}
Output:
enter x:
451236789012345678
numOfDigits = 18
8 7 6 5 4 3 2 1 0 9 8 7 6 3 2 1 5 4
First num is: 4 in string 451236789012345678

Related

Unexpected output for this following code [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 2 years ago.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int a1(int *a)
{
int middleItem;
int midIndex;
if (a == NULL || sizeof(a) % 2 == 0)
return 0;
midIndex = sizeof(a) / 2 ;
middleItem = a[midIndex];
for (int i=0; i<sizeof(a); i++)
{
if (i != midIndex && middleItem >= a[i])
return 0;
}
return 1;
}
int main()
{
int a[] = {9};
for (int i=0; i<sizeof(a); i++)
{
a1(a[i]);
}
return 0;
}
An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element.
output:
returns 1 if it is a centered array, otherwise, it returns 0.
sizeof(a) is number of bytes in a and it is not necessarily same as the number of elements in the array a.
It is even worse in the function a1: now sizeof(a) is the size of pointer and you cannot get number of elements from that, so you have to pass it separately.
Passing a[i] as the first argument of a1 is wrong because a[i] is an integer while a pointer is required for the argument.
You will want to output what the function returned.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int a1(int *a, int size)
{
int middleItem;
int midIndex;
if (a == NULL || size % 2 == 0)
return 0;
midIndex = size / 2 ;
middleItem = a[midIndex];
for (int i=0; i<size; i++)
{
if (i != midIndex && middleItem >= a[i])
return 0;
}
return 1;
}
int main()
{
int a[] = {9};
int size = sizeof(a) / sizeof(*a);
printf("%d\n", a1(a, size));
return 0;
}

How to bitshift an array of ints?

I have an int array of size 50 and the first 49 'slots' are filled and I want to move each of the 49 elements of the array one position along so that the first element in the array is now free.
Is there a way to bit shift the entire array 32 bits? like:
array[0] >(49)> 32;
some random made up notation... but I hope it conveys what I am looking for
If you want to take the long way home...
#include <stdio.h>
int main(void)
{
int array_size = 5;
int array[] = {5, 1, 2, 3, 4};
int i;
for (i = array_size - 2; i >= 0; i--)
{
array[i+1] = array[i];
if (i == 0)
array[i] = 0; //whatever you want
}
// not necessary, just print the change
int j;
for (j = 0; j < array_size; j++)
printf("%d ", array[j]);
printf("\n");
return 0;
}
As #COLDSPEED suggested in the comments, memmove does very close to what you are expecting.
void *memmove(void *str1, const void *str2, size_t n)
NOTE: n is the total size in bytes to move. From moving 32 bits you might want to make space for 1 int I guess. (size of int is machine dependent). So, with memmove you can shift 1 byte. Not 1 bit.
And the main purpose of memmove is just to copy. Hence it should not be any better than straight forward copying. Both should take O(n) times.
Conventional method:
for (i = 5; i > 0; i--)
arr[i] = arr[i-1];
arr[0] = 5;
Here is a sample code, using memmove doing the same thing:
#include <stdio.h>
#include <string.h>
int main ()
{
int i;
int arr[5] = {1, 2, 3, 4};
// Printing before state
for (i = 0; i < 4; i++)
printf ("%d ", arr[i]);
printf ("\n");
// The shift operation
memmove(arr+1, arr, 4*sizeof(int));
// Inserting at the beginning
arr[0] = 5;
// Printing after state
printf("After memmove:\n");
for (i = 0; i < 5; i++)
printf ("%d ", arr[i]);
printf ("\n");
return 0;
}
Output:
1 2 3 4
After memmove:
5 1 2 3 4
Here is an article if you want to learn more about mmove: memmove-in-c/c++

C program - How to check array elements [duplicate]

This question already has answers here:
C sizeof a passed array [duplicate]
(7 answers)
Closed 6 years ago.
I have a function repsEqual that takes an array and integer and returns 1 if the array contains only digits of the number in the same order that appear in the same number. Otherwise it returns 0.
int repsEqual(int a[], int len, int n)
If a is {3,2,0,5,3} and n is 32053 return 1 because the array contains only the digits of the number in same order as they are in the number.
If a is {0,3,2,0,5,3} and n is 32053 return 1; we can ignore leading zeros.
I tried like this
int repsEqual(int a[], int len, int n)
{
int len = sizeof(a)/sizeof(a[0]);
//storing elements in array
for(int i=0;i<len;i++)
{
scanf("%d", &a[i]); //eg storing:3 2 0 5 3
}
//asking user integer number and storing in next array
scanf("%d",&a2[num]);//eg 32053
}
Now I need to check if a2 elements are in same order as a1, but do not know how to get started.
This is what you want
int repsEqual(int a[], int len, int n)
{
for (int i = 0; i < len; i++)
{
if (a[len - i - 1] == n % 10)
n /= 10;
else
return 0;
}
//For cases where your number-length is longer than your array length
if (n != 0) return 0;
return 1;
}
First you have your array, say like a[5] = { 5, 2, 3, 1, 4}
Basically what i do is looping the array from end to start, thats a[len - i - 1]
Then i check it with the last character of n thats n%10
So example with n = 52314, the first if statement check if (52314 % 10) which is 4 equal with a[4] which is also 4
if the 2 character match then the loop continue first by remove the last character of n: 52314 / 10 = 5231.
And the next loop will check for 5231 % 10 and a[3]
else the loop break mid-way and return 0 indicate that a mis-match is found
finally after all the character in array is checked and no mismatch is found, it will return 1, as the pattern match
Note: a function should only does what its name says
In your case, check if an array and an integer have the same pattern
User input should be put outside somewhere else, after you have the inputs (the array, the len, and n) you then pass-in to repsEqual for checking
Try matching the number (n) backwards against the array 'a'. To do this you'll want to modulus the smallest digit from 'n', by getting the remainder from dividing by 10. Then remove the smallest digit from 'n' by dividing by 10.
int repsEqual(int a[], int len, int n)
{
int i;
int temp;
if (0 == len || NULL == a)
return 0; // no array, or elements, doesn't match a real number (n).
temp = n;
for (i = len - 1; i >= 0; --i)
{
if (a[i] != (temp % 10))
return 0; // remainder mismatch against array element.
temp = temp / 10; // removes the smallest digit.
}
return 1;
}
By modulus 10 on your n you get the remainder of dividing by 10. IE 452 % 10 = 2. Then by dividing be ten we remove the smallest digit IE 452 / 10 = 45.
This seems to be some homework, haha. Anyway I gave u a quick/ugly sample to start with.
#include <stdio.h>
int repsEqual(int a[],int len , int n)
{
char str[100];
sprintf(str, "%d", n);
int i;
int nonzeroIndex;
for(i=0; i<len; i++){
if (a[i] != 0)
break;
}
nonzeroIndex = i;
printf("nonzeroIndex is %d\n", nonzeroIndex);
for(i= nonzeroIndex; i <len; i++){
if (a[i] != str[i - nonzeroIndex] - 48) {
printf("diff at %d\n", i);
return 0;
}
}
return 1;
}
int main()
{
int a[5];
a[0] = 0;
a[1] = 2;
a[2] = 0;
a[3] = 5;
a[4] = 3;
int output = repsEqual(a, 5, 2053);
printf("result: %d\n", output);
}

Walk-through of a simple c program

I have this question to walk through and show the output when this program is run. The one thing I don't understand is how f is found to be four or even found at all.I know the correct answer is
7 falcon 3
9 RK 4
_
I just dont know how they found the f value to be 4 ,once i have that I can do the rest fine
#include <stdio.h>
#include <string.h>
void falcon(int f);
char a[20];
int main() {
int i, j;
a[3] = 'G';
a[1] = 'K';
i = 3 + 2 * 3;
j = 4;
a[2] = 'Y';
falcon(j);
printf("%d %s %d\n", i, a, j);
}
void falcon(int f) {
int j;
j = 11 % f;
printf("%d falcon %d\n", f+3, j);
a[2] = '\0';
a[0] = 'R';
}
Let's walk through the program together (with some of the irrelevant bits cut out).
#include <stdio.h>
#include <string.h>
void falcon(int f);
char a[20];
int main() {
int i, j;
j = 4;
falcon(j); // in other words, falcon(4). Now, let's go down to the
// falcon function where the first argument is 4.
printf("%d %s %d\n", i, a, j);
}
void falcon(int f) { // Except here we see that in this function,
// the first argument is referred to by 'f',
// which, as we saw, is 4.
int j;
j = 11 % f; // here, j is equal to the remainder of 11 divided by
// f, which is 4.
printf("%d falcon %d\n", f+3, j);
}
Now you see why code should not have is and js for variable names except in probably, loops.
Anyways,
char a[20]; on the top says that a is a globally declared character array.
int main()
{
int i, j; // declares two local stack variables, i and j
a[3] = 'G'; // sets 4th location in 'a'(remember, arrays start at 0) to 'G'{useless}
a[1] = 'K'; // sets 2nd location in 'a' array to 'K'
i = 3 + 2 * 3; // i is now 9 {remember, multiplication before addition}
j = 4; // j is now 4
a[2] = 'Y'; // a[2] is now 'Y'
falcon(j); // call to falcon, with argument 4, explained next
printf("%d %s %d\n", i, a, j); // prints "9 RK 4"
//return 0; -- this should be added as part of 'good' practices
}
void falcon(int f)
{
// from main(), the value of 'f' is 4
int j; // declares a local variable called 'j'
j = 11 % f; // j = 11 % 4 = 3
printf("%d falcon %d\n", f+3, j); // prints 7 falcon 3
a[2] = '\0'; // a[2] contains null terminating character, overwrites 'Y'.
a[0] = 'R'; // sets a[0] to 'R'. At this moment, printf("%s",a); must yield "RK"
}

All Integers have the same value

So I am working on some homework, in which I have to create a global array of 500 random integers between 0 and 99. Then, I have to count how many are greater than 75, and how many are less than 50.
Here is my code:
#include <stdlib.h>
#include <stdio.h>
static int ARRAY[500];
static char str[1];
void main() {
int i = 0;
for (i = 0; i < 500; i++) {
int r = rand() % 99;
ARRAY[i] = r;
}
int gt75 = count75();
int lt50 = count50();
printf("%d\n", str, gt75);
printf("%d\n", str, lt50);
}
int count75() {
int i = 0, counter = 0;
for (i = 0; i < 500; i++) {
int n = ARRAY[i];
if (n > 75) {
counter += 1;
}
}
return counter;
}
int count50() {
int i = 0, counter = 0;
for (i = 0; i < 500; i ++) {
int n = ARRAY[i];
if (n < 50) {
counter += 1;
}
}
return counter;
}
However, after compiling and running my program, I get the following output:
4225008
4225008
This can't be right, as the list should only have 500 elements in the first place. What am I doing wrong?
You have two errors.
First, int r = rand() % 99; should be int r = rand() % 100; Otherwise you just get numbers between 0 and 98.
Second, your printf statements are odd. They should be:
printf("Greater than 75: %d\n", gt75);
printf("Less than 50: %d\n", lt50);
In the current printf statements, the str is cast to an int, which is interpreting the str pointer as an int, thus your strange output.
You're printing a char array with printf using "%d", which is for printing integers. Use "%s" for printing char arrays:
printf("%s\n", str, gt75);
Or, if you're trying to print the value of gt75 as an integer:
printf("%d\n", gt75);
I do not know why you would pass str in this case, though.
When you use "%d", you are telling printf to interpret the input as an int. Since str is actually a char array, it does not output correctly. Instead, you're printing the memory location of str, which is the value of an array.
You are always printing the value of str, which is not an int.

Resources