Thread: inserting an element into an array

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    63

    inserting an element into an array

    Code:
    #include<stdio.h>
     #include<conio.h>
     void main()
     {
     int a[11],i,j,k,ch,sh,e;
     clrscr();
     printf("enter array elements:");
     for(i=0;i<10;i++)
     scanf("%d",&a[i]);
     printf("enter choice\n1.in between insertion\n2.insertion in the beginning\n3.insertion at the end");
     scanf("%d",&ch);
     switch(ch)
     {case1:
     printf("enter the element:");
     scanf("%d",&e);
     printf("enter the element after which the number has to be inserted:");
     scanf("%d",&sh);
     for(i=0;i<10;i++)
     {
     if(a[i]==sh)//finding the element
     break;
     }
     for(k=9;k>i;k--)
     a[k+1]=a[k];//shifting the element
     a[i+1]=e;
     break;
     case2:
     printf("enter the element:");
     scanf("%d",&e);
     for(k=9;k>=0;k--)
     a[k+1]=a[k];
     a[0]=e;
     break;
     case3:
     printf("enter the element:");
     scanf("%d",&e);
     a[10]=e;
     }
     printf("\n");
     for(i=0;i<11;i++)//display the result
     printf("%d",a[i]);
     getch();
     }
    the above program is for INSERTING AN ELEMENT INTO AN ARRAY.but when i run this code it gives me very weird output....it doesn't print the "enter the element after which the number has to be inserted "line and also when i enter choce 1.that means in
    between insertion//
    the output is like:
    enter the array:
    1 2 3 4 5 6 7 8 9 10
    enter the choice:1.in between 2.in the beginning 3.at the end.
    when i enter choice 1.in bwetween it prints..enter the element:suppose i enter 30
    then it immediately prints
    array after insertion is:1 2 3 4 5 6 7 8 9 10 30 52 33 30
    and the same output for in beginning and at the end....what do i do now?where is the error?i don't know plz help me out ??/


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You might consider the delights of

    int main

    meaningful variable names

    and some indentation in your code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Posts
    63
    could any 1 help me out here??? with my program..........?plz tell me the errors in my program
    ????????

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    63
    whar the changes that i can make in my program in order to run it correctly??????with all the 3 choices..,..???

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Quote Originally Posted by galmca
    could any 1 help me out here??? with my program..........?plz tell me the errors in my program
    ????????

    whar the changes that i can make in my program in order to run it correctly??????with all the 3 choices..,..???
    salem said it best:
    Quote Originally Posted by salem
    You might consider the delights of

    int main

    meaningful variable names

    and some indentation in your code.

  6. #6
    Registered User
    Join Date
    Sep 2004
    Posts
    63
    what's wrong with my code here?can any 1 plz tell me that?

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well I could easily tell you, but I'm waiting to see if you're capable of formatting your code.

    No doubt some of your problems would be evident if you just made a decent attempt to format your programs rather than just mushing everything together like you do at present.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    galmca, you may want to consider signing up for the Obfuscated Code Contest Here!
    j/k j/k :P

    1. conio.h is not very portable, so take that out along with clrscr().
    2. case1: is written wrong, it should be: case 1: with a space.
    3. getch(); is not very portable, you will probably want to replace that with getchar(); that is located I believe in stdio.h.
    4. Change void main() to int main(void) for issues concerning whacko returns to the system and main() meaning infinite parameters and main(void) meaning 0 parameters.
    5. Make sure you return 0; at the end of your int main() function for certain reasons (like int main() returning some whacko #).
    6. You can change int a[11] to int a[10] because I believe you don't use the 11th index of the integer array.
    7. Instead of scanf(), since you're getting a character from the user, just use getchar();
    8. I changed statements like: printf("enter the element:"); to puts("Enter the Element: "); just because of my preference, you had no problems there.
    9. I changed the a variable to cElements to better distinguish the variable.
    10. Sometimes I wasn't totally sure what the for loop was looping :(, so I just added brackets the best I could.
    11. I probably screwed it all up again :(

    Here's the fixed code: *
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    // Used for flushing newlines after input
    #define FLUSHINPUT while( (fc=getchar()) != EOF && fc != '\n');
    
    int main(void) {
    	int cElements[10],i,j,k,sh,e;
    	int c;	/* Temperary character holder used by getchar(); */
    	int fc;	/* Temperary character used for flushing */
    	puts("Enter 10 Numbers:");
    
    	for(i=0;i<10;i++) {
    		c = getchar();
    		if(isdigit(c))
    			cElements[i] = c;
    		else
    			exit(1);
    
    		/* Flush out the newlines */
    		FLUSHINPUT
    	}
    
    	printf("Enter choice\n1. In between insertion\n2. Insertion in the beginning\n3. Insertion at the end\n");
    	c = getchar();
    	if(!isdigit(c))
    		exit(1);
    
    	/* Flush out the newlines */
    	FLUSHINPUT
    
    
    	switch(c) {
    		case '1':
    			puts("Enter the Element: ");
    			e = getchar();
    			if(!isdigit(e))
    				exit(1);
    			FLUSHINPUT
    
    			puts("Enter the element after which the number has to be inserted:\n");
    			sh = getchar();	/* Only 0-9 works for this version lol :( */
    			FLUSHINPUT
    			for(i=0; i<10; i++) {
    				if(cElements[i] == sh)	//finding the element
    					break;
    			}
    			for(k=9;k>i;k--)
    				cElements[k+1]=cElements[k];//shifting the element
    
    			cElements[i+1]=e;
    			break;
    		case '2':
    			puts("Enter the Element: ");
    			e = getchar();
    			if(!isdigit(e))
    				exit(1);
    			FLUSHINPUT
    
    			for(k=9;k>=0;k--)
    				cElements[k+1] = cElements[k];
    
    			cElements[0] = e;
    			break;
    		case '3':
    			puts("Enter the Element: ");
    			e = getchar();
    			if(!isdigit(e))
    				exit(1);
    			FLUSHINPUT
    
    			cElements[10]=e;
    		default:
    			puts("Choice Error");
    			exit(1);
    	}
    
    	printf("\n");
    	for(i=0; i<10; i++)	/* Display Result */
    		printf("%d\n", cElements[i]);
    	getchar();
    	return 0;
    }
    * Maybe...

  9. #9
    Quote Originally Posted by Kleid-0
    galmca, you may want to consider signing up for the Obfuscated Code Contest Here!
    j/k j/k :P
    Now that's what I'm talking about!

    In fact I have had a few run-ins with galmca in the past. I would have thought he learned from his previous mistakes.


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  10. #10
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    galmca, Go To This Website , and then go to doctors and get fixed. Then come back. lol :P I feel I'm being mean :(

  11. #11
    Registered User
    Join Date
    Sep 2004
    Posts
    63
    Code:
    #include <stdio.h>
    #define SIZE 10
    
    int main()
    {
    int a[ SIZE ];
    int i,n,pass,hold;
    printf("enter the number of elements in an array:");
    scanf("%d",&n);
    
    printf( "Data items in original order\n" );
    
    for ( i = 0; i <= SIZE - 1; i++ )
    printf( "%4d", a[ i ] );
    
    for ( pass = 1; pass <= SIZE - 1; pass++ )
    
    for( i = 0; i <= SIZE - 2; i++ )
    printf( "%d %d ", a[ i ], hold );
    if ( a[ i ] > a[ i + 1 ] ) {
    hold = a[ i ];
    a[ i ] = a[ i + 1 ];
    a[ i + 1 ] = hold;
    }
    
    printf( "\nData items in ascending order\n" );
    
    for ( i = 0; i <= SIZE - 1; i++ )
    printf( "%4d", a[ i ] );
    
    printf( "\n" );
    
    return 0;
    }
    the above program is for bubble sorting....
    but it is not running properly....when i enter number of elements in an array:7
    and enter array elements:5 10 15 14 16 18 20 ....it prints...some weird output of array in ascending order :1280315..1280313..etc..and then prints data items in ascending order after bubble sorting is:5 10 15 16 18 20...
    whats wrong with the code?plz make some necessatu changes and plz explain th code if u can to make the program run successfully...im really confused now...????could u plz explain the functioning of for loops... here,,,???im confused now how is that working ..why have we taken i=size -2?in the for loop?plz explain the for loops ?
    and plz make my program run correctly....its not showing any error but not running properly......

    Sponsored Links

  12. #12
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    you forgot to scan the information into the array.

    >> for ( i = 0; i <= SIZE - 1; i++ )

    no big deal but it's usually written:

    Code:
    for ( i = 0; i < SIZE; i++ )
    // and for the bubble sort loop:
    for( i = 0; i < SIZE - 1; i++ )
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  13. #13
    ---
    Join Date
    May 2004
    Posts
    1,379
    AT LEAST indent your code.

  14. #14
    Registered User Scribbler's Avatar
    Join Date
    Sep 2004
    Location
    Aurora CO
    Posts
    266
    I'd almost try to pick them apart, since he's learned to use code tags, however I'm hesitant to do somebody's homework assignment for them.

  15. #15
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    ok ok ok ....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Absolute value of each element in a given array
    By DriftinSW20 in forum C Programming
    Replies: 9
    Last Post: 11-15-2007, 04:08 PM
  2. Modify an single passed array element
    By swgh in forum C Programming
    Replies: 3
    Last Post: 08-04-2007, 08:58 AM
  3. Replies: 19
    Last Post: 07-20-2007, 01:46 AM
  4. Deleting an element from an array
    By Matt13 in forum C Programming
    Replies: 7
    Last Post: 11-19-2003, 04:42 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM