convert an array to multi dimensional C without using pointer - c

First of all, I would like to know if its possible. If so, please checkout my code and tell me what is wrong.
int m[n]; // this is where I pass the values to a array
for(int i=0;i<n;i++) {
scanf("%d",&a);
m[i]=a;
}
int v[n][b]; // this is where I pass the values from a array to a 2d array
for(int i=0;i<n;i++) { // but for some reason it doesnt work
for(int j=0;j<b;j++) {
v[i][j]=m[i];
}
}
}
The output is :
something like this
v[0][0]:0
v[0][1]:0
v[1][0]:1
v[1][1]:1
....
but I want something like this:
v[0][0]:0
v[0][1]:1
v[1][0]:2
v[1][1]:3
without repeating the values
P.S- if I need to use pointers you can also explain me that way but I would prefer the first one.

In assigning to v[i][j], you are constantly reassigning whatever value was in m[i].
Instead try:
v[i][j] = m[i*n + j];
This is only going to work if the array m has n*b elements.
i*n represents the row you're working on, and j is the column. Or vice-versa, it's up to you how you imagine it.

#include <stdio.h>
int main(){
int m[6]; // this is where I pass the values to a array
int i;
int j;
int k;
int a;
for(i=0;i<6;i++) {
scanf("%d",&a);
m[i]=a;
}
k=0;
int v[2][3]; // this is where I pass the values from a array to a 2d array
for(i=0;i<2;i++) { // but for some reason it doesnt work
for(j=0;j<3;j++) {
v[i][j]=m[3*k+j]; // 3 is the maximum i value [n of your code]
}
k++;
}
return 0;
}
Just used OP's code and changed:
1) Defined all integer variables.
2) the int inside the for removed to be compatible code with every c compiler (OP doesn't really need this changes)
3) Added a variable k that been increased with the changes of outer loop variable and used it in the command v[i][j]=m[3*k+j]; to give the appropriate m value to the new array. (3 been explained in the comment of the same line)
See #Pablo's comment for not using k

Assuming you have at least as many elements in your 1D array as your 2D array and you want to fill in your 2D array in row major order, it suffices to just increment an index for your 1D array every time you read an element from it.
int v[n][b];
int k = 0;
for(int i=0;i<n;i++) {
for(int j=0;j<b;j++) {
v[i][j]=m[k++];
}
}

Related

A string of codes connected to multiple strings.I have some doubts about the two dimensional array and the for loop. Thank you very much!

/* link many strings*/
#include<stdio.h>
char *mystrcat(char * strDest, char * strSrc);
int main(void)
{
int n;
while(scanf("%d",&n))//输入要连接的字符串个数
{
if(n==0) break;//输入0结束
else
{
char words[n][100];
int i=0;
int j;
for(i=0;i<=n;i++)
{
while(fgets(words[i],100,stdin)!=NULL)
{
j=0;
while(words[i][j]!='\n')
j++;
if(words[i][j]=='\n') words[i][j]='\0';break;
}
}//输入字符串
for(i=n;i>0;i--)
{
mystrcat(words[i-1],words[i]);
}//连接这几个字符串
fputs(words[0],stdout);//输出字符串
printf("\n");
}
}
return 0;
}
//strcat函数原型
char *mystrcat(char * strDest,char * strSrc)
{
char *res=strDest;
while(*strDest)strDest++;
while(*strDest=*strSrc)
{
strDest++;
strSrc++;
}
return res;
}
This is a string of correct code to connect multiple strings. But I think n should be n-1 in two for cycles. But if you change the n to n-1, you can only enter n-1 strings, one less than I think. Can you tell me where my idea is wrong?
for(i=0;i<=n;i++)
Accessing array index out of bound when i=n - this is undefined behavior. So of course indexing should be from n-1 to 0( at max) or 0 to n-1.
And also array indexing in C starts from 0. So there are n elements that you are accessing, not n-1.
So corrections would be
for(i=0;i<=n-1;i++)
The thing is - you are reading in the n locations having index 0 to n-1 on the array and then you concatenate them one by one and at last all concatenated strings will be in words[0]. You are printing it out.
The second loop would be like
for(i=n-1;i>0;i--)
{
mystrcat(words[i-1],words[i]);
}
The idea is no matter what while accessing array indices don't access array index out bound. Here you can simply write it like this as shown in the second case. The thing is here we have ensured that all the indices used are from {0,1,2,3...,n-1}.
First determine what you want to do, if you want to take n string and then try to concatenate them then yes you can. That's what is being done here. but a much cleaner way to do it would be that keep a different result string on which you will concatenate n strings. That will not overwrite or change the already inputted strings.

C programming error.2Darrays

I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected.
#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
int arr[a][1];
int i,j,k,sum=0;
for(i=0;i<a;i++)
{
scanf("%d",&arr[i][0]);
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i][0]);
}
for(j=0;j<a;j++)
{
arr[j][1]=0;
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i][0]);//Different Values
}
}
int arr[a][1]; There is only one column and not two.You should use
int arr[a][2];
Here you write out of bounds
arr[j][1]=0;
This is because you write to the second element of an array with only one element.
The size of arr[x] (for any valid x) is just one.
Writing out of bounds leads to undefined behavior.
Your arrays should be something like this :
arr[row][col] where row denotes the number of rows and col the no of coloumns.
Therefore arr[a][1] is a array of a rows and 1 coloumn and therefore your code works wrong.
Your array should be a[a][2]. It means arr is a array with a rows and 2 coloumn.Similarly you have to change the other arr[][] 's throughout the code.

finding how many times an element has repeated in c

I've got a c study which it must print all the numbers in an array then how many times they repeated.
int lottery(int a,int b,int c,int d,int e,int f,int i,int count)
{
printf("Enter the loop count:");
scanf("%d",&d);
a=time(NULL);
srand(a);
int genel[100][100];
int hepsi[50]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49};
count=0;
for(e=0;e<=d-1;e++)
{
for(b=0;b<=5;b++)
{
genel[e][b]=(rand()%49+1);
while(i>=0 && i<=49)
{
if(genel[e][b]==hepsi[i])
{
count=count+1;
}
else{
count=count;
}
}
printf("%d->%d\t",genel[e][b],count);
}
}
}
This doesnt work obviously. the output must be something like that
1-->0 2-->3 3-->15 etc
TY for your help, cheers :)
It is important that you understand what you are doing, naming is therefore very important. Nesting loops is okay if you know what you are doing. An easier to understand approach would be:
void lottery() {
int i, j //forloop counters
int randArray[100][100]; //array for random values
srand(Time(NULL)); //set random seed based on system time
//set random values
for(i = 0; i < 100; i++) {
for(j = 0; j < 100; j++) {
randArray[i][j] = rand()%49 + 1; //sets random ranging from 1 to 49 (49 incl)
}
}
//here you can start the counting procedure, which I won't spoil but ill give some hints below
}
There are a few options, first the easy lazy approach:
use a loop over all the values, 'int number' from 1 up to 49, inside that forloop use two forloops to search through the whole array, incrementing int x everytime you encounter the value 'number'. After youve searched through the whole array, you can use printf("%d -> %d", number, x); to print the value, set x to zero and count another number.
Another approach is as u tried,
create an array with for each number a location where you can increment a counter. Loop through the whole array now using two for-loops, increment the arraylocation corresponding to the value which youve found at randArray[i][j]. Afterwards print the array with counts using another forloop.
I suggest you try to clean up your code and approach, try again and come back with problems you encounter. Good luck!
sorry if this wasn't helpful to you, I tried to spoil not too much because according to my own experience programming should be learned by making mistakes.

C how do I check if an array is full?

I have an array: array[3][3]
I will let the user input data into the array as long as it is not full. As soon as the array gets full I want to stop the user from inserting more data into it.
C has no array bounds check. You have to do it yourself. Use a variable to keep track of how many items you have inserted, and stop when your counter is equal to the array size.
You cannot check if "array is full". To do what u want to do, keep track of index while adding elements to array.
You need to keep track of the data inserted by a user. When your counter reaches the size of the array, the array is full. :D There is not other way in C to achieve this result as it does not provide any means of verifying how many elements are in the array.
Introduce a variable for counting the number of cells filled. You adjust this variable whenever you add/remove data to your array. Then, in order to check if your array is full, just check if this variable is equal to the total number of cells in your array.
The most simple way in my opinion is to dynamically allocate memory using calloc(), where you can initialise the array elements to, for example, zeros. The you can check if the array is full by checking, if the last element in the array is still zero or not. Of course, if the last element is still zero, then the array is not full.
First of all this is not an array but a matrix (aka array of array). you already know that the matrix has dimensions 3x3 and then you could do something like this:
int x, y;
int array[3][3];
for (x = 0; x<2; x++)
{
for (y = 0; y<2; y++)
{
//I assume that it is an array of int
printf("Insert number at %d - %d" ,x,y);
scanf("%d" ,&array[x][y]);
}
}
Now the user can only insert 3*3=9 values.
There are no way to array bound check in C, However with better coding practice we check whether array is full.
For example, consider in your array a[3][3] you don't want to have some particular value. That value could be anything! 0xFF or 0 or anything which is in the integer range! and you have to make sure that value is never given as the input to the array, and then you can verify whether your array a[3][3] is full!
/*part of coed in main*/
/*here initialize the array with 0, assuming that 0 will never be a part of array a[3][3]*/
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
a[i][j] = 0; // assuming that 0 will never be a part of array a[3][3]
}
}
while(CheckArray(**a)!=0)
{
printf("give array input:\n")
scanf("%d", &a[row][column]); //writing to empty cell of an array
}
//CheckArray code
int CheckArray(int a[][])
{
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
if(a[i][j] == 0) // assuming that 0 will never be a part of array a[3][3]
{
row = i; // row and column must be global variables in this example!
column = j; // row and column must be global variables in this example!
return 1;
}
else
{
// no need to do anything here
}
}
}
//if code reaches here then array is full!
printf("Array is full.\n");
return 0;
}
You can still optimize the above code! this is just one way of checking whether array is full with better coding practice!
If possible, you could initialize all elements in the array to a certain value that your program would otherwise consider "illegal" or "invalid". E.g. an array of positive numbers can be initialized to be all -1's. Or an array of chars can be initialized to be all NULL characters.
Then, just look at the last element if it is set to the default value.
measurement = sizeof(myarray) / sizeof(element); //or just a constant
while(myarray[measurement-1] == defaultvalue){
//insert code here...
}
Encapsulate the behavior into a struct with getter/setter functions that check for the max length of the desired vector:
typedef varvector
varvector;
struct varvector {
int length;
void* vector;
};
varvector* varvector_create(int length) {
varvector* container = malloc(sizeof(varvector));
void* vector = malloc(length);
if(container && vector) {
container->vector = vector;
}
return(container);
}
void varvector_destroy(varvector* container) {
free(container.vector);
free(container);
}
varvector_get(varvector* container, int position) {
if(position < container.length) {
return(container->vector[position]);
}
}
varvector_set(varvector* container, int position, char value) {
if(position < container.length) {
container->vector[position] = value
}
}
Object Oriented Programming is a design pattern which happens to have syntactic support in some languages and happens to not have syntactic support in C.
This does not mean that you cannot use this design pattern in your work, it just means you have to either use a library that already provides this for you (glib, ooc) or if you only need a small subset of these features, write your own basic functions.
You can assume that the last element of an array has id=0.
Then in function add check if there is an element with id=0.
int add(char *source, char *target, int size) {
int index = 0;
for (int i = 0; i < size; i++) {
if (target[i].id == 0) {
index = i;
break;
}
}
if (index >= 0 && index < size) {
if (index < size - 1) target[index + 1].id = 0;
// check that element with id=0 is the last in the array
//write code to add your element here
return index;
}
}

Changing array values in functions

Ok so I have a 10x10 array that I need to flip and print. I made this function to do just that
void flip(int d[][10], int rows)
{
int temp, x, y, cols;
cols=rows;
for(x=0; x<rows; x++)
{
for(y=0; y<cols; y++)
{
temp=d[x][y];
d[x][y]=d[y][x];
d[y][x]=temp
}
}
}
Now I know arrays are passed by reference but I also read somewhere that arrays itself act as pointers so you don't have to use pointer notation which seems right. My problem is that when I try to print after flipping it, it does not print the flipped array, but prints out the original one making me think that it isn't flipping the original array.
Here is the print function.
void printArray(int d[][10])
{
int rows, cols,x,y;
rows = sizeof(d[0])/sizeof(d[0][0]);
cols = rows;
for(x=0;x<rows; x++)
{
for(y=0;y<cols;y++)
printf("%2d ",d[x][y]);
printf("\n");
}
}
Odd thing is if I change temp into a "hard" value like the number 10, then it does print out a 10x10 array with half of them being 10s. I am at a loss here why the simple swapping isn't working :(
From what I can tell, by "flip" you mean "transpose"...
Also, if you work out the code by hand, your code works, but twice - aka, you get the original matrix. You can try changing the inner for loop to start at x, not zero.

Resources