How to get input for arrays whose length is not determined - c

I am supposed to write a program that "quicksort"s a given array of numbers. The problem is , dynamic memory allocation is not allowed and nor am I given the number of "numbers" that are supposed to be inputs of my program.
For instance, here's an input/output example:
INPUT: 0 1 5 3 6 2 4
OUTPUT: 0 1 2 3 4 5 6
But I just can't seem to be able to close my while loop when getting the numbers using scanf(); (I know , scanf() is silly , but I can't use "iostream" either)
Here's the code I was trying to get to work:
int main()
{
int target_arr[1000], l, h, i = 0, c = 0, k = 0;
while (scanf("%d", &target_arr[i]) != EOF)
{
i++;
}
h = i -1;
l = 0;
quick(l, h, target_arr);
print_arr(target_arr, i );
return 0;
}
quick() and print_arr() functions are previously defined and work perfectly well given the proper input.I just don't know how to stop the loop when I'm done inputting.
Any help would be greatly appreciated.

Related

how to get sum of each input printed?

I am new to C and need some help with this basic program. I want the program to print out the sum directly after the input. I tried to put printf("..%d", sum); inside the for brackets and got but program shuts after the first input. It works if I have a scanf("%d", &value); before the For and inside the for brackets but there for I don't get the format I want.
I want the values to be printed vertical, left side should be inputs and right side should be output as u can see in the image.
Here is my code
#include <stdio.h>
int main()
{
int sum = 0, c, value;
scanf("%d", &value);
for (c = 1; c <= value; c++)
{
sum = sum + c;
printf("..%d", sum);
scanf("%d", &value);
}
return 0;
}
It appears you are a bit confused about which values you are actually summing (or I am...) From your problem descriptions (and from how you have initialized your for loop), it appears you are to input the ending value and then are to sum from 1 to that value?
If that is the case, there is no need for additional input within the for loop, your loop variable provides all values you are supposed to add to your sum.
Additionally, you cannot use any user-input function correctly unless you validate the return to determine whether input succeeded or failed.
Putting it altogether, you could do:
#include <stdio.h>
int main()
{
int sum = 0, c, value;
fputs ("sum from 1 to: ", stdout); /* prompt for input */
if (scanf ("%d", &value) != 1 || value < 1) { /* VALIDATE EVERY INPUT !!! */
fputs (" error: invalid integer input or negative value.\n", stderr);
return 1;
}
putchar ('\n'); /* add newline before output */
/* you are looping over the values of c -- no input is necessary */
for (c = 1; c <= value; c++)
{
sum = sum + c; /* sum */
printf ("%2d\t\t\t%d\n", c, sum); /* output value added and sum */
}
return 0;
}
Example Use/Output
$ ./bin/suminput
sum from 1 to: 5
1 1
2 3
3 6
4 10
5 15
Or for 1-10:
$ ./bin/suminput
sum from 1 to: 10
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
Or if invalid input is provided:
$ ./bin/suminput
sum from 1 to: twenty
error: invalid integer input or negative value.
Or a negative value:
$ ./bin/suminput
sum from 1 to: -10
error: invalid integer input or negative value.
No harm done.
Taking Input For The Sum
The other way I read your sample input and output (characterized by the 0 ending the loop), is that your task is simply to read inputs and sum them until the user enters 0 (or an invalid integer) displaying the sum after each input. That is quite a bit easier -- but the requirement to validate each input remains the same, e.g.
#include <stdio.h>
int main()
{
int sum = 0, value;
while (scanf ("%d", &value) == 1 && value != 0) { /* input value */
sum += value; /* sum */
printf ("%20d\n", sum); /* output sum */
}
}
Example Use/Output
$ ./bin/suminput2
1
1
2
3
3
6
4
10
5
15
0
Or any random values until 0 is entered:
$ ./bin/suminput2
1
1
-2
-1
3
2
-4
-2
5
3
-6
-3
0
(note: there are ways to place the input and output on the same line but that differs between compilers and operating systems. Windows could use the non-standard getch(), while on Linux you would need to do the same thing by changing input to non-cannonical mode with tcsetattr(). Another way would simply be to save the inputs until the user enters 0 and then to loop over all values input summing and displaying the values (though that would eliminate the 0 at the end of input show in your example input))
Look things over and let me know if you have further questions (and also whether I interpreted your question correctly). If you do need to enter each value to sum, let me know and I am happy to help further.

I tried make a bubble sort with C but it's not working (It's doing bubble sort 10 times)

first i giving how many numbers will i enter then i enter numbers. he need make bubble sort to them but its writing like======>
1 3 2 6 = 0 0 0 0(but it must be like 1 2 3 6(small to big))
the app how i want=
7
1 5 2 7 4 7 3
1 2 3 4 5 7 7
#include<stdio.h>
int main()
{
int numbers[500000];
int counter=0;
int howmany;
scanf("%d",&howmany);//getting how many numbers will we enter
int howmany2=howmany;//we will use this for write all numbers after all
while(howmany>0)//getting all numbers
{
scanf("%d",&numbers[counter]);
howmany--;
counter++;
}
int checker1,checker2;//its gonna check first and second number, then second and third...etc
int hm=howmany-1;//its gonna check entered number-1 times(1,2,3)={1,2},{2,3}
int clone1;//later we will copy numbers[checker1]
int tentime=10;//we gonna do bubble sort 10 times
while(tentime>0)//doing bubble sort
{
checker1=0;
checker2=1;
while(hm>0)
{
if(numbers[checker1]>numbers[checker2])
{
clone1=numbers[checker1];
numbers[checker1]=numbers[checker2];
numbers[checker2]=clone1;
}
checker1++;
checker2++;
hm--;
}
tentime--;
}
int counter2=0;
while(howmany2>0)//showing new number sort on screen
{
printf("%d ",numbers[counter]);
howmany2--;
counter2++;
}
printf("\n");
return 0;
}
You have several problems in your code:
At the end of your first while loop howmany will be 0. As a result hm will be set to -1 and the sort loop (while hm > 0 ) will never run.
When you print out the results are using counter as the array index (this is 4 which is out of bounds and never changes since you are incrementing counter2. As a result you are printing out an undefined value (0 in your case) four times.
Declaring an array of size 500000 may blow up your stack. Even if not it is way larger than you need

C Program crashes at For Loop

I'm new to C programming (I have some very basic experience with programming via vb.NET), and I'm attempting to write a program for the Project Euler Problem #1.
https://projecteuler.net/problem=1
Algorithm
The challenge requires the programmer to find the sum of all multiples of 3 or 5 (inclusive) below 1000 (I used intInput to allow the user to enter an integer in place of 1000).
My current solution takes the input, and decrements it by 1 until (intInput - n) % 3 = 0, that is, until the next nearest multiple of 3 under the input integer is found.
The program then cycles through all integers from 1 to ((intInput - n) / 3), adding each integer to the sum of the previous integers, so long as the current integer is not a multiple of 5, in which case, it is skipped.
The resultant sum is then stored in intThreeMultiplier.
The above process is then repeated, using 5 in place of 3 to find the highest multiple of 5 under intInput, and then cycles through integers 1 to ((intInput - n) / 5), not skipping multiples of 3 this time, and stores the sum in intFiveMultiplier.
The output sum is then calculated via sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier).
The Problem
Whenever I compile and run my code, the user is allowed to input an integer, and then the program crashes. I have determined that the cause has something to do with the first For loop, but I can't figure out what it is.
I have commented out everything following the offending code fragment.
Source Code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int intInput = 0; /*Holds the target number (1000 in the challenge statement.)*/
int n = 0;
int count = 0;
int intThreeMultiplier = 1;
int intFiveMultiplier = 1;
printf("Please enter a positive integer.\n");
scanf("%d",intInput);
for( ; (((intInput - n) % 3) != 0) ; n++)
{}
/*for(; count <= ((intInput - n) / 3); count++)
{
if ((count % 5) != 0)
{
intThreeMultiplier += count;
}
}
count = 0;
for(n = 0 ; ((intInput - n) % 5) != 0 ; n++)
{}
for(; count <= ((intInput - n) / 5) ; count++)
{
intFiveMultiplier += count;
}
int sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier);
printf("The sume of all multiples of 3 or 5 (inclusively) under %d is %d.",intInput, sum);*/
}
This is my first time posting on StackOverflow, so I apologize in advance if I have broken any of the rules for asking questions, and would appreciate any feedback with respect to this.
In addition, I am extremely open to any suggestions regarding coding practices, or any rookie mistakes I've made with C.
Thanks!
scanf("%d",intInput);
might be
scanf("%d", &intInput); // note the ampersand
scanf need the address the variable where the content is to be stored. Why scanf must take the address of operator
For debugging only, print the input to verify that the input is accepted correctly, something like
printf("intInput = %d\n", intInput);
The first thing you need when you are inputting intInput you should use:
scanf("%d", &intInput);
Because scanf() need as an argument of a pointer to your variable. You are doing this by just putting the & sign before your int.
In addition I think that you should double check your algorithm, because you are summing up some numbers more than once. :)

C What is up with my Matrix Reader?

so I am trying to make a matrix reader that will take a text file that contains only data for a NxN matrix such as:
10 9 8 7
6 5 4 3
2 1 0 1
Read the test file into a dynamic multidimensional array. The program will not have headers, so it will need to read the entire file in order to obtain # of rows/cols.
Once I have all the data in my array I then will be able to manipulate how I want (i.e. swapping columns/rows, reversing order, etc).
At this point I am just trying to get my program to simply output the array as it appears in the test file once the entire matrix has been read in.
Here is what I have written so far:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
int i=0;
int j=0;
scanf("%d", &n);
int **array;
array = malloc(n * sizeof(int *));
if(array == NULL) {
printf("Out of memory\n");
exit(1);
}
for(i = 0; i < n; i++) {
array[i] = malloc(n * sizeof(int));
if(array[i] == NULL) {
printf("Out of memory\n");
exit(1);
}
}
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
int k;
scanf("%d", &k);
array[i][j] = k;
printf("%d ", array[i][j]);
}
}
}
And running this gives me output:
9 8 7 6 5 4 3 2 1 0 1 1 1 1 1 1 1 1 1 1 1 1... repeating 1's...
I am not sure what is wrong with my code I have been staring at it for a solid hour and have made 0 progress.
Because my output prints out about 100 different ints I feel that my problem lies in my printing loops, and I feel like it has something to do with int n, but I am not sure how to deal with this.
Any help with be greatly appreciated! Thanks.
The issue is as follows: The first number that is obtained from your file is 10 and that is being stored inside the int n close towards the beginning. That value defines the width and height of your multi-dimensional array, your matrix. You then ask for further values from that file, exactly 10 * 10 many times.
The file, however, only has 4 * 3 - 1 = 11 numbers left in it. It provides them all, right into the int k. Those values get stored inside your matrix, printed. After the 11th (or 12th if you count the first 10) the scanf starts failing. As it fails, it returns the value EOF == -1 but you do not recognize that.
Failure leaves the k as it is, although I am not sure whether it is guaranteed to remain what it previously was, since as far as I know, k could very well have another memory location allocated for itself with each cycle, since (again) as far as I know it gets cleared at the end of each loop. In your case, it does keep its value, luckily I would say, and that gets stored/printed.
In the end, you should have exactly 100 numbers printed, because of that 10 at the very beginning.
Even if you had an additional 4 at the very beginning, you'd end up with a matrix that has a wild last line with all 1s.
If you want to have a 3 by 4 matrix in your hands, consider making your file as the following example:
3 4
10 9 8 7
6 5 4 3
2 1 0 1
Then read the first value into an int n and then second one into an int m. Make first memory allocation with malloc( n * sizeof * array );, then the secondary allocations with malloc( m * sizeof ** array );.
You could also alternatively omit reading anything, deduce how many rows and columns your matrix should have by reading the amount of new-line '\n' occurrences in your file (plus one), as well as amount of numbers there are on a single line.
Edit:
Okay, let's show this you could also part: This is just an example, I'll be using a pair of scanfs for counting both the amount of lines that have at least one number inside and amount of numbers on a single line.
...
int n = 0;
int m = 0;
int discardable;
while ( scanf( "%d", &discardable ) == 1 ) {
// as long as a number has been successfully read
n++;
if ( scanf( "%*[^\n]" ) != 0 )
// discard everything until a '\n'
// and if you fail to encounter a '\n' anywhere until the file ends...
break;
}
// rewind back to the beginning of the file
rewind ( stdin );
while ( scanf( "%d", &discardable ) == 1 ) {
// as long as a number has been successfully read
m++;
if ( scanf( "%*[ \t]" ) != 0 || stdin->_ptr[0] == '\n' )
// discard every ' ' or '\t'
// if you rather get carried until the end of file, break
// else, if the upcoming character is '\n', again, break
break;
}
rewind ( stdin );
...
There you have it, n and m here should be storing the height and width of the matrix you should have, respectively.
This is just a way to do it, I can see why many could potentially just hate this, because I have made use of the FILE structure, and referred to _ptr, but whatever. I personally would prefer this any day over carrying a temporary character array and read from it.

Matrix with variables in C

I'm going to write in pseudo code to make my question more clear. Please keep in mind this code will be done in C.
Imagine I have an array of any amount of numbers. The first number tells me how big of an array we're dealing with. For example, if my first number is 3, it means I have two 3x3 matrices. So I create two multidimensional arrays with:
matrix1[3][3]
matrix2[3][3]
What I'm having a hard time with is the arithmetic/coding to assign all the numbers to the matrices, I'm having a very hard time visualizing how it would be done.
Imagine a test array contains [2,1,2,3,4,5,6,7,8]
My program should now have two matrixes with:
1 2 5 6
3 4 7 8
Do I need several nested loops? Any help would be appreciated.
At the moment the only idea i get is using two for loops. Or you can make a function and call it every time you need (but don't forget to use k as second argument).
int i, j, k;
/* We start in the 2nd element of the array that's why k = 1. */
k = 1;
/* Now we fill the array1 copying 1 by 1 the elements of the "test array" until
we fill it. Then we do the same with the array2. */
for( i = 0; i < test[ 0 ]; i++ ){
for( j = 0; j < test[ 0 ]; j++ ){
array1[ i ][ j ] = test[ k ]
k++;
}
}
for( i = 0; i < test[ 0 ]; i++ ){
for( j = 0; j < test[ 0 ]; j++ ){
array2[ i ][ j ] = test[ k ]
k++;
}
}
Your data is presented in row-major order. After reading your integer array and validating the content (i.e. the dim=4 means 32 values follow, dim=2 means 8 values follow, etc.) I'm not sure why you want to allocate or loop anything.
I.e. You can use your physical test[] data as the matrices:
int dim = test[0];
int (*mat1)[dim] = (int (*)[dim])(test+1);
int (*mat2)[dim] = (int (*)[dim])(test+1 + dim*dim);
C99 supports variable array declarations at the implementation level (i.e. the compiler can support the feature as it is defined by the standard, but does not have to; see 6.7.6.2 of the C99 standard for more info). If your toolchain does NOT support it, then a predefined macro, __STDC_NO_VLA__ must be defined and can be tested at compile time (see section 6.10.8.3-1 of the C99 standard). That being said, every C99-compliant compiler I've ever used in the last decade-plus does support it, so if your's does not, tell us below in a comment.
If it does, then pay note to the use of 'dim' in the declarations of mat1 and mat2 above). It is one of the few features of C I like that C++ does not have. So dance with the one you brought.
Finally, assuming your compiler is C99 compliant and supports VLAs (__STDC_NO_VLA__ is NOT defined), as an extra super-special bonus it is all-but-guaranteed to be the fastest algorithm to get your two matrices, because there is no algorithm. You read one array element, then assign two pointers. O(3) is hard to beat.
Example
#include <stdlib.h>
#include <stdio.h>
// main loader.
int main(int argc, char *argv[])
{
int test[] = {2,1,2,3,4,5,6,7,8};
int dim = test[0];
int (*mat1)[dim] = (int (*)[dim])(test+1);
int (*mat2)[dim] = (int (*)[dim])(test+1 + dim*dim);
// proof stuff is where it should be.
int i=0,j=0;
for (i=0;i<dim;i++)
{
for (j=0;j<dim;printf("%d ", mat1[i][j++]));
printf (" ");
for (j=0;j<dim;printf("%d ", mat2[i][j++]));
printf("\n");
}
return EXIT_SUCCESS;
}
Output
1 2 5 6
3 4 7 8
A similar test with a 3x3 data set:
int test[] = {3,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1};
Output
1 2 3 9 8 7
4 5 6 6 5 4
7 8 9 3 2 1
And finally, a 4x4 data set:
int test[] = {4,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,8,7,6,5,4,3,2,1,8,7,6,5,4,3,2,1};
Output
1 2 3 4 8 7 6 5
5 6 7 8 4 3 2 1
1 2 3 4 8 7 6 5
5 6 7 8 4 3 2 1
The problem with multidimensional arrays in C is that you need to know in advance (at compile time) n-1 of the dimension sizes, they are also a drag when used as function parameters.
There are a couple of alternate approaches:
Creating an array of arrays. i.e. allocating an array of array pointers and then allocating arrays to those pointers.
type **array = malloc(sizeof(type * ) * < firstnumread > );
array[0] = malloc(sizeof(type) * < firstnumread > );
...
Allocating a single dimension array with the size of all the multiplied dimensions. i.e.
type *array = malloc(sizeof(type) * < firstnumread > * < firstnumread >);
In your case, the second is probably more appropiate. Something like:
matrix1 = malloc(sizeof(type)*<firstnumread>*<firstnumread>);
matrix2 = malloc(sizeof(type)*<firstnumread>*<firstnumread>);
Then you can assign values like this:
matrix1[column*<firstnumread> + row] = <value>;
Yes, with 2 for loops.
2D arrays are stored in continuous series of lines from the matrix. So you doesn't even need to allocate new memory you can use your original array. Anyway you can create 2 new standalone array too.
You can crate a function like this, to get the correct number of the matrix.
int getNumber(int array[], int arraynumber, int index_x, int index_y)
{
return array[(((array[0]*index_x)+index_y)+1)+((array[0]*array[0])*arraynumber)];
}
The arraynumber variable is 0 for the first and 1 for the second matrix. This funciton works only if all parameters are correct, so ther is no error detection.
With this function you can easily loop through and create 2 new arrays:
int i,k;
for (i=0; i<array[0]; i++)
{
for (k=0; k<array[0]; k++)
{
newarray1[i][k] = getNumber(array, 0, i,k);
newarray2[i][k] = getNumber(array, 1, i,k);
}
}
Here is something that works in a single loop; no nests and no repeats. I don't know if it'll outperform other answers, but I just felt like giving you a different answer ^_^
I have not tested this code, but it looks like the logic of the algorithm works - that's the point, right? Let me know if it has any errors....
int c=0, x=0, y=0, size=test[0], length=sizeof(test);
for(i=1; i<length; i++) {
if((c-size)<0) {
matrix1[x][y] = test[i];
} else {
matrix2[x][y] = test[i];
}
++y;
if(y%size == 0) {
++c;
y = 0;
x = (c-size)<0 ? ++x : 0;
}
}

Resources