How to put an integer in a individual number by arry? - c

I want to input an integer such as 123454321. Then I want to print it in
this form:1 2 3 4 5 4 3 2 1.
Here is my code:
#include <stdio.h>
int main(void)
{
int A[100];
int i, input, current;
printf("Input n:");
scanf("%d",&input);
printf("\n");
for(i=1; i!=0; i++){
A[i]=input%10;
input=input/10;
printf("%d ",A[i]);
current++;
}
return 0;
}

You can put your input into your array like you do and display it, but the input will be reverse.
In case of intput: 12345
Value will be stored like this: A[0] = 5, A[1] = 4, ...
To change that you will have to display A[] from the end to the start. (already answered by chux)
Or you can store your input into A[] from the end to the start and after simply display it:
Example below:
#include <stdio.h>
int main(void)
{
int A[100];
int i, input, len, nb;
printf("Input n:");
scanf("%d",&input);
printf("\n");
nb = input; //I do a save of input.
for(len = 0; nb != 0; len++){ //Calculating the size of the input
nb = nb / 10; //
} //
len--;
for(int z = len; input != 0; z--){ //I copy the input into A.
A[z] = input % 10; //
input = input / 10; //
}
for(i = 0; i <= len; i++) // I display A
printf("%d ",A[i]); //
return 0;
}
EDIT:
By the way your for:
for(i=1; i!=0; i++){
A[i]=input%10;
input=input/10;
printf("%d ",A[i]);
current++;
}
Will infinite loop because i is never equals to 0 and the case A[0] of your array will not be used because ì start at 1.

Determine the values for A[] looping in one direction and then print the values in the other loop direction.
Let us assume input >= 0.
A do loop is useful here to handle the case of input == 0 to print "0".
i = 0;
do {
A[i] = input%10;
input = input/10;
i++;
} while (input);
Now print looping the other way
while (i) {
printf("%d ", A[--i]);
}
printf("\n");

Related

How to write a program to delete an element in an array using C language? [duplicate]

I wrote the following program to delete an array element entered by the user.
#include <stdio.h>
#include <conio.h>
void main() {
int j, i, a[100], n, key, l;
clrscr();
printf("Enter the number of elements:");
scanf("%d", &n);
printf("\nEnter the elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\nEnter the element to delete:");
scanf("%d", &key);
l = n; //Length of the array
for (i = 0; i < l; i++) {
if (a[i] == key) {
for (j = i; j < l; j++)
a[j] = a[j + 1];
l--; //Decreasing the length of the array
}
}
printf("\nThe new array is \n");
for (i = 0; i < l; i++)
printf("%d ", a[i]);
getch();
}
It works fine for most inputs but when the input is something like: 1 2 2 3 5 (here 2 repeats consecutively) and the element to be deleted is 2, the output is 1 2 3 5.
How can I modify the program such that all instances of the entered element is removed?
After l-- put i-- too as shown below
if(a[i]==key)
{
for(j=i;j<l;j++)
a[j]=a[j+1];
l--; //Decreasing the length of the array
i--; //check again from same index i
}
Other posters have given you 2 solutions ... I think understanding why it happens is good too :)
Let's take your example 1, 2, 2, 3, 5 and follow the code line by line
i = 0; /* first time through the loop; i "points" to 1 */
if (a[i] == 2) ... /* nope; next loop */
i = 1;
if (a[1] == 2) ... /* yes! let's go inside the if */
/* move all elements back
** and "decrease" array length */
/* array is now 1, 2, 3, 5 */
/* next loop */
i = 2;
if (a[i] == 2) ... /* nope; OH! Wait ...
** a[1] is the new 2 and it wasn't checked */
If you don't care about the order of the elements in the array, you can move the last element of the array into the newly formed gap (cunningly reducing the length of the array by one). This can be vastly more efficient than shunting the elements down: in computer science term this makes deleting an element O(1) rather than O(N).
a[i] = a[--l];
If your i index is looping over the array, you'll want to loop over this element again:
a[i--] = a[--l];
For example, to remove all elements '3' from an array of length 'l':
for (i = 0; i < l; ++i) {
if (a[i] == 3) {
a[i--] = a[--l];
}
}
If you do care about the order of the elements in the array, it's most efficient to use memmove rather than move elements by hand. It's designed to be used where the source and destination memory overlap.
memmove(a + i, a + i + 1, sizeof(a[0]) * (l - i - 1));
Change "if" to "while":
for(i=0;i<l;i++)
{
while (i<l && a[i]==key)
{
for(j=i;j<l;j++)
a[j]=a[j+1];
l--; //Decreasing the length of the array
}
}
use a new array.
int array[l];
int k=0;
for(i=0;i<l;i++)
{
if(a[i]!=key)
{
array[k]=a[i];
k++;
}
}
#include<stdio.h>
int main(){
int size;
int array[20];
int delete_pos;
int i;
printf("Enter the Size of the Array :");
scanf("%d",&size);
for(i=0;i<=size-1;i++){ //no of elements taken are 1 less than size of the array asked.
printf("\nEnter the element[%d] :",i+1);
scanf("%d",&array[i]);
}
printf("\nEnter the Position of the array to be deleted :");
scanf("%d",&delete_pos);
for(i=delete_pos-1;i<=size;i++){ //every element of the array is replaced by array on next position.
array[i]=array[i+1];}
size=size-1; // Reducing the size of the array as one element is deleted.
printf("Your new array is \n");
for(i=0;i<=size-1;i++){ //printing the entire new array.
printf("%d ",array[i]);
}
printf("\n\n");
return 0;
}
Your method with 2 nested for loops is too complicated. You can simple scan the array with an index i and copy all elements different from key with a different index len. The resulting array length is the final value of len.
Here is a modified version:
#include <stdio.h>
#include <conio.h>
int main(void) {
int a[100];
int i, n, key, len;
clrscr();
printf("Enter the number of elements: ");
if (scanf("%d", &n) != 1) {
printf("invalid input\n");
return 1;
}
if (n < 0 || n > 100) {
printf("invalid number of elements\n");
return 1;
}
printf("\nEnter the elements:\n");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
printf("\nEnter the element to delete: ");
if (scanf("%d", &key) != 1) {
printf("invalid input\n");
return 1;
}
for (i = len = 0; i < n; i++) {
if (a[i] != key)
a[len++] = a[i];
}
printf("\nThe new array is:\n");
for (i = 0; i < len; i++)
printf("%d ", a[i]);
printf("\n");
getch();
return 0;
}
Notes:
The prototype for main without arguments is int main(void) and it is considered good style to return 0 for success.
always test the return value of scanf(). This prevents many bugs and undefined behavior for invalid input. It also saves a lot of time looking in the wrong places when input was just invalid.
avoid naming a variable l as it looks too close to 1 in many fixed pitch fonts.
always terminate the program output with a newline.

Find the longest arithmetic progression from an array

I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].
#include <stdio.h>
void main()
{
int array[100], i, num,diff;
printf("Enter the size of an array \n");
scanf("%d", &num);
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
printf("\n Numbers in a.p: ");
for (i = 0; i < num; i++) {
diff = array[i+1]-array[i];
if (array[i]-diff == array[i+1]-diff);
{
printf("%d, ", array[i]);
}
}
printf("\n Common difference:%d", diff);
}
like this
#include <stdio.h>
int main(void){
#if DEBUG
int array[] = {5,1,2,4,6,8,12};
int num = sizeof(array)/sizeof(*array);
int i, diff;
#else
int array[100], i, num,diff;
printf("Enter the size of an array \n");
scanf("%d", &num);
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
#endif
int j, len, longest_len = 2, longest_i = 0;
for (i = 0; i < num - longest_len; i += len-1) {
diff = array[i+1]-array[i];
for(j = i+2; j < num && array[j-1]+diff == array[j]; ++j);
len = j - i;
if(longest_len < len){
longest_len = len;
longest_i = i;
}
}
printf("\n Numbers in a.p: ");
diff = array[longest_i+1] - array[longest_i];
printf("[ ");
for(i = 0; i < longest_len; ++i){
printf("%d", array[longest_i + i]);
if(i == longest_len-1)
printf(" ]\n");
else
printf(", ");
}
printf("\n Common difference:%d", diff);
}
Since this seems to be a homework or challenge I will only help by solving your immediate problems, caused by very strange code.
Here is code which at leat detects the progressions correctly.
You can yourself count the length, store the longest length and its index, then print that sequence after parsing all the array.
There are two assumptions here, which you might want to avoid for challenge/homework:
no identical numbers entered
no overlapping progressions,
i.e. no number is the last of one and the first of next progression
The representation of more than one sequence in the output is a little jittery (missing ")"), but that is not relevant for finding and exclusively printing the longest one.
I did not bother about your ratio output, no idea what that is supposed to be.
Code:
#include <stdio.h>
// avoid a warning
int main() {
int array[100], i, num, diff=0, lastdiff=0, first=1;
printf("Enter the size of an array \n");
// for good code, this should check the result
scanf("%d", &num);
// in case of scaf-failure, cleanup here for good code
// asking for the number of elements
// and then relying on that number to be entered
// is less elegant than checking for and end condition
// like EOF or negative input
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
// for good code, this should check the result
scanf("%d", &array[i]);
// in case of scaf-failure, cleanup here for good code
}
printf("\n Numbers in a.p: ");
for (i = 1; i < num; i++) {
lastdiff=diff;
diff = array[i]-array[i-1];
if (diff==lastdiff)
{ if(first==1)
{ first=0;
printf("(%d, %d",array[i-2], array[i-1]);
}
printf(", %d", array[i]);
} else
{ first=1;
}
}
printf(")\n Ratio:%d", diff);
// avoid a warning
return 0;
}
There are a number of ways to approach this challenge. You can either check each diff against each value in the array or work the other way around. Given you are not sorting the values, you may benefit by nesting the check of values within your loop over all possible diffs. Something similar to the following works:
#include <stdio.h>
int main (void) {
int a[] = {5, 1, 2, 4, 6, 8, 12},
n = sizeof a / sizeof *a,
startidx = 0,
maxlen = 0;
for (int d = 1; d < n; d++) { /* loop over diffs */
int idx = -1,
len = 1;
for (int i = 1; i < n; i++) /* loop over values */
if (a[i - 1] + d == a[i]) {
if (idx < 0) /* if index not set */
idx = i - 1; /* set to 1st index */
len++; /* increment length */
}
if (idx >= 0 && len > maxlen) { /* if progression found */
maxlen = len; /* save length */
startidx = idx; /* save start index */
}
}
printf ("longest progression: '%d' elements.\n", maxlen);
for (int i = 0; i < maxlen; i++)
printf (i ? ", %d" : "%d", a[startidx + i]);
putchar ('\n');
return 0;
}
Example Use/Output
$ ./bin/maxprogression
longest progression: '4' elements.
2, 4, 6, 8
Investigate several ways to approach it, and finally settle on the one that makes the most sense to you. You can work on optimizing later.
As far as the code you posted goes, always validate all user input by, at minimum, checking that the number of expected conversions to type took place, e.g.
if (scanf("%d", &num) != 1) {
fprintf (stderr, "error: input conversion failed for 'num'.\n");
return 1;
}
You would do the same in your values loop. Let me know if you have any questions. Good luck with your coding.
Following is the complete working code. You can see it working here:
#include <stdio.h>
int main()
{
int array[100], i, num,diff, resDiff, startIndx, resStartIndx, countCur, countPre;
printf("Enter the size of an array \n");
scanf("%d", &num);
printf("Enter the elements of the array \n");
for (i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
//Now code changes
startIndx =0, resStartIndx=0, countPre=0, resDiff=0;
for (i = 0; i < num; /*No increment required here*/) {
countCur =0;
startIndx=i;
countCur++;
if(++i < num)
{
diff = array[i] - array[startIndx];
countCur++;
i++;
while((i < num) && (diff == (array[i] - array[i-1])))
{
countCur++;
i++;
}
if(countCur > countPre)
{
resStartIndx = startIndx;
countPre = countCur;
resDiff = diff;
}
}
}
countPre += resStartIndx;
printf("\n Numbers in a.p: ");
for (i = resStartIndx; i < countPre; i++) {
printf("%d, ", array[i]);
}
printf("\n Common difference:%d", resDiff);
return 0;
}

How to print the number of elements in an array?

How do I make it so I can enter 10 or less elements into an array, and then print the number or elements??
#include <stdio.h>
#define MAX_SIZE 10
int main()
{
int a[MAX_SIZE], i;
printf("Enter up to %d different numbers seperated by spaces: \n", MAX_SIZE);
for(i=0; i < MAX_SIZE; i++)
scanf("%d", &a[i]);
printf("Length: %lu\n", sizeof(MAX_SIZE));
return 0;
}
Please close the for loop while storing data and add another loop before print.
Check this code.
This code takes upto MAX_SIZE [10 here] integer inputs and print the number of elemnts. You can stop the scanf() using CTRL + D [EOF].
IMHO, this is the logical approach to end the input, because if you want to end the input based on some particular number, you can't have that number stored in your array.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
int main()
{
int count = 0;
int arr[MAX_SIZE] = {0, }; //initialize the array
printf("Enter the numbers one by one ==> \n");
for (count = 0; count < MAX_SIZE; count ++)
{
if (scanf("%d", &arr[count]) == EOF)
break;
}
printf("Number of elements into the array %d\n", count);
return 0;
}
Try This
int main()
{
int a[MAX_SIZE], i,count=0;
printf("Enter up to %d different numbers seperated by spaces: \n", MAX_SIZE);
for(i=0; i < MAX_SIZE; i++)
{
scanf("%d", &a[i]);
if(a[i] == -1) // Use any number to break the loop
break; // Break the loop
count++; // Count number of elements
}
printf("Length: %d", count ); //Print number of elements
return 0;
}
You can do it as following, Enter 0 as input where you want to stop entering more elements.
#include <stdio.h>
#define MAX_SIZE 10
int main()
{
int a[MAX_SIZE], i;
int count = 0;
printf("Enter up to %d different numbers seperated by spaces: \n", MAX_SIZE);
for(i=0; i < MAX_SIZE; i++)
{
scanf("%d", &a[i]);
if(!a[i])
break;
count++;
}
printf("Length: %lu\n", count);
return 0;
}
By using any counter variable you can count the number of scanned elements and using that variable you can print also..
int main()
{
int a[MAX_SIZE], i,count=0;
printf("Enter up to %d different numbers seperated by spaces: \n", MAX_SIZE);
for(i=0; i < MAX_SIZE; i++)
{
scanf("%d", &a[i]);
if(a[i] == 0) // Use any number for breaking loop
break; // break the loop
count++; // for Counting number of elements
}
printf("number of scanned elements: %d", count ); //Print number of elements
for(i=0;i<count;i++) // for printing upto scanned numbers
printf("%d\n",a[i]);
return 0;
}
We cant find out that which are scanned elements in one array. Because array can hold garbage values. So, maintain any counter variables for counting the number of elements scanning when you want to scan less than actual array boundary.
Your size will always be MAX_SIZE * sizeof(int); (which is 10 * 4-bytes per int in your case). Test by replacing your printf with:
printf("Length: %d\nsize : MAX_size * sizeof (int): %lu\n", MAX_SIZE, MAX_SIZE * sizeof (int));
output:
Length: 10
size : MAX_SIZE * sizeof (int): 40
Note: The storage size for an integer can very from hardware-to-hardware, so always use sizeof(int) in your computations.
I apologize, I see, you want a way to enter less than 10 and still print the array:
#include <stdio.h>
#define MAX_SIZE 10
int main()
{
int a[MAX_SIZE] = {0};
int i = 0;;
int cnt = 0;
printf("Enter up to %d different numbers seperated by spaces (ctrl+d when done): \n", MAX_SIZE);
while (i < MAX_SIZE)
{
if (scanf("%d%*c", &a[i]) < 1)
break;
i++;
}
cnt = i;
i = 0;
printf ("\nPrinting elements using while loop:\n\n");
while (a[i])
{
printf ("a[%d] = %d\n", i, a[i]);
i++;
}
/* or */
printf ("\nPrinting elements using for loop:\n\n");
for (i = 0; i < cnt; i++)
printf ("a[%d] = %d\n", i, a[i]);
return 0;
}
output:
$ ./bin/arrcnt
Enter up to 10 different numbers seperated by spaces (ctrl+d when done):
1 2 3 4 5
Printing elements using while loop:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
Printing elements using for loop:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
You can either keep a count or by initializing your array to zero, you can use a while loop checking for entries. (note: a '0' entered will not work with the while method, so it is only useful for values > 0) Also note: the use of the format string in scanf to consume the trailing newline. This can save you headaches later.
just add these to your code
for (i = 0; i< MAX_SIZE; i++)
{
printf("%d",a[i]);
}
also add curly brackets to your loop
for (i = 0; i<MAX_SIZE; i++)
{
scanf("%d", &a[i]);
}

Average of prime numbers in an array

Well, the problem is the above. To sum it up, it compiles, but I guess my main idea is just wrong. What I'm trying to do with that code is:
I want the person to give us the elements of the array, how many he wants to (with a limit of a 100 elements).
After that, I'm checking what array positions are prime numbers.(ex: position 2,3,5,etc. Not the elements itself).
After that, I'm doing the average of the values in the prime numbers position.
That's it. Any ideas? Keep in mind that I'm on the first period of engineering, so I'm not the best in programming.
The code is below:
#include <stdio.h>
#include <windows.h>
int main(void)
{
int k, i, j, d, v[101], sum, prim, f;
float ave;
i = 0;
while ((i < 101) && (j != 0) )
{
i++;
printf("Set the value of the element %d => ", i);
scanf("%d", &v[i]);
printf("To stop press 0 => ");
scanf("%d", &j);
}
k = 0;
prim = 1;
f = i;
sum = 0;
while (f > 2)
{
if (i % (f - 1) == 0)
{
prim = 0;
}
else
{
k++;
sum = sum + v[f];
}
f = f - 1;
}
med = sum / k;
printf("%d, %d, %d", k, soma, i);
printf("The average is => %f \n", ave);
system("pause");
}
For those wondering, this is what i got after the editing in the correct answer:
int main(void)
{
int v[101];
int n = 0;
int k,j = 0;
int i=0;
int sum = 0;
while( i<100 )
{
i++;
printf ("Set the value of the element %d => ", i);
scanf ("%d", &v[i]);
int x,primo=1;
if (i>1){
for (x=2; x*x<=i; x++) {
if (i % x == 0) primo = 0;
}
if(primo==1)
{
sum = sum+ v[i];
n++;
}
}
printf ("To stop press 0 => ");
scanf ("%d", &j);
if(j == 0)
break;
}
float ave =(sum /n);
printf("%d, %d, %d", n,i,sum);
printf("The average is => %f \n", ave);
system("pause");
}
First lets make a readable method to test if a number is prime; this answer from another SO post gives us a good one:
int IsPrime(int number) {
int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
Second, let's clean your code, and compute a running sum of all the prime numbers encountered so far. Also, we will check the return values of scanf (but we should avoid scanf !)
And third, we add some indentation.
int main(void)
{
int n = 0;
int i = 0;
int j = 0;
int k = 0;
int sum = 0;
while( i<101 )
{
i++;
printf ("Set the value of the element %d => ", i);
if(scanf ("%d", &k) != 1)
continue;
if(is_prime(k))
{
sum += k;
++n;
}
printf ("To stop press 0 => ");
if(scanf ("%d", &j) == 1)
if(j == 0)
break;
}
float ave = sum / (double) n;
printf("The average is => %f \n", ave);
system("pause");
}
Well there are a few things to say. First the easy part: if the max number of integers allowed to read is 100 your variable "v" should be v[100]. This is not a char array, so this array don't need to have an extra element (v[100] will be an array of int that goes from v[0] to v[99]; adjust the loop limit too).
Also, you are checking if the number you have is prime in the variable f, but this var is assigned with the variable i and i is not an element of the array. You want to assign f something like v[i] (for i equal to 0 to the count of numbers read minus one). So you will need 2 loops: the one you are using now for checking if the number is prime, and another one that assigns v[i] to f.
Another thing to say is that you are calling scanf two times for reading, you could just read numbers and store it in a temporary variable. If this number is not zero then you store it in the array and keep reading, else you stop the reading.
By last I strongly recommend you set var names that make sense, use single letters only for the index variables; names like temp, array, max and countnumbers should appear in your code. It will be easier for you and everyone else to read your code, and you will reduce the number of mistakes.
Here's the solution to your problem. Very easy stuff.
/* C program to find average of all prime numbers from the inputted array(you can predefine it if you like.) */
#include <stdio.h>
#include <conio.h>
void main()
{
int ar[100], i, n, j, counter;
float avg = 0, numprime = 0;
printf("Enter the size of the array ");
scanf("%d", &n);
printf("\n Now enter the elements of the array");
for (i = 0; i < n; i++)
{
scanf("%d", &ar[i]);
}
printf(" Array is -");
for (i = 0; i < n; i++)
{
printf("\t %d", ar[i]);
}
printf("\n All the prime numbers in the array are -");
for (i = 0; i < n; i++)
{
counter = 0;
for (j = 2; j < ar[i]; j++)
{
if (ar[i] % j == 0)
{
counter = 1;
break;
}
}
if (counter == 0)
{
printf("\t %d", ar[i]);
numprime += 1;
avg += at[i];
}
}
avg /= numprime;
printf("Average of prime numbers is ℅f", avg);
getch();
}
You just need counter variables like above for all average computations. (Cause we need to know number of prime numbers in the array so we can divide the total of them and thus get average.) Don't worry about typecasting it is being done downwards... This solution works. I've written it myself.
Here is a cut at doing what you wanted. You don't need near the number of variables you originally had. Also, without knowing what you wanted to do with the prime number, I just output when a prime was encountered. Also as previously mentioned, using a function for checking prime really helps:
#include <stdio.h>
// #include <windows.h>
/* see: http://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime */
int IsPrime(unsigned int number) {
if (number <= 1) return 0; // zero and one are not prime
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
int main(void)
{
int i, v[101], sum, pcnt=0, psum=0;
float ave;
i=0;
printf ("\nEnter array values below, use [ctrl + d] to end input\n\n");
printf ("Set the value of the element %d => ", i);
while((i<101) && scanf ("%d", &v[i]) != EOF ){
sum += v[i];
if (IsPrime (v[i]))
psum += v[i], pcnt++;
i++;
printf ("Set the value of the element %d => ", i);
}
ave=(float)psum/pcnt;
printf("\n\n Number of elements : %d\n",i);
printf(" The sum of the elements: %d\n",sum);
printf(" The number of primes : %d\n",pcnt);
printf(" The average of primes : %f\n\n", ave);
return 0;
}
Sample Output:
Enter array values below, use [ctrl + d] to end input
Set the value of the element 0 => 10
Set the value of the element 1 => 20
Set the value of the element 2 => 30
Set the value of the element 3 => 40
Set the value of the element 4 => 51
Set the value of the element 5 => 11
Set the value of the element 6 => 37
Set the value of the element 7 =>
Number of elements : 7
The sum of the elements: 199
The number of primes : 2
The average of primes : 24.000000

Nested for/while loops and arrays, filtering out numbers from an array

int main(void)
{
int i,j=0,k; //initialization
char equation[100]; //input is a string (I think?)
int data[3]; //want only 3 numbers to be harvested
printf("Enter an equation: ");
fgets(equation, 100, stdin); //not so sure about fgets()
for (i = 0; i < equation[100]+1; i++) { //main loop which combs through
//"equation" array and attempts
//to find int values and store
while (j <= 2) { //them in "data" array
if (isdigit(equation[i])) {
data[j] = equation[i]
j++;
}
}
if (j == 2) break;
}
for (k = 0; k <= 2; k++) { //this is just to print the results
printf("%d\n", data[k]);
}
return 0;
}
Hello! This is my program for my introductory class in C, I am trying to comb through an array and pluck out the numbers and assign them to another array, which I can then access and manipulate.
However, whenever I run this I get 0 0 0 as my three elements in my "data" array.
I am not sure whether I made an error with my logic or with the array syntax, as I am new to arrays.
Thanks in advance!!! :)
There are a few problems in your code:
for (i = 0; i < equation[100]+1; i++) { should be something like
size_t equ_len = strlen(equation);
for (i = 0; i < equ_len; i++) {
Whatever the input is, the value of equation[100] is uncertain, because char equation[100];, equation only has 100 element, and the last of them is equation[99].
equation[i] = data[j]; should be
data[j] = equation[i];
I suppose you want to store digit in equation to data.
break; should be deleted.
this break; statement will jump out of the while loop, the result is you will store the last digit in equation to data[0] (suppose you have switched data and equation, as pointed out in #2).
If you want the first three digits in equation, you should do something like
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
printf("%d\n", data[k]); should be printf("%c\n", data[k]);
%d will give the ASCII code of data[k], for example, if the value of data[k] is character '1', %d will print 50 (the ASCII code of '1') instead of 1.
Here is my final code, based on the OP code:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int i,j,k;
char equation[100];
int data[3];
int equ_len;
printf("Enter an equation: ");
fgets(equation, 100, stdin);
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
for (k = 0; k <= 2; k++) {
printf("%c\n", data[k]);
}
return 0;
}
Tested with:
$ ./a.out
Enter an equation: 1 + 2 + 3
1
2
3

Resources