C programming array swap [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have been trying to do this for 4 hours with no luck and I really need to have it done. It is my school's task.
#include <stdio.h>
#include <stdlib.h>
int main() {
char strings[5][5][5][5][5];
char *temp[5];
int b[5];
int a[5];
int x;
int i;
int z;
int a_value;
int b_value;
//get 5 strings from the input
for (i = 0; i < 5; i++) {
scanf("%s", strings[i]);
}
//Get 5 numbers from the input
for (x = 0; x < 5; x++) {
scanf("%d %d", & b[x], & a[x]);
//printf("B is %d and A is %d\n", b[x], a[x]);
a_value = a[x];
b_value = b[x];
temp[b_value] = strings[a_value];
//If the values of a and b are equal to -1 denote the operation (end it)
if (b[x] == -1 && a[x] == -1) {
break;
}
}
//Get the swapped values
for (z = 0; z<=x; z++) {
printf("%s\n", temp[z]);
}
return 0;
}
Input:
aadf
bazz
abkt
bbaa
zzzz
1 3
0 4
3 2
-1 -1
The output is supposed to be like this
zzzz
bbaa
bazz
abkt
aadf
What I get is this
zzzz
bbaa
abkt
So everything works fine and strings get replaced based on that but the problem is that if b and a are not given so the swapped value should be the normal value and I don't know how to do it.
The task exactly says:
Read 5 strings from standard input and put them in an array. Each string is 4 characters length. Then prepare a function, that swaps i-th and j-th elements of the array. Indexes of i and j are given as standard input as two numbers separated by space. There can be more than one operations - each swap operation is separated by new line. Values -1 and -1 denote the end of operations. Print strings separated by new line.
Please help me and thanks ;)

Why 5D array, char strings[5][5][5][5][5] ? you just want to 5 strings as input So for this take 2D array
char strings[5][4];// total 5 strings , in each you can stores 4 characters.
Next things How will you scan data for 2D arrays, you need to rotate two loops namely for rows and columns . Assume row = 5 & col = 4
for (i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
scanf("%c", &strings[i][j]);
}
}
Next this temp[b_value] = strings[a_value]; statement you need to modify, modify according your requirement.
I hope this helps.

Here's you code, corrected and optimized:
#include <stdio.h>
#include <stdlib.h>
int main() {
char strings[5][5];
char temp[4];
int x,y;
//get 5 strings from the input
for (int i = 0; i < 5; i++) {
scanf("%s", strings[i]);
}
do{
scanf("%d %d", & x, & y);
// Assign string[x] to temp
for(int i=0;i<4;i++){
temp[i] = strings[x][i];
}
// Assign string[y] to string[x]
for(int i=0;i<4;i++){
strings[x][i] = strings[y][i];
}
// Assign temp to string[y]
for(int i=0;i<4;i++){
strings[y][i] = temp[i];
}
}while(x!=-1 && y!=-1);
//Get the swapped values
for (int i = 0; i< 5; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
I have tested it. Let me know if you need any explanation.

Related

Trying to find smallest array elements from 2 arrays returns 0 (doesn't work) and the other works. (C lang)

I'm trying to accomplish a simple task in C which is to print out the smallest number from array 1 and smallest number from array 2. Both array elements are imputed by the user.
First one just returns 0 (which in my testing case its supposed to be 1) and the other one returns the correct one (11). I seriously can't understand why and I also tried to google this with no result so that's when I once again decided to seek help here!
int main () {
int masyvas1[10] = {0};
int masyvas2[10] = {0};
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk pirmo masyvo 10 sk: ");
scanf("%d", &x);
masyvas1[i] = x;
}
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk antro masyvo 10 sk: ");
scanf("%d", &x);
masyvas2[i] = x;
}
int mas1maz[2] = {0, 0};
for(int i = 0; i < 10; i++){
if(masyvas1[i] < mas1maz[1]){
mas1maz[1] = masyvas1[i];
}
if(masyvas2[i] < mas1maz[2]){
mas1maz[2] = masyvas2[i];
}
}
printf("testas: %d %d", mas1maz[1], mas1maz[2]);
}
If I enter numbers say from 1 to 10 for the first array and 11 to 20 for the second the program output is: testas: 0 11 which I was expecting it to be testas: 1 11
Thank you in advance!
I would like you to go over your program by trying what is below
int mas1maz[2] = {0, 0};
The Array has 2 elements, try to print each element.
Note: there are only 2 elements but I am printing 3 as you have used mas1maz[2] ( this is grabage= 11)
printf("%d,%d,%d",mas1maz[0],mas1maz[1],mas1maz[2]);
Then you are trying to compare with mas1maz[1]=0, this will result in a minimum always equal to zero.
for(int i = 0; i < 10; i++) {
/*
*/
if(masyvas1[i] < mas1maz[1]) {
mas1maz[1] = masyvas1[i];
}
Here you are tyring to compare mas1maz[2] with garbage=11, this is the reason why you see 11.
if(masyvas2[i] < mas1maz[2]) {
mas1maz[2] = masyvas2[i];
}
What you should try is the following :
for(int i = 0; i<9; i++) {
if(masyvas1[i]>masyvas1[i+1])
{
/*copy to your array*/
mas1maz[0]=masyvas1[i]
}
/* similarly for masyvas2*/
}
see that for an array of length len, indices of the array ranges from 0 to len-1
if(masyvas2[i] < masyvas2[i]){
mas1maz[2] = masyvas2[i];
}
Change your second if as follow. You was checking for smaller number in masmaz1 array and was passing 2 in array parameters which is not compatible. As you have initialized an array for 2 locations 0 and 1 as array locations are started from 0. So change that Second if to compare it with itself for smallest number.
int min;
int max;
int i;
min=max=mas1maz[0];
for(i=1; i<10; i++)
{
if(min>mas1maz[i])
min=mas1maz[i];
}
You should use this after you fill your tables with scanf to find the minimum value
then compare the two different minimums

Remove unnecessary value entries from multidimensional array in c?

Hi I am working with a scenario where user input multiple contiguous arrays of different lengths and I want to store these array for further use.
I am using multidimensional array for this purpose.
Here is the code :
#include <stdio.h>
int main()
{
int rows,cols;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
printf("Enter the maximum number of inputs in a single array ?"); //Need to remove these lines
scanf("%d", &cols); //Need to remove these lines if possible
int array[rows][cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
array[i][j]=0;
}
}
for(int i=0;i<rows;i++)
{
int count;
printf("Enter the number of inputs for array %d - ", i);
scanf("%d",&count);
for(int j=0;j<count;j++)
{
scanf("%d",&array[i][j]);
}
}
//// Use array for other purpose
////printf("\n\nArray --> \n");
////for(int i=0;i<rows;i++)
////{
////for(int j=0;j<cols;j++)
////{
////printf("%d ",array[i][j]);
////}
////printf("\n");
////}
return 0;
}
Example input :
Enter the number of user input arrays ? 5
Enter the maximum number of inputs in a single array ?5
Enter the number of inputs for array 0 - 5
1 2 6 3 5
Enter the number of inputs for array 1 - 1
3
Enter the number of inputs for array 2 - 2
6 5
Enter the number of inputs for array 3 - 1
3
Enter the number of inputs for array 4 - 1
9
Array created in this case :
1 2 6 3 5
3 0 0 0 0
6 5 0 0 0
3 0 0 0 0
9 0 0 0 0
Now I have number of issues in this case :
I want to reduce the space being used by removing the unnecessary entries in the array.
I would not like to use '0' or any other integer to define an unnecessary entry as it is a valid input.
I would like to remove the line
printf("Enter the maximum number of inputs in a single array ?");
scanf("%d", &cols);
Can anyone provide me help to overcome these issues.
From the design criteria you have described:
Array with user determined number of rows.
Rows have differing lengths, also user determined.
Reduce the space being used. (space only for real inputs, no padding, or filler values.)
Array definition is created at run-time per user inputs, but is not required to change during same run-time session.
Note: One design criteria: //Need to remove these lines if possible is not included in this solution. Without a description of the desired method to instruct user, I do not know how to improve on the the user prompt method.
Jagged arrays may be what you are looking for. Following is a simple example directly from the link that incorporates dynamic memory allocation that can be adapted to the code you have already discussed:
int main()
{
int rows;
//Place you user input prompts and scans here
// User input number of Rows
int* jagged[2];//
// Allocate memory for elements in row 0
jagged[0] = malloc(sizeof(int) * 1);
// Allocate memory for elements in row 1
jagged[1] = malloc(sizeof(int) * 3);
// Array to hold the size of each row
int Size[2] = { 1, 3 }, k = 0, number = 100;
// User enters the numbers
for (int i = 0; i < 2; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[k]; j++) {
*p = number++;
// move the pointer
p++;
}
k++;
}
k = 0;
// Display elements in Jagged array
for (int i = 0; i < 2; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[k]; j++) {
printf("%d ", *p);
// move the pointer to the next element
p++;
}
printf("\n");
k++;
// move the pointer to the next row
jagged[i]++;
}
return 0;
}
This is the concept moved a little closer to what I think you want, adapted from the code above to accept user input similar to what your code does...
int main(int argc, char *argv[])
{
int rows = 0;
int cols = 0;
int i, j;
int number = 100;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
// n Rows
int* jagged[rows];
int Size[rows];//array to keep size if each array
for(i=0;i<rows;i++)
{
printf("Enter the maximum number of inputs for array[%d]: ", i);
scanf("%d", &cols); //Need to remove these lines if possible
// Allocate memory for elements in row 0
jagged[i] = malloc(sizeof(jagged[i]) * cols);
Size[i] = cols;//set size of nth array
}
// User enters the numbers (This is spoofed. You will need to code per comment below.
for (i = 0; i < rows; i++) {
int* p = jagged[i];
for (j = 0; j < Size[i]; j++) {
*p = number++; //Note, this is spoofing user input .
//actual user input would be done exactly as above
//with printf prompts and scans for value
// move the pointer
p++;
}
}
// Display elements in Jagged array
for (i = 0; i < rows; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[i]; j++) {
printf("%d ", *p);
// move the pointer to the next element
p++;
}
printf("\n");
// move the pointer to the next row
jagged[i]++;
}
return 0;
}

For loop not working properly to get inputs in an array in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am working on a coding problem "find the smallest number from inputs", I take inputs in the form of for loop and store them in an array. Its working fine for total inputs less than 11 but for greater than 11 it only takes 10 inputs and then breaks.
printf("HOW MANY NUMBERS DO YOU WANT TO INPUT\n");
int array_size , var1;
scanf("%d",&array_size );
var1 = array_size;
int index = 0 , array[index];
for(int index = 0; index < array_size; index++)
{
printf("inputs left: %d\n",var1);
var1 -= 1;
scanf("%d",&array[index]);
}
I expect it should take as many inputs as user desire but it only takes 10 inputs and I can't seem to find the problem.
You want to create an array with a size of zero which is not allowed. You also canĀ“t declare an array with a variable size so you have to use malloc or something else.
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("HOW MANY NUMBERS DO YOU WANT TO INPUT\n");
int array_size;
scanf("%d", &array_size);
int* Array = (int *) malloc(array_size * sizeof(int));
for(int index = 0; index < array_size; index++)
{
printf("inputs left: %d\n", array_size - index);
scanf("%d", (Array + index));
}
for(int i = 0; i < array_size; i++)
{
printf("%d\n\r", *(Array + i));
}
free(Array);
return 0;
}
Which gives
HOW MANY NUMBERS DO YOU WANT TO INPUT
3
inputs left: 3
1
inputs left: 2
2
inputs left: 1
3
1
2
3
Or you use something like an std::vector.
#include <stdio.h>
#include <vector>
int main()
{
printf("HOW MANY NUMBERS DO YOU WANT TO INPUT\n");
int array_size;
scanf("%d", &array_size);
std::vector<int> Array;
for(int index = 0; index < array_size; index++)
{
int Temp;
printf("inputs left: %d\n", array_size - index);
scanf("%d", &Temp);
Array.push_back(Temp);
}
for(int i = 0; i < array_size; i++)
{
printf("%d\n\r", Array.at(i));
}
return 0;
}
Which result in the same output.
int index = 0 , array[index];
You're declaring an array of size 0 here. Array sizes must be positive.
You're not using index as declared here, to remove it and use array_size as the size:
int array[array_size];

C: Store a list of ints in Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What i'm trying to solve here is print a list of prime numbers into an array. I'm kinda fresh to C and the following code is what I have so far, it does not seem to accomplish what I am looking for which a list of prime numbers.
#inlude <stdio.h>
int main(void) {
int i, j, arr[40]
for (i=2; i<40; i++){
for (j=1; j<i; j++) {
if (i%j == 0){
arr[i] = 0;
}
else
arr[i] = i;
}
printf("%d\n", arr[i]);
}
}
This code prints a list 0 instead of primes
try this
#include <stdio.h>
#include <string.h>
int main(void) {
int i, j, arr[40]; // you forgot ';' here
int flg =0; // use an additional flag
for (i=2; i<40; i++)
{
for (j=2; j<i; j++) // don't start from j=1? every number is divisable by 1
{
if (i%j == 0) flg=1; // flage raises whenever divisor found
}
if(flg == 0) arr[i]=i; // no divisor ==> prime number
else arr[i] =0; // there are divisors ==> not prime number
flg = 0; // reset flag to use in next iteration, next number
printf("%d\n", arr[i]);
}
}
It seems you posted code which is not original one. It contains many syntax error.
correct first it.
#inlude <stdio.h> must be #include <stdio.h>
put ; after int i, j, arr[40]
Array index must start with 0 but here you initialize array with i=2.
Also use of two for loop is looks bad codding style instead you can use one function which return the status of number if it's prime number or not. like
#include <stdio.h>
int prime(int n){
int j;
for (j=2;j<=n/2;j++)
if((n%j)==0)
return 0;
return 1;
}
void main(){
int i,p,index, arr[40];
for (i=2;index=0,i<=40;i++,index++)
{
p=prime(i);
if(p==1)
arr[index]=i;
else
arr[index]=0;
printf ("%d\n", arr[index]);
}
}
This might be what you want:
#include <stdio.h>
int main(void) {
int i, j, arr[40]={0};
for (i=2; i<40; i++){
for (j=2; j<i; j++) {
if (i%j == 0){
arr[i] = 0;
break;
}
arr[i] = i;
}
}
for(i = 1; i < 40; i++ )
printf("%d\n", arr[i]);
}
First of all, the code you've given doesn't compile. You've written inlude instead of include on the first line, and your declaration of i, j, and arr needs a ; at the end of the line.
With that taken care of, the code compiles, but it doesn't produce 0s - it produces
0
3
4
5
6
...
etc. Your inner loop sets arr[i] at every iteration, so your printf will only see what it was set to that last time through the loop. The last time through the loop, you had j=i-1, which will only satisfy your if when i = 2 (so j = 1)
To fix this you need to do two things:
Break out of the inner loop the first time you find a divisor, to make sure you don't overwrite the 0 that you write when you do find a divisor.
Start the inner loop from j=2 instead of j=1. Remember 1 is a divisor for primes (as well as every other integer), so if you start the loop from 1, all of the numbers will fail your test

Reading an array of integers and printing them out

I'm learning C on my own and doing a few exercises. The following code reads in an
array of integers from the user. The integers are printed out when the user types in a "0" or when the array is filled. Now the problem is the output. When I type in "0" after I have typed in 3 digits e.g. 1 2 3 the output is the following: 1 2 3 -858993460 -858993460. I am not sure why I get the value "-858993460" but I have already found a solution to avoid it. Now my question is what the values mean and if there is a smarter solution than mine which is presented below as comments.
#include <stdio.h>
#include <string.h>
#define arraylength 5
int main ()
{
//const int arraylength = 21; //alternative possibility to declare a constant
int input [arraylength] ;
int temp = 0;
//int imax = 0;
printf("Please type in a your digits: ");
for (int i = 0; i < arraylength; i++)
{
scanf("%d", &temp);
if ( temp !=0)
{
input[i]= temp;
//imax= i;
}
else
{
//imax= i;
break;
}
if (i < arraylength-1)
printf("Next: ");
}
for (int i =0; i < arraylength; i++ ) // switch arraylength with imax
{
printf("%d", input[i]);
}
getchar();
getchar();
getchar();
}
This happens because irrespective of when the 0 input is given you print all 5 numbers:
for (int i =0; i < arraylength; i++ )
To fix this you can print only the number(s) user entered before entering a 0 by running a loop from 0 to i:
for (int j =0; j < i; j++ )
Those 2 numbers are the garbage that was left in the memory locations for the last 2 parts of your array. You never initialise those when you only input 3 numbers, so when you go through and print all 5 elements in the array, it prints whatever garbage was in the memory.
You print all integers in array which is size of arraylength = 5. So you get 5 integers in output. As you didn't initialize array, you get uninitilized values as 4th and 5th elements of array. You can use memset(&input, 0, arraylength*sizeof(int)); to set initials values in array to 0.

Resources