How to print user input array in one line - c

Trying to print out the user input of the array online but ended up in prints in one element at a time.
The following code aims to compute the sum of elements in the n number of ArrayList:
// let int count be counter
int count=0;
int inputNum;
// calculate the length of the array
int len;
for (int i=0; i<numOfLines; i++)
{
count++;
printf("Enter line %d: \n", count);
for (int j=0; j<numOfLines; j++)
{
scanf("%d", &inputNum);
printf("DEBUG:input number %d \n", inputNum++);
if (inputNum != 0)
{
int arrNum[]= {inputNum++};
len = sizeof(arrNum)/sizeof(arrNum[0]);
printf("Total: %d \n", len);
}
}
}
Output:
Enter number of lines:
2
Enter line 1:
3 2 3 4
DEBUG:input number 3
Total: 1
DEBUG:input number 2
Total: 1
Enter line 2:
DEBUG:input number 3
Total: 1
DEBUG:input number 4
Total: 1
Correct sample output:
Enter number of lines:
2
Enter line 1:
3 2 3 4
Total: 9
Enter line 2:
4 1 2 3 4
Total: 10

It seems the first number of each line is the number of data in that line. Use that information.
// let int count be counter
int count=0;
int inputNum;
for (int i=0; i<numOfLines; i++)
{
count++;
printf("Enter line %d: \n", count);
int sum = 0;
scanf("%d", &inputNum);
for (int j=0; j<inputNum; j++)
{
int value;
scanf("%d", &value);
printf("DEBUG:input number %d \n", value);
sum += value;
}
if (inputNum != 0)
{
printf("Total: %d \n", sum);
}
}

Related

Print Odd numbers using 2 arrays in a function

The point of my code is to print all the odd numbers inputted each array using function.
#include<stdio.h>
void printOdd(int arr1[], int arr2[], int s1, int s2) {
int count = 0;
for (int i = 0; i < s1; i++) {
if (arr1[i] % 2 != 0) {
printf("%d", arr1[i]);
count++;
if(count<(s1+s2)/2)
{
printf(", ");
}
}
}
for (int i = 0; i < s2; i++) {
if (arr2[i] % 2 != 0) {
printf("%d", arr2[i]);
if(count<(s1+s2)/2-1)
{
printf(", ");
}
}
}
}
int main(void)
{
int s1, s2;
printf("Enter first array size: ");
scanf("%d", &s1);
int arr1[s1];
printf("Enter second array size: ");
scanf("%d", &s2);
int arr2[s2];
printf("Enter first array values: ");
for(int x = 0; x < s1; x++)
{
scanf("%d", &arr1[x]);
}
printf("Enter second array values: ");
for(int y = 0; y < s2; y++)
{
scanf("%d", &arr2[y]);
}
printOdd(arr1, arr2, s1, s2);
}
These are the expected outputs
Enter first array size: 5
Enter second array size: 5
Enter first array values: 1 2 3 4 5
Enter second array values: 6 7 8 9 10
1, 3, 5, 7, 9
Enter first array size: 3
Enter second array size: 3
Enter first array values: 5 6 10
Enter second array values: 12 41 36
5, 41
Enter first array size: 4
Enter second array size: 3
Enter first array values: 1 2 3 5
Enter second array values: 3 2 1
1, 3, 5, 3, 1
My problem is everytime I input numbers, the result is that there is always a comma at the end, here's my output
Enter first array size: 3
Enter second array size: 3
Enter first array values: 5 6 10
Enter second array values: 12 41 36
5, 41,
https://gyazo.com/9d544951a3572666a3b6b0dc8620d9cc
the link is a picture of expected output and my output
The simplest thing to do is to print the comma before printing your value, and only when count is non-zero. The reason is that you never know if there will be a next odd number, but you do know when there was a previous one. So you should always leave your output with no trailing comma.
void printOdd(int arr1[], int arr2[], int s1, int s2) {
int count = 0;
for (int i = 0; i < s1; i++) {
if (arr1[i] % 2 != 0) {
if (count > 0) printf(", ");
printf("%d", arr1[i]);
count++;
}
}
for (int i = 0; i < s2; i++) {
if (arr2[i] % 2 != 0) {
if (count > 0) printf(", ");
printf("%d", arr2[i]);
count++;
}
}
}

How to read tetrads (groups of four integers) and save it in 2d array?

This is the function that I have written:
int read_data(int (*p)[0][0])
{
int i,j;
for (i=0;i<N;i++)
{
for (j=0;j<1;j++)
{
printf("give first number:");
scanf("%d",&(*p)[i][j]);
printf("give second number:");
scanf("%d",&(*p)[i][j]);
printf("give third number:");
scanf("%d",&(*p)[i][j]);
printf("give forth number:");
scanf("%d",&(*p)[i][j]);
}
}
for (i=0;i<N;i++)
{
for (j=0;j<4;j++)
{
printf("%d [%d],[%d]\n",(*p)[i][j],i,j);
printf("%d [%d],[%d]\n",(*p)[i][j],i,j);
printf("%d [%d],[%d]\n",(*p)[i][j],i,j);
printf("%d [%d],[%d]\n",(*p)[i][j],i,j);
}
}
}
I have to solve an exercise. One part of the problem is to read tetrads of integers (groups of four integers) and save it in an array. I tried many different approaches, but none seem to work.
Thanks in advance.
Here is a very simple solution.
Numbers are assigned directly in the 2 dimension array in a single scanf (you can use indices but it is not really needed because you know you can have only 4 numbers).
The function scanf_tetrad takes the array as parameter.
Code:
#include <stdio.h>
#include <stdlib.h>
void scanf_tetrad(int p[2][2])
{
printf("Enter 4 numbers:");
scanf("%d %d %d %d", &p[0][0], &p[0][1], &p[1][0], &p[1][1]);
}
int main()
{
int ia[2][2];
int i,j;
scanf_tetrad(ia);
printf("You entered: ");
for (i=0; i < 2; i++)
for(j=0; j < 2; j++)
printf("%d ", ia[i][j]);
printf("\n");
return 0;
}
Execution:
./tetrad
Enter 4 numbers:54634 456 7486743 4546
You entered: 54634 456 7486743 4546
Here is simple program to read multiple tetrads:
it firsts asks to enter the number of tetrad
it allocates a dynamic array tt which in array of tetrad arrays
it allocates each array tetrad in tt
it reads each tetrad array with the same above function
it displays the tetrad array items using a formula to access array item address [x,y] which is x * (number of columns) + y. Note that this code may not be 100% C standard compliant.
metrad.c
#include <stdio.h>
#include <stdlib.h>
void scanf_tetrad(int p[2][2])
{
printf("Enter 4 numbers:");
scanf("%d %d %d %d", &p[0][0], &p[0][1], &p[1][0], &p[1][1]);
}
int main()
{
int i,j, idx;
int ttnb;
int ***tt, **ctt;
printf("Enter number of tetrad:");
scanf("%d", &ttnb);
tt = malloc(ttnb * sizeof (int [2][2]));
if (tt == NULL)
{
perror("malloc");
return 1;
}
for (idx=0; idx < ttnb; idx++)
{
tt[idx] = malloc(sizeof (int [2][2]));
if (tt[idx] == NULL)
{
perror("malloc");
return 1;
}
}
for (idx=0; idx < ttnb; idx++)
{
scanf_tetrad((int (*)[2])tt[idx]);
}
printf("You entered:\n");
for (idx=0; idx < ttnb; idx++)
{
printf("tetrad %d: ", idx);
ctt = tt[idx];
for (i=0; i < 2; i++)
for(j=0; j < 2; j++)
{
printf("%d ", *((int*)ctt + (i * 2) + j));
}
printf("\n");
}
return 0;
}
Example of execution:
./mtetrad
Enter number of tetrad:4
Enter 4 numbers: 1 2 3 4
Enter 4 numbers:5 6 7 8
Enter 4 numbers:9 10 11 12
Enter 4 numbers:13 14 15 16
You entered:
tetrad 0: 1 2 3 4
tetrad 1: 5 6 7 8
tetrad 2: 9 10 11 12
tetrad 3: 13 14 15 16

How to print this series?(1 \n 2 3 \n 4 5 6 \n 7 8 9 10... ... ...)

I am trying to print the following series: 1 2 3 4 5 6 7 8 9 10 ... ... ...The input of my program contains a single integer n, which determines the number of lines to print.
I've tried to code it but got the following output:
12 33 4 54 5 6 7... ... ...
#include<stdio.h>
int main()
{
int n,i,j,t,m;
scanf("%d", &n);
for(i=1;i<=n;i++)
{
for(j=i,t=1;t<=i;j++,t++)
{
printf("%d ",j);
}
printf("\n");
}
}
To print those numbers, you'll want a counter that starts at 1, increases by 1 every print and is never reset by anything. Adjust your loop like this:
int main()
{
int n, i, j, t = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++, t++)
{
printf("%d ", t);
}
printf("\n");
}
}
Note how t is set to 1, and just gets increased by t++ without resetting like you previously did. Also, you should be printing t, not j.
You should maintain separate counters for the numbers and the number of numbers per line.
int nr = 1, target;
int nrsperline = 1, i;
scanf("%d", &target);
while (nr <= target) {
for (i = 0; i < nrsperline; i++) {
printf("%d ", nr++);
}
printf("\n");
nrsperline++;
}

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

Resources