Converting matrix to an array in C - arrays

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

Related

Read Input and Display Output in Star

I want to create a program that can read scores from user and display the scores output in the form of stars. But it seems that my code keep getting an infinity loop. Can anyone tell me what is wrong with my looping.
#include <stdio.h>
int main() {
int i, k, j;
int score[5];
for(i = 1; i < 6; i++) {
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 1; k < 6; k++) {
printf("%d. ", k);
for (j = 1; j <= score[k]; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Array indices are 0 based in C. So for an array with 5 elements the indices are from 0-4 inclusive. You are using indices 1-5 which results in buffer overflow. Below is the corrected program with the for loops fixed up to use the right indices:
#include <stdio.h>
#define NUM_SCORES 5
int main()
{
int i, k, j;
int score[NUM_SCORES];
for(i = 0; i < NUM_SCORES ; i++)
{
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 0; k < NUM_SCORES ; k++){
printf("%d. ", k);
for(j = 1; j <= score[k]; j++){
printf("*");
}
printf("\n");
}
return 0;
}
You should also add a check to ensure scanf is able to successfully read each input.

How can I move all elements in an array with a K number and make the numbers rotate when it comes to the end?

#include <stdio.h>
#include <stdlib.h>
int main()
{
int N, K, i;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Please enter value of K: ");
scanf("%d", &K);
int arr[N];
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < N; i++)
{
int temp = arr[i];
arr[i + K] = arr[i];
arr[i] = temp;
}
for (i = 0; i < N; i++)
{
printf("%d", arr[i]);
}
return 0;
}
I know the current code is totally wrong It was just another test.
Basically what I need to do is something like this:
the array before: arr[N]={1,2,3,4,5,6,7,8,9,10}
the array after if K is 2: arr[N]={10,9,1,2,3,4,5,6,7,8}
Like #whozcraig pointed out for in-place rotation of array members.
Define a function to reverse(in-place) array members in a range :
static inline void
arr_reverse (const int start, const int end, int arr[]) {
for (int ai = start, zi = end; ai < zi; ++ai, --zi) {
int tmp = arr[ai];
arr[ai] = arr[zi];
arr[zi] = tmp;
}
}
Then you call it like :
K %= N;
if (K != 0) {
arr_reverse (0, N-1, arr);
arr_reverse (0, K-1, arr);
arr_reverse (K, N-1, arr);
}
I write something like this but it creates new array instead of modifying current one but it works.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N, K, i;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Please enter value of K: ");
scanf("%d", &K);
int arr[N], newArr[N];
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < K; i++)
{
newArr[i] = arr[N-1-i];
}
for (int x = 0; i < N; i++)
{
newArr[i] = arr[x];
x++;
}
for (i = 0; i < N; i++)
{
printf("%d ", newArr[i]);
}
return 0;
}
Thank you guys, for all the comments and answers. I've tried them and they worked.
I have found a way to do it as well. It's bit different. I did it with a function which moves all the elements with 1 position and then repeat the func as much as needed (K times).
#Cheatah helped me come up with it. I will post it in case somebody likes this solution in the future.
Here it is:
#include <stdio.h>
#include <stdlib.h>
int moveOnePos(int num, int array[num])
{
int temp = array[num - 1];
for (int b = num - 1; b > 0; b--)
{
array[b] = array[b - 1];
}
array[0] = temp;
return 0;
}
int main()
{
int N, K, i;
printf("Please enter size of array: ");
scanf("%d", &N);
printf("Please enter K: ");
scanf("%d", &K);
int arr[N];
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < K; i++)
{
moveOnePos(N, arr);
}
for (i = 0; i < N; i++)
{
printf("%d", arr[i]);
}
return 0;
}

Finding pairs in an array that are equal to an input value

I have to find out if there is any pair of i,j such that array[i]^2 + array[j]^2 == x^2
.
If there are such pairs, I need to print all such (i,j). Otherwise, print “There are no such pairs”.
#include <stdio.h>
int main(){
int size=10, i, x,j;
int Array[size];
printf("What is the value of x:");
scanf("%d",&x);
for(i=0;i<size;i++){
printf("Enter array value :");
scanf("%d",&Array[i]);
}
for(i=0;i<size;){
for(j=i+1;j<size;j++)
if((Array[i]*Array[i])+(Array[j]*Array[j])==x*x) //how do I complete this for loop?
}
return 0;
}
Yo're almost there, why weren't you incrementing the value of i? Keep a counter to count the matched pairs, then print those or if nothing is found print whatever you want.
#include <stdio.h>
int main() {
int size = 10, i, x, j;
int Array[size];
printf("What is the value of x:");
scanf("%d", &x);
for (i = 0; i < size; i++) {
printf("Enter array value :");
scanf("%d", &Array[i]);
}
int counter = 0;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++)
if ((Array[i] * Array[i]) + (Array[j] * Array[j]) == x * x) {
printf("%d %d\n", Array[i], Array[j]);
counter++;
}
}
if (!counter) {
printf("There are no such pairs\n");
}
return 0;
}

EOF and free part of unused 2d array

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;
}

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