EOF and free part of unused 2d array - c

My background is java so I'm not used to c syntax yet.
I need to do the following: let the user to input number k (number of rows), and after to insert values into 2d array with this form:
1 2
3 4
5 6
i.e two values with space between them and then new line for the new row.
If the user entered k=1000 but entered only 4 rows so the function call would be only with the array with 4 rows and not 100. the loop that reads the values should stop if: there are k rows or reaching to EOF
My questions:
I don't know how to implement the EOF part.
I don't know how to implement that for k=1000 and there only 4 rows so call the function with the array that contains only 4 rows
Here my code:
#include <stdio.h>
#define COLS 2
void foo(int** rows, int n);
int main()
{
int k;
printf("Please enter number of rows\n");
scanf_s("%d", &k);
int** matrix = (int**)malloc(k * sizeof(int*));
for (int i = 0; i < k; i++)
matrix[i] = (int*)malloc(COLS * sizeof(int));
int num1, num2;
for (int i = 0; i < k||num1!=EOF; i++)
{
printf("Enter two numbers separated by space \n");
scanf_s("%d %d", &num1, &num2);
matrix[i][0]=num1;
matrix[i][1] = num2;
}
printf("The array:: \n");
for (int i = 0; i < k; i++)
{
for (int j = 0; j < COLS; j++)
{
printf("%d \t",matrix[i][j]);
}
printf("\n");
}
foo(matrix, k);
for (int i = 0; i < k; i++)
{
free(matrix[i]);
}
free(matrix);
return 0;
}
void foo(int** rows, int n)
{
//some stuff
}

Change the bellow portion of your code:
for (int i = 0; i < k||num1!=EOF; i++)
{
printf("Enter two numbers separated by space \n");
scanf_s("%d %d", &num1, &num2);
matrix[i][0]=num1;
matrix[i][1] = num2;
}
To:
int i;
for (i = 0; i < k; i++)
{
printf("Enter two numbers separated by space \n");
if(2 != scanf_s("%d %d", &num1, &num2)) break;
matrix[i][0]=num1;
matrix[i][1] = num2;
}
k = i;
Hope it will work as you want

check the return value of scanf
for (int i = 0; i < k; i++)
{
printf("Enter two numbers separated by space \n");
if(scanf_s("%d %d", &num1, &num2)==EOF)
break;
matrix[i][0]=num1;
matrix[i][1] = num2;
}

Related

Converting matrix to an array in C

How can I copy the elements from a matrix,entered by user,to an array? I tried this, but it didn't work:
#include<stdio.h>
int main(){
int m[20][20],a[400],c=0;//max dimensions;
scanf("%d %d",&M,&N);//dimensions of matrix;
for(i=0;i<M;i++{
for(j=0;j<N;j++{
scanf("%d", &m[i][j]);
for(c=0;c<M*N;c++)
a[c]=m[i][j];
}}}
Don't know why you want to store both the matrix format and the array format, but anyway here is a code that should do the trick with also the data output to show the result:
#include <stdio.h>
#include <stdlib.h>
#define R 20 //max rows
#define C 20 //max columns
int main() {
int m[R][C]; //matrix
int a[R*C]; //array
int r, c; //user matrix size
int i, j; //iterators
printf("insert row size: ");
scanf("%d", &r);
printf("insert column size: ");
scanf("%d", &c);
if(r > R || c > C) {
printf("Invalid sizes");
return -1;
}
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
printf("insert value for row %d column %d: ", i + 1, j + 1);
scanf("%d", &m[i][j]);
a[(c * i) + j] = m[i][j];
}
}
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
for(i = 0; i < r * c; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Note that I also added some checks for the user data, avoiding to generate a matrix bigger that the maximum size. Also you don't need separate loops but it can be done all together.
Also please post a code that is compilable and can be run, as explained here: https://stackoverflow.com/help/how-to-ask

To printf a matrix

When i want to print a matrix which i input,i can use code:
#include <stdio.h>
int main(void)
{
int n, m; //row and column
printf("Enter row and column:\n");
scanf("%d %d", &n, &m);
int x[n][m];
printf("Enter your matrix:\n");
for (int i = 0; i < n; i++) //input my matrix
{
for (int j = 0; j < m; j++)
{
scanf("%d", &x[i][j]);
}
}
printf("print it:\n");
for (int i = 0; i < n; i++) //print it
{
for (int j = 0; j < m; j++)
{
printf("%d ", x[i][j]);
}
putchar('\n');
}
}
enter image description here(a possible case)
In code above, I have to assign values to the rows and columns of the matrix,which named "n" and "m".
int n, m;
scanf("%d %d", &n, &m);
But now I am asking a way to automatic tally .
Can I get this one directly?
enter image description here
You can simulate a two-dimensional array with a one-dimensional array, if that's what you mean:
#include <stdio.h>
#include <stdlib.h>
#define DIGITS 3
int main(void) { // It's good practice to fill function arguments with void if not planning on using them
/* scanf("%d %d", &n, &m); Using scanf with uninitialised variables will result in
* undefined behaviour if it is unable to convert the input. Using fgets
* is easier to debug, safer, and cleaner.
* I highly recommend this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
*/
char buf[DIGITS+1];
printf("%s", "Enter array rows:");
fgets(buf, DIGITS+1, stdin);
const int n = atoi(buf);
printf("%s", "Enter array columns:");
fgets(buf, DIGITS+1, stdin);
const int m = atoi(buf);
int x[n*m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("Enter array value at %d, %d: ", i, j);
fgets(buf, DIGITS+1, stdin);
x[i+j] = atoi(buf);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", x[i+j]);
}
printf("\n");
}
}
I'm not really sure as to why you would do this when C supports your two-dimensional array answer equally.
But now I am asking a way to automatic tally. Can I get this one directly?
Yes.
Form a linked-list of lines. Initially the list is empty.
Read the first line of input, the "1 2 3" into a string. Use fgets().
Parse the line to detect the number of values in it.
Append the line to the linked list of lines.
Continue doing so until 1) end-of-file, 2) a blank line or 3) number of integer is not the same as the first (error condition).
Now code has the m (number of values per line) and n, the number of lines.
Form int x[n][m];
Parse the lines for values and save in x.

Check if the first and last row of a matrix has only negative values

i have some problem making this program
I have created two arrays where I go to insert the first and the last line, then I check if every element is > 0 but it doesn't seem to work..
That's my code:
int main()
{
int i, j, n, m;
int matrix[10][20];
int first_row[m];
int last_row[m];
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(matrix[i=0][j]) // First row
first_row[i] = matrix[i=0][j];
if(matrix[i=n-1][j]) // second row
last_row[i] = matrix[i=n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=j+1;j<n;j++)
{
if(last_row[i] < 0)
printf("Negative element");
}
}
}
I assume in the if conditions matrix[i=0][j] and matrix[i=n-1][j] was to check if the current row being input is the first or last row respectively. If that was the case then you just need to simply check if i is 0 (i == 0) or n - 1 (i == n-1) instead of using matrix[i=0][j] and matrix[i=n-1][j].
Also the line first_row[i] = matrix[i=0][j]; and last_row[i] = matrix[i=n-1][j]; will update i which is what you should avoid in a for loop where i is index. If you intended to assign values to first_row and last_row, you should change them to first_row[j] = matrix[0][j]; and last_row[j] = matrix[n-1][j]; to a get the desire result (note that j should be used for indexing first_row and last_row instead of i because j represents matrix column).
If you want to check every element in the matrix for negative values, then the for loop for (j=j+1;j<n;j++) should be changed to for (j=0;j<m;j++) and matrix[i][j] should be used instead of last_row[i].
Edit: Also as #chux suggested, you should consider initializing matrix, first_row and last_row arrays after you input n and m in order to avoid segmentation fault for any n and m values that are larger than 10 and 20 respectively.
#include <stdio.h>
int main()
{
int i, j, n, m;
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
int matrix[n][m];
int first_row[m];
int last_row[m];
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(i == 0) // First row
first_row[j] = matrix[0][j];
if(i == n-1) // second row
last_row[j] = matrix[n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=0;j<m;j++)
{
if(matrix[i][j] < 0)
printf("Negative element %d\n", matrix[i][j]);
}
}
}

Correct Alignment of Numbers in PASCAL TRIANGLE

I made a program for making a pascal triangle and for the input of numbers ( rows ) > 5 , there is an alignment problem i.e for ncr > 10. Help me out please.
I have included the images for output of the program.
Output Image
#include<stdio.h>
int factorial(int number)
{
int fact=1;
for(int i=1; i<=number; ++i )
{
fact*=i;
}
return fact;
}
int ncr(int n, int r)
{
int ncr;
int fact1=factorial(n);
int fact2=factorial(n-r);
int fact3=factorial(r);
ncr = fact1 /(fact2 * fact3);
return ncr;
}
int main()
{
int rows;
printf("enter the number of rows :\n");
scanf("%d",&rows);
for(int n=0; n<rows; n++)
{
for(int i=1; i<=rows-n; i++)
{
printf(" ");
}
for(int r=0; r<=n; r++)
{
printf("%d ",ncr(n,r));
}
printf("\n");
}
return 0;
}
You can change the inner loop like this
for(int i=1; i<=rows-n; i++)
{
printf(" "); // Note the extra space
}
for(int r=0; r<=n; r++)
{
printf("%3d ",ncr(n,r)); // Changed to %3d
}
This will work upto 9 rows. If you want it to work for more rows, you can add another space in the first printf and change the second printf to %5d
printf can take a precision before the formatter. Change printf("%d ",ncr(n,r)); to printf("%3d ",ncr(n,r)); to make the numbers 3 characters wide. Also change printf(" "); to printf(" ");.
If you use
printf ("Width trick: %*d \n", 5, 10);
this will add 5 more spaces before the digit value.

How to delete duplicated values in array in C?

I want to delete duplicates values in array. For example: array[1,5,6,1,3,5,9] I want to have array[6,3,9].
I have written this, but I am having troubles:
#include<stdio.h>
main() {
int array[50], i, j, k=0, c=0, array2[50], n;
printf("Enter array dimension: "); scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("array[%d]= ", i); scanf("%d", &array[i]);
}
for (i = 0; i < n; ) {
for (j = i + 1; j < n; j++) {
if (array[i] == array[j])
i++;
else {
array2[k++] = array[i];
c++;
}
}
}
for (k = 0; k < c; k++) {
printf("%d ", array2[k]);
}
system("pause");
}
You should start by describing your problem in pseudo code, and breaking it into smaller pieces.
Start from scratch by deleting all these redundant variables, and try to implement the following algorithm:
for each element in inputArray
if not elementIsDuplicate(element)
add to outputArray
That's a single for loop. The elementIsDuplicate is separate function.
Now try to implement the function elementIsDuplicate. This function also contains a single loop, takes input parameters (int* array, int n, int currentIdx) and returns 1 or 0 indicating whether the element at currentIdx occurs anywhere else in the array.
#include<stdio.h>
int main(){
int array[50], i, j, k=0, c, n, array2[50] = {0};
printf("Enter array dimension: "); scanf("%d", &n);
for (i = 0; i < n; ++i){
int num, dup = 0;
printf("array[%d]= ", i); scanf("%d", &num);
for(j = 0; j < k; ++j){
if(array[j] == num){
array2[j] = dup = 1;
break;
}
}
if(!dup){
array[k++] = num;
}
}
for (c=i=0; i < k; ++i){
if(!array2[i])
printf("%d ", array[c++] = array[i]);
}
printf("\n");
/*
for(i=0;i<c;++i)
printf("%d ", array[i]);
printf("\n");
*/
system("pause");
return 0;
}
#include<stdio.h>
main()
{
int n, a[50], b[50], count = 0, c, d;
printf("Enter number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for(c=0;c<n;c++)
scanf("%d",&a[c]); //enter array elements
for(c=0;c<n;c++)
{
for(d=0;d<count;d++)
{
if(a[c]==b[d])
break;
}
if(d==count)
{
b[count] = a[c];
count++;
}
}
printf("count is: %d\n",count);
printf("Array obtained after removing duplicate elements\n");
for(c=0;c<count;c++)
printf("%d\n",b[c]);
return 0;
}
This will remove multiple duplicates from the desired array..
Example: if the input array is: 3 6 5 6 2 8 6 5 9 8 6 ,,then the output array will be: 3 6 5 2 8 9

Resources