Given an array of integers print each element in reverse order as a single line of space-separated integers.
Input Format
Output Format
Print all integers in in reverse order as a single line of space-separated integers.
Sample Input
4
1 4 3 2
Sample Output
2 3 4 1
Here's my Code
int main()
{
int n;
int a[n];
cin >>n;
for (int i=0;i<n;i++)
{
cin>>a[i];
}
for (int i=n-1;i>=0;i--)
cout<<a[i]<<" ";
return 0;
}
You can not allocate an static array with a variable size meaning the expression a[n] is not acceptable since in the compile time the variable "n" is not determined. If this question have a limit for "n" - for example n < 1000 - then replace the expression with int a[1000] ;. If it doesn't , replace it with int* a = new int[n] ;. It is called dynamic allocation , you can search it to find out how amazing it is ;)
Related
I am trying to input an array and then print it in reverse order using for loop. Firstly, I tried to print out the array elements in original order as follows:
#include <stdio.h>
int main()
{
int a[100];
int n,i;
int *p=a;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++){
printf("Enter array element [%d]:",i);
scanf("%d",p+i);
}
printf("Array elements in reverse order: ");
for (i=0;i<n;i++){
printf("%d\n",*(p+i));
}
The above code worked and desired output was achieved. And then I tried to output array elements in reverse order using following changes in the last for loop:
for (i=n;i>0;i--){
printf("%d\n",*(p+i));
But doing this the output appears as below:
while the desired output is:
3
2
1
What am I missing?
In your first attempt, the indices range from 0 to n-1 which is correct. In your second attempt the indices range from n to 1, so you read and write one element past the end of the array.
The proper initialization and condition is:
for (i=n-1;i>=0;i--){
You iterate from p+3 (array[3]), while max index is 2 -> undefined behavior, garbage printed
You iterate until p+0, excluded, you exclude array[0].
for (i = n - 1; i >= 0; i--) {
//...
}
This question already has answers here:
Pointer to string changes its value unexpectedly
(4 answers)
Closed 4 years ago.
I would like to create an array in C and then assign to every value in that array the string "[ ]".
This is what I have in mind:
char Array[N];
for(int i = 0; i < N; i++)
{
Array[i]="[ ]";
}
What is the correct approach to doing that?
Bellow is a sample working code you customize to your taste:
#include<stdio.h>
#include<string.h> // for strcpy: use to copy one string into another
// set a symbolic constant
#define N 10
int main(int argc, char **argv)
{
// declare the array
char Array[N][4]; // 4, because "[ ]" is 3+1 long
for(int i=0; i < N; i++){
strcpy(Array[i], "[ ]");
}
// print out the content for test purpose
for(int i=0; i < N; i++){
printf("Array[%d] = %s\n", i, Array[i]);
}
return 0;
}
This question already has an accepted solution but I'd like to provide a bit more context that will help people who are used to higher-level languages like Java and C++ understand why these steps are needed when writing this algorithm in C vs. in a newer language.
For starters, not every C compiler will allow you to create an array with a size determined by a variable (this is called a Variable Length Array, or VLA--you can read more about them here: How do I declare a variable sized array in C?). Unfortunately you can't even declare a const variable for the number of terms you want in your array (read more about that here: Can a const variable be used to declare the size of an array in C?). So that's why you're stuck typing the literals everywhere in the program or using preprocessor commands like I've demonstrated.
Next, the length of a char array in C is the number of chars it can hold. However, since each of your terms is 3 characters long plus the null character at the end you need the array to be 4 times longer than the number of terms. You can use two See the code below for how to declare this.
Finally, you need to #include the string.h header file in order to be able to work with strings in C.
#include <stdio.h>
#include <string.h>
int main(){
#define N_TERMS 6
#define L_TERM 4
char term[L_TERM] = "[ ]";
char Array[N_TERMS * L_TERM] = ""; //array should be the size of the product of number of terms and length of term
for(int i = 0; i < N_TERMS; i++){
strcat(Array, term); //strcat adds the second string to the end of the first
}
printf("%s", Array); //prints the entire string
return 0;
}
A char is one character. Which would be in single quotes not double quotes. "[ ]" is three character. [, the space and ] are together three characters. Each index in a char array can only hold one character at a time, so the [ or the space or the ] or some other character.
I want to make a program that handles strings in 2d arrays in the following manner:
Each row represents one name only, while columns holds separate characters of each name.
Like so:
0 1 2 3 4 5
0 K e v i n \0
1 J o h n \0
2 L u c y \0
Now, the way I understand arrays is that they work as pointers for the first element. So when I read the string using the readstring(name) function even though I used a 1D array, it should work as a pointer to the 2D array and store each string as I showed above, right?
The following code is supposed to ask for three names then print them all, but it only prints the last name and some gibberish, what did I do wrong?
#include <stdio.h>
#include <stdlib.h>
void readstring(char name[]);
void get_data(char name[][15]);
void show_data(char name[][15]);
int main()
{
char name[3][15];
get_data(name);
show_data(name);
return 0;
}
void get_data(char name[][15]){
int i=0;
for(i=0;i<3;i++){
printf("\nEnter name: ");
readstring(name);
}
}
void show_data(char name[][15]){
int i;
for(i=0;i<3;i++){
printf("%s",name[i]);
}
}
void readstring(char str[]){
int i=0;
while((str[i++]=getchar())!='\n' && i<15);
str[i]='\0';
}
The output shows like this:
http://i58.tinypic.com/e7i048.jpg
The problem is here:
readstring(name);
Change it to:
readstring(name[i]);
The problem is that name is a 2 - d array, or , an array of strings. Therefore, to access one string in the array of strings, you need to use an index for that particular string.
In fact, the calling function readstring() expects a string as an argument.
I have this simple problem to which I am trying to write a solution, in C.
If an array arr contains n elements, then write a program to check
if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.
And my code looks like this-
#include<stdio.h>
int main()
{
int arr[10],i=0,j;
int k=0;
printf("\n Enter 10 positive integers: \n");
for(k=0;k<=9;k++)
scanf("%d",&arr[k]);
while(i<=9)
{
for(j=9;j>=0;j--)
{
if(arr[i]==arr[j])
{
printf("\n The array element %d is equal to array element %d\n", arr[i],arr[j]);
}
i++;
continue;
}
}
return 0;
}
On entering this input-
Enter 10 positive integers:
10
20
30
40
50
60
40
80
20
90
The output I get is-
The array element 20 is equal to array element 20
The array element 40 is equal to array element 40
The array element 40 is equal to array element 40
The array element 20 is equal to array element 20
Now, there are two problems with this code-
As you can see, the program prints out matching array elements twice. This is because, the way I've structured the program, once the variable i loops through the array from the first to last element, and then j loops through from the last to first element. So each prints out the matching array element once, leading to two sets of values.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
I've read that, in C, array dimensions(when declaring) cannot be a variable. So, a declaration like this(which was my first thought) wouldn't work-
int n; // n is no. of elements entered by the user
int arr[n];
I'm a newbie to programming, so my apologies if the question sounds/is too simple, low-quality.
Thank You.
1)You can traverse the array for half times for getting the prints only once. Instead of for(j=9;j>=0;j--) you can use for(j=9;j>=9/2;j--).
2)
int n;
int arr[n].
Recent Compilers support this statement. If you don't like to use this, you can go for dynamic memory allocation for the array.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
Use dynamic memory allocation. Use malloc().
So code will be
{
int num_elements;
int* arr;
printf("Enter number of elements\n");
scanf("%d", &num_elements);
arr = (int *) malloc(num_elements * sizeof(int)); // Use this 'arr' for holding input data from user
// Your remaining code comes here
free(arr); // Free the pointer in the end of program
}
the variable length creation works for me:
#include<stdio.h>
int main(){
int a, i;
scanf("%i", &a);
int blah[a];
for (i = 0; i < a; i++){
printf("/n%i", blah[a]);
}
}
The other way would be to create the maximum length array and than simply use first n elements.
As the previous answer states it is up to you to make sure you are checking each element only once therefore stopping at the element n/2. It is probably important that n/2 is rounded to the closest smaller integer, so at first glance odd numbers of arguments may be differently handled. But as it is omitting only the middle element it is identical to itself.
For your first query
for(i=0;i<n/2;i++)
{
if(a[i]==a[n-(i+1)])
{
printf("\n The array element %d is equal to array element %d\n",a[i],a[n-(i+1)]);
}
}
For your second query you can use condition i<(n/2) (which runs the loop (n/2)-1 times) For your case where n = 10 it will run from 0 to 4.
If you want to loop from 0 to 9 you can use
for(i=0;i<n;i++)
For making array of n elements where n is a variable either make an array of elements that is always greater than n or do it by making a dynamic array.
http://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
corrected:
#include<stdio.h>
int main()
{
int i=0, size; // size of array
int k=0; // counter
printf("enter size of array\n");
scanf("%d", &size); // ask user for desired size
int *arr = malloc(size * sizeof(int)); // allocate memory for array
printf("\n Enter 10 positive integers: \n"); // fill your array of size size
for(k=0;k<size;k++)
scanf("%d",&arr[k]);
k = 0; // reset this counter
for(i=0; i<size/2; i++) // check only for half of it
{
if(arr[i] == arr[size-i-1]) // try it with paper and pincil
{
printf("match arr[%d]=arr[%d]=%d\n", i,size-i-1, arr[i]);
k++;
}
}
if(k==0) printf("No matching");
return 0;
}
I am breaking my head on this but cannot proceed so please help.
Working on a programming assignment:
INPUT:
First line contains a value N representing the dimension of the input matrix, followed by N lines, each line representing a row of the matrix. Within each row, N values are given and are separated by whitespace.
So instead of using fgets() and then extracting the digits using strtol() I am forced to use scanf() because the assignment platform does not work properly with strtol().
This is my program:
int main()
{
int N;
int arr[N][N];
int idx1, idx2=0;
scanf("%d ",&N);
for (idx1=0; idx1<N; idx1++) {
for(idx2=0; idx2<N; idx2++) {
scanf("%d", &arr[idx1][idx2]);
printf("arr[%d][%d]=%d ", idx1, idx2, arr[idx1][idx2]);
}
}
printf("\n");
for (idx1=0; idx1<N; idx1++) {
for(idx2=0; idx2<N; idx2++) {
printf("arr[%d][%d]=%d ", idx1, idx2, arr[idx1][idx2]);
}
}
return 0;
}
Output:
3
1 2 3
arr[0][0]=1 arr[0][1]=2 arr[0][2]=3
4 5 6
arr[1][0]=4 arr[1][1]=5 arr[1][2]=6
7 8 9
arr[2][0]=7 arr[2][1]=8 arr[2][2]=9
arr[0][0]=1 arr[0][1]=4 arr[0][2]=7 arr[1][0]=4 arr[1][1]=7 arr[1][2]=8 arr[2][0]=7 arr[2][1]=8 arr[2][2]=9
FWIW gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Why is the second output not matching the first? What am i missing here?
int N;
int arr[N][N];
int idx1, idx2=0;
scanf("%d ",&N);
You have to declare arr after you write N object. Here when arr is declared, N value is indeterminate.
If you want to create a variable length array like that, you need to dynamically allocate it instead of creating an array of size N (N has some garbage value at the time) and then changing the size of it based on user input. Use malloc or calloc.