0% found this document useful (0 votes)
96 views

Reversing An Array

The code provides a program that allows a user to input integers into an array, calls a function to remove duplicates from the array, and then prints out the modified array. The function rmDup takes the integer array and a reference to the size as parameters. It loops through the array comparing each element to subsequent elements, and if a duplicate is found it replaces the duplicate with the element preceding it in the array and decreases the size. In main, the program prompts the user to input integers until they enter 'q', stores the inputs in an array, calls rmDup to remove duplicates, then prints out the modified array. The code is getting a "Segmentation fault" error when trying to run it after input.

Uploaded by

ryan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Reversing An Array

The code provides a program that allows a user to input integers into an array, calls a function to remove duplicates from the array, and then prints out the modified array. The function rmDup takes the integer array and a reference to the size as parameters. It loops through the array comparing each element to subsequent elements, and if a duplicate is found it replaces the duplicate with the element preceding it in the array and decreases the size. In main, the program prompts the user to input integers until they enter 'q', stores the inputs in an array, calls rmDup to remove duplicates, then prints out the modified array. The code is getting a "Segmentation fault" error when trying to run it after input.

Uploaded by

ryan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Reversing an array

Apr 21, 2016 at 11:15am


brendancostner (16)
I was given this problem for my class:
Write a program in C++ that asks the user to enter an array of size N and pass the array to a
function named reverse_array that takes as its arguments an array of floating point values and an
integer that tells how many floating point values are in the array. The function must reverse the
order of the values in the array. The function should not return any value. Do not forget to write
the main function as well. Display the original array and the reversed array in the main function.

The following program is what i have typed up, but I have 2 issues. This compiling issue in line
4:
4:23: error: expected unqualified-id before 'int'
4:23: error: expected ')' before 'int'

Also, I tried to write the function with 20 numbers, but I don't know how to make it be able to
take unlimited numbers in the array. Any help is appreciated, Thank you!

#include<iostream>
using namespace std;

struct reverse_array(float array,int arraylength){


for (int i = 0; i < (arraylength / 2); i++)
{
temporary = array[i];
array[i] = array[(arraylength - 1) - i];
array[(arraylength - 1) - i] = temporary;
}
cout << "The new array order is " << endl;

for (int i = 0; i < arraylength; i++)


{
cout << "Array[" << i << "] = " << array[i] << endl;
}

}
int main()
{
int temporary, arraylength;
float array[50];
cout << "Enter the array size: ";
cin >> arraylength;

cout << "Enter the numbers in the array:" << endl;


for (int i = 0; i < arraylength; i++)
{
cout << "Array[" << i << "] = ";
cin >> array[i];
}
cout<< reverse_array(array,arraylength);

}
Apr 21, 2016 at 1:43pm
integralfx (897)
Please use code tags.
http://www.cplusplus.com/articles/jEywvCM9/

1 #include <iostream> Edit &


2 using namespace std; Run
3
4 // struct isn't a return type
5 /*struct*/ void reverse_array( float array[], int arraylength )
6 {
7 for (int i = 0; i < (arraylength / 2); i++) {
8 float temporary = array[i]; // temporary
9 wasn't declared
10 array[i] = array[(arraylength - 1) - i];
11 array[(arraylength - 1) - i] = temporary;
12 }
13 }
14
15 int main()
16 {
17 int /*temporary,*/ arraylength; // unused variable
18 temporary?
19 //float array[50];
20 /*
21 You need to dynamically allocate memory for the array,
22 as its size is not know at compile time.
23 */
24 cout << "Enter the array size: ";
25 cin >> arraylength;
26
27 float* array = new float[arraylength];
28
29 cout << "Enter the numbers in the array:" << endl;
30 for ( int i = 0; i < arraylength; i++ ) {
31 cout << "Array[" << i << "] = ";
32 cin >> array[i];
33 }
34
35 reverse_array( array, arraylength );
36
37 cout << "The new array order is " << endl;
38 for ( int i = 0; i < arraylength; i++ ) {
39 cout << "Array[" << i << "] = " << array[i] << endl;
40 }
41
42 // free the memory, to prevent memory leaks
delete[] array;
}
Enter the array size: 5
Enter the numbers in the array:
Array[0] = 1
Array[1] = 2
Array[2] = 3
Array[3] = 4
Array[4] = 5
The new array order is
Array[0] = 5
Array[1] = 4
Array[2] = 3
Array[3] = 2
Array[4] = 1

http://cpp.sh/3nl56
Last edited on Apr 21, 2016 at 1:43pm
Apr 22, 2016 at 1:48am
brendancostner (16)
Well sir, you are awesome. I feel like an idiot not trying that as a void. I have been confused on
which to use, and what time. My teacher has gone over functions where he will use void, struct,
string, float, etc. and I have no clue when to you which. Do you by any chance know the
differences?
Apr 22, 2016 at 4:41am
Yawzheek (120)

My teacher has gone over functions where he will use void, struct, string, float, etc.

A struct is just a user-defined type that you'll create yourself, basically. It's just a class with
public members by default. You know how you make something and use it, like:

1 int i = 0;
2 cout << i << endl;

int is a TYPE, and struct allows you to use your own user TYPE.

Float is just floating point numbers. You're probably more familiar with "double." It too is just a
type.

String is also a type, and it's used for strings (hence the name). You use that for words/text:

1 string s1 = "Hello";
2 string s2 = "world!";
3 cout << s1 + ' ' + s2 << endl;
void is a "type" in the sense that it doesn't return anything. It's quite useful, especially for
functions where you want to do something to something else, but (obviously) have no need or
desire for a return type. You could use a void function, using the variables s1 and s2 above, in a
manner such as:

1 void print(string x, string y) Edit & Run


2 {
3 cout << x + ' ' + y << endl
4 }
5
6 int main(){
7 //define s1 and s2 -- see above
8 print(s1, s2);
9 return 0;
10 }

So hopefully now you see that I could create any number of strings and concatenate them (put
them together two at a time -- "stitch" them together, if you will) by simply passing two strings
to the function print(), rather than typing cout instructions every time I wanted to do it. No return
value is needed for this, so we use void.

Hope that helped.


Ask Question

4
1
I'm writing a program that has a user input integers into an array, calls a function that removes
duplicates from that array, and then prints out the modified array. When I run it, it lets me input
values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing
values. What am I doing wrong?

Here is my code:

#include <iostream>

using namespace std;

void rmDup(int array[], int& size)


{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i];
size--;
}
}
}
}
int main()
{
const int CAPACITY = 100;
int values[CAPACITY], currentSize = 0, input;

cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";

while (cin >> input)


{
if (currentSize < CAPACITY)
{
values[currentSize] = input;
currentSize++;
}
}

rmDup(values, currentSize);

for (int k = 0; k < currentSize; k++)


{
cout << values[k];
}

return 0;
}
Thank you.

C Source Code/Sorting array in ascending


and descending order
< C Source Code

Jump to navigationJump to search

/*
Program - Array Sorting
Author - Vishal Solanki
Language - C Language
Date - 03/02/2018 (dd/mm/yyyy)
*/

//IDE used for this code is "Visual Studio 2017"

#include <stdio.h> //including stdio.h for printf and other


functions

int main() //default function for call


{
int a[100],n,i,j;
printf("Array size: ");
scanf("%d",&n);
printf("Elements: ");

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for (int i = 0; i < n; i++) //Loop for
ascending ordering
{
for (int j = 0; j < n; j++) //Loop for
comparing other values
{
if (a[j] > a[i]) //Comparing other
array elements
{
int tmp = a[i]; //Using temporary
variable for storing last value
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
printf("\n\nAscending : "); //Printing message
for (int i = 0; i < n; i++) //Loop for printing
array data after sorting
{
printf(" %d ", a[i]);
}
for (int i = 0; i < n; i++) //Loop for
descending ordering
{
for (int j = 0; j < n; j++) //Loop for
comparing other values
{
if (a[j] < a[i]) //Comparing other
array elements
{
int tmp = a[i]; //Using temporary
variable for storing last value
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
printf("\n\nDescending : "); //Printing message
for (int i = 0; i < n; i++) //Loop for printing
array data after sorting
{
printf(" %d ", a[i]); //Printing data
}
return 0; //returning 0
status to system
}

//Ouput
/*

Array size: 10

Elements : 3 4 7 6 5 1 2 8 10 9

Ascending : 1 2 3 4 5 6 7 8 9 10

Descending : 10 9 8 7 6 5 4 3 2 1
*/

import
java.util.Random;

/**
This class generates permutations of a sequence of integers
1...length.
*/
public class PermutationGenerator
{
private Random generator;
private int length;

/**
Construct a PermutationGenerator object.
@param length the length of the permutations generated
by this generator.
*/
public PermutationGenerator(int length)
{
// "Seeding" this so testing is deterministic.
generator = new Random(42);
this.length = length;
}
/**
Gets the next permutation.
@return the array containing the next permutation
*/
public int[] nextPermutation()
{
??????
}
}
Raw

PermutationTester_Skeleton.java

import java.util.Arrays;

/**
Prints some permutations.
*/
public class PermutationTester
{
public static void main(String[] args)
{
PermutationGenerator gen = new PermutationGenerator(10);

System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [5, 7, 3, 2, 8, 10, 9, 6, 4, 1] ");
System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [5, 4, 7, 2, 6, 8, 1, 10, 9, 3] ");
System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [7, 10, 8, 9, 2, 6, 3, 4, 5, 1] ");
System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [7, 5, 8, 10, 3, 6, 9, 2, 4, 1] ");

gen = new PermutationGenerator(5);


System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [2, 3, 4, 5, 1] ");
System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [5, 4, 3, 2, 1] ");
System.out.println(Arrays.toString(gen.nextPermutation()));
System.out.println("Expected: [4, 5, 1, 2, 3] ");
}
Write a program that produces random permutations of the numbers 1 to 10. To
generate a random permutation, you need to fill an array with the numbers 1 to
10 so that no two entries of the array have the same contents. You could do it by
brute force, by calling Random.nextInt until it produces a value that is not
yet in the array. Instead, you should implement a smart method. Make a second
array and fill it with the numbers 1 to 10. Then pick one of those at random,
remove it, and append it to the permutation array. Repeat 10 times. Implement a
class PermutationGenerator with a method

int[] nextPermutation

Complete the following file:

PermutationGenerator.java

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
import java.util.Random;
/**
This class generates permutations of a sequence of
integers
1...length.
*/
public class PermutationGenerator
{
. . .
/**
Construct a PermutationGenerator object.
@param length the length of the permutations
generated
by this generator.
*/
public PermutationGenerator(int length)
{
. . .
}
/**
Gets the next permutation.
@return the array containing the next permutation
*/
public int[] nextPermutation()
{
. . .
}
}
Use the following file:

PermutationPrinter.java
/**
This class prints 5 permutations of the numbers 1 through 10.
*/
public class PermutationPrinter
{
public static void main(String[] args)
{
PermutationGenerator gen = new PermutationGenerator(10);

for (int i = 1; i <= 5; i++)


{
for (int n : gen.nextPermutation())
System.out.print(" " + n);
System.out.println();
}
}
}
1. #include <string>
2. #include <vector>
3.
4. using namespace std;
5.
6. class PermutationGenerator
7. {
8. public:
9. std::vector<int> randPermutation;
10. std::vector<int> intList;
11. Random ;*randSelection;
12. int listSize;
13.
14. PermutationGenerator() //this(10);
15. {
16. }
17.
18. PermutationGenerator(int lsize)
19. {
20. randSelection = new Random();
21. listSize = lsize;
22. intList = std::vector(listSize);
23. randPermutation = std::vector(listSize);
24. }
25.
26. virtual std::vector<int> nextPermutation()
27. {
28. // Fill the ArrayList intList with the numbers 1 to 10
29.
30. intList.clear();
31. for (int i = 1; i <= listSize; i++)
32. intList.push_back(i);
33.
34. randPermutation.clear();
35. for (int i = 1; i <= listSize; i++)
36. {
37. // Pick a number at random using (using Random.nextInt(int),
38. // that removes a number from the intList.
39. int index = randSelection->nextInt(intList.size());
40. int number = intList.remove(index);
41.
42. // Add and append the random number to the randPermutation
ArrayList.
43. // Repeated listSize times
44. randPermutation.push_back(number);
45. }
46.
47. return randPermutation;
48. }
49.
50. static void main(std::string args[])
51. {
52. // Prints out the values of the returned ArrayList
53. PermutationGenerator *gen = new PermutationGenerator(10);
54. for (int i = 1; i <= 10; i++)
55. {
56. std::cout::put("List " + i + ": ");
57. std::vector<int> list = gen->nextPermutation();
58. puts(list);
59. }
60. }
61.

Dsa

You might also like