C programming introduction

Discussion in 'Programmer's Corner' started by anukalp, Jul 31, 2018.

  1. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    Thank you for your assistance in this matter. I appreciate your help

    This program does exactly what you're saying

    Code (Text):
    1. #include<stdio.h>
    2. int main()
    3. {
    4.    int array[5] = { 5, 6, 7, 8, 9};
    5.    int i = 0;
    6.  
    7.    printf("%d, %d, %d, %d, %d", array[0], array[1], array[2],  array[3], array[4]);
    8.  
    9.    return 0;
    10. }
    5, 6, 7, 8, 9
     
  2. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    But you are losing site of the big picture -- we are exploring using arrays to efficiently solve problems and we are working with "toy" problems to keep things simple. So while we might be working with five values in our little programs here, we are trying to develop skills and techniques that allow us to write programs that solve similar problems but that are MUCH larger in scale.

    Even with this toy problem, try to apply your approach here to your prior program in which you asked the user to enter how many data elements were going to get stored in the array. Since you don't know how many data elements they are going to work with, you would have to have a huge set of if() statements to trap each one. And then what if the size of the problem could have them entering thousands of data values.

    So you want to use a loop to print out your comma-separate list.
     
  3. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    Check it this program
    Code (Text):
    1. #include<stdio.h>
    2.  
    3. int main (void)
    4. {
    5.     int i, j, k, loop, number, size;
    6.  
    7.     int sum = 0;
    8.  
    9.     int array[20];
    10.  
    11.     printf ( "Array Size :  " ) ;
    12.  
    13.     scanf ( "%d",  &size ) ;         /* Get the size of array */
    14.      if ( size  >  0 && size  <  20 )    /* Check valid size */
    15.      {
    16.  
    17.         /* Loop to repeat process two times */
    18.  
    19.         for ( loop  =  0; loop  <  2; loop++ )
    20.         {
    21.               printf ( "\nEnter array Elements \n" ) ;
    22.        
    23.        
    24.            for ( i = 0; i  <  size ;  i++ )
    25.        
    26.           {
    27.               scanf ( "%d",  &array[i] ) ;    /* Store array elements */
    28.            }
    29.        
    30.            printf ( "value : ",  array[i] ); /*Print list of values on one line */
    31.        
    32.            for ( j = 0;  j  <  size;  j++ )
    33.            {
    34.                printf ( " %d ",  array[j] ) ;
    35.            }
    36.        
    37.            for( k = 0; k  <  5;  k++ )
    38.            {
    39.                sum = sum + array[k] ;
    40.  
    41.            }
    42.               printf ( "\nsum : %d ",  sum );   /* Print out the sum of the five values */
    43.          
    44.             sum  =  0 ;
    45.        
    46.             printf ( "\nEnter number : "  ) ;  /*Ask the user which value they want to double,  */
    47.  
    48.             scanf ( "%d", &number ) ;
    49.  
    50.             {
    51.               if ( ( 0 <= number ) && ( number <  5 ) )
    52.      
    53.                {
    54.                   printf ( "Double value : %d \n",  array[number] * 2 ) ;
    55.                }
    56.                 else
    57.                {
    58.                   printf ( "invalid number \n" ) ;
    59.                }
    60.             }
    61.         }
    62.      }    
    63.        
    64.     else
    65.     {
    66.       printf ( "Array size  is not acceptable" ) ;
    67.     }
    68.    
    69.     return 0;
    70. }

    Array Size : 5

    Enter array Elements
    1
    2
    3
    4
    5
    value : 1 2 3 4 5
    sum : 15
    Enter number : 3
    Double value : 8

    Enter array Elements
    5
    4
    3
    2
    1
    value : 5 4 3 2 1
    sum : 15
    Enter number : 3
    Double value : 4
     
    Last edited: Aug 4, 2018
  4. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    Progress.

    However, your code has some problems (including some that were previously pointed out to you. Run your program with the following input:

    First pass: 8 values: 100, 200, 300, 400, 500, 600, 700, 800
    Have it double value #6 (the 700)

    Second pass: 3 values: 1, 2, 3
    Have it double value #4 (which doesn't exist).

    Do you see some of the problems?

    You also aren't doing what the problem statement requested. Are you trying to, or just doing something different? Either is fine, but I need to know which in order to provide useful feedback.

    Assuming you are trying solve the problem as stated, notice that the user is only entering a single data set. The problem then prints out that data set and it's sum. Then it asks the user which value within the original data set should get doubled (with the first value being value #1) and prints out the modified data set and the sum of the modified data set.

    You also aren't printing out the commas between the values (and only between them).
     
    anukalp likes this.
  5. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    One thing you want to get in the habit of doing is formatting your code cleanly and consistently. You aren't doing too bad (much better than most) and formatting code when posting to the forum is admittedly a pain because (in most browsers) you have to enter the code in a proportional-spaced font but it will be displaced monospace (and, unfortunately, if you copy/paste from another source multiple spaces are reduced to a single space -- very annoying) so you just have to count spaces as you type.

    One thing that can make your code more readable is to not use enclosing braces for single line blocks of code. But there is a downside in that if you later add a second line you may forget to add the now-mandatory braces. There are different schools of thought on this one.

    Below is your reformatted code (I've done nothing else to it).

    Code (Text):
    1. #include<stdio.h>
    2.  
    3. int main (void)
    4. {
    5.    int i, j, k, loop, number, size;
    6.    int sum = 0;
    7.    int array[20];
    8.  
    9.    printf ( "Array Size :  " ) ;
    10.    scanf ( "%d",  &size ) ;         /* Get the size of array */
    11.  
    12.    if ( size  >  0 && size  <  20 )    /* Check valid size */
    13.    {
    14.  
    15.       /* Loop to repeat process two times */
    16.       for ( loop  =  0; loop  <  2; loop++ )
    17.       {
    18.          printf ( "\nEnter array Elements \n" ) ;
    19.        
    20.          for ( i = 0; i  <  size ;  i++ )
    21.             scanf ( "%d",  &array[i] ) ;    /* Store array elements */
    22.      
    23.          printf ( "value : ",  array[i] ); /*Print list of values on one line */
    24.      
    25.          for ( j = 0;  j  <  size;  j++ )
    26.             printf ( " %d ",  array[j] ) ;
    27.      
    28.          for( k = 0; k  <  5;  k++ )
    29.             sum = sum + array[k] ;
    30.  
    31.          printf ( "\nsum : %d ",  sum );   /* Print out the sum of the five values */
    32.          
    33.          sum  =  0 ;
    34.        
    35.          printf ( "\nEnter number : "  ) ;  /*Ask the user which value they want to double,  */
    36.          scanf ( "%d", &number ) ;
    37.  
    38.          if ( ( 0 <= number ) && ( number <  5 ) )
    39.             printf ( "Double value : %d \n",  array[number] * 2 ) ;
    40.          else
    41.             printf ( "invalid number \n" ) ;
    42.       }
    43.    }  
    44.    else
    45.       printf ( "Array size  is not acceptable" ) ;
    46.    
    47.    return 0;
    48. }
    Cleaning up the formatting let me see a problem that I didn't see before.

    It's now obvious that the

    printf ( "value : ", array ); /*Print list of values on one line */

    statement is not included in the for() loop above it. This made me look a bit closer and I can see that this statement can't produce the output you show -- you've tweaked the code someone between running it and pasting it into your post. The printf() statement above lacks a format specifier, so it will not even look at the second argument. Which is just as well because the second argument, if size = 5, is array[5] (since that is the value of size with the for() loop exits), which has not been set by the user.

    Now let's clean up the code a bit -- without changing the logic any.

    You use a different variable in each of your for() loops. This is generally not recommended unless it is necessary to do so, for the symbol reason that people reading your code will be led to believe that it is necessary to do so when they see you do this and waste a bunch of time figuring out that your code doesn't actually need to do this. So when you have a dummy variable used as a loop counter, try to use the same one. An even better way is to make the variable local to the loop, but we can discuss that at some later time.

    Another style problem is with your initialization of sum. You do it in two places and neither is a good place. The first one is unnecessarily far from where it is needed and the second is needed for the next iteration of the loop by code that precedes it. Try to see if there is a single place that you can initialize loop that is close to where it is used. This makes the code more modular.

    Another common style (but there are others) is to put a space between control structures and opening parens but to not do so between a function name and the opening parens. What matters more is being consistent. You code was pretty consistent -- just a single place where you didn't have a space in both cases.

    Code (Text):
    1. #include<stdio.h>
    2.  
    3. int main(void)
    4. {
    5.    int i, loop, number, size, sum;
    6.    int array[20];
    7.  
    8.    printf( "Array Size :  " ) ;
    9.    scanf( "%d",  &size ) ;         /* Get the size of array */
    10.  
    11.    if ( (size > 0) && (size < 20) )    /* Check valid size */
    12.    {
    13.  
    14.       /* Loop to repeat process two times */
    15.       for ( loop = 0; loop < 2; loop++ )
    16.       {
    17.          printf( "\nEnter array Elements \n" ) ;
    18.        
    19.          for ( i = 0; i < size ; i++ )
    20.             scanf( "%d",  &array[i] ) ;    /* Store array elements */
    21.      
    22.          printf( "value : ",  array[i] ); /* Print list of values on one line */
    23.      
    24.          for ( i = 0; i < size; i++ )
    25.             printf ( " %d ",  array[i] ) ;
    26.      
    27.          sum = 0;
    28.          for ( i = 0; i < 5; i++ )
    29.             sum = sum + array[i] ;
    30.          printf( "\nsum : %d ",  sum );   /* Print out the sum of the five values */
    31.        
    32.          printf( "\nEnter number : "  ) ;  /* Ask the user which value they want to double,  */
    33.          scanf( "%d", &number ) ;
    34.  
    35.          if ( ( 0 <= number ) && ( number <  5 ) )
    36.             printf( "Double value : %d \n",  array[number] * 2 ) ;
    37.          else
    38.             printf( "invalid number \n" ) ;
    39.       }
    40.    }  
    41.    else
    42.       printf( "Array size  is not acceptable" ) ;
    43.    
    44.    return 0;
    45. }
    Again, I haven't changed the logic of your code at all. It still has the bugs I pointed out earlier.

    There are some other things that could be done to clean up the code, but they involve introducing some things you might not have seen yet, so I'll leave those alone for now.
     
  6. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    I've written following program to complete all requirement

    Code (C):
    1. #include <stdio.h>
    2.  
    3. int PassValue, loop, size , i, j, k, sum, number, array[20];;
    4.  
    5. int main ()
    6. {
    7.     printf ("How many pass you want to check : ");
    8.     scanf ("%d", &PassValue);
    9.  
    10.         if  ( PassValue  >  0 && PassValue  <  8 )    /* Check valid pass  */
    11.         {
    12.              printf("pass : %d \n", PassValue);
    13.         }
    14.        else
    15.         {
    16.  
    17.             printf("Please try again \n");
    18.             printf("Pass value you enterd is not valid \n");
    19.             printf("1. Pass value shouldn't be more then 8 \n");          
    20.             printf("2. You can't enter neagtive value \n");
    21.      
    22.          
    23.             while (!( PassValue  >  0 && PassValue  <  8 ))
    24.             {
    25.                   printf ("How many pass you want to check :");
    26.                   scanf ("%d", &PassValue);
    27.            
    28.                   printf("Please try again \n");
    29.                   printf("Pass value you enterd is not valid \n");
    30.                   printf("1. Pass value shouldn't be more then 8 \n");
    31.                   printf("2. You can't enter neagtive value \n");
    32.      
    33.                   if ( PassValue >  0 && PassValue  <  8 )                
    34.                   {
    35.                        printf("pass : %d \n", PassValue);
    36.                        break;
    37.                   }
    38.             }
    39.          
    40.         }
    41.          
    42.     /* Loop to repeat process n times */
    43.     for ( loop  =  0; loop  <  PassValue; loop++ )
    44.         {
    45.             printf ("Enter array size : ");
    46.             scanf ("%d", &size);
    47.  
    48.             if ( size >  0 && size  <  32 )    /* Check valid size */
    49.             {        
    50.                 printf("Entered Array size : %d \n", size);
    51.             }
    52.            
    53.             else
    54.             {
    55.                 printf("Please try again \n");
    56.                 printf("size you enterd is not valid \n");    
    57.                 printf("1. number shouldn't be more then 32 \n");              
    58.                 printf("2. You can't enter neagtive value \n");
    59.          
    60.                 while (!( size >  0 && size <  32 ))
    61.                 {                
    62.                     printf ("Enter array size ");
    63.                     scanf ("%d", &size);
    64.          
    65.                     printf("Please try again \n");
    66.                     printf("size you enterd is not valid \n");    
    67.                     printf("1. number shouldn't be more then 32 \n");              
    68.                     printf("2. You can't enter neagtive value \n");
    69.                  
    70.                     if(size >  0 && size  <  32 )
    71.                     {
    72.                        printf("Entered  array size : %d \n", size);
    73.                        break;
    74.                     }
    75.                 }
    76.             }
    77.                  
    78.                  
    79.             printf ( "\nEnter array Elements \n" ) ;
    80.    
    81.             for ( i = 0; i  <  size ;  i++ )
    82.                 scanf ( "%d",  &array[i] ) ;      
    83.                 printf ( "value : ",  array[i] );
    84.  
    85.             for ( j = 0;  j  <  size;  j++ )
    86.                 printf ( " %d ",  array[j] ) ;
    87.  
    88.             for( k = 0; k  <  size;  k++ )
    89.                 sum = sum + array[k] ;
    90.                 printf ( "\nsum : %d  ",  sum );   /* Print out the sum of the five values */
    91.             sum  =  0 ;
    92.  
    93.             printf ("\nEnter number you want to double : ");
    94.             scanf ("%d", &number);
    95.            
    96.                if ( number >  0 && number  <  size )    /* Check valid number */
    97.                {
    98.                   printf("Enterd number : %d \n", number);
    99.                }
    100.            
    101.                else
    102.                {
    103.                    printf("Please try again \n");    
    104.                    printf("number you enterd is not valid \n");    
    105.                    printf("1. number shouldn't be more then size \n");              
    106.                    printf("2. You can't enter neagtive value \n");
    107.            
    108.          
    109.                    while (!( number >  0 && number <  size ))
    110.                    {
    111.                         printf ("\nEnter number you want to double :");
    112.                         scanf ("%d", &number);
    113.                         printf("Please try again \n");    
    114.                         printf("number you enterd is not valid \n");    
    115.                         printf("1. number shouldn't be more then size \n");              
    116.                         printf("2. You can't enter neagtive value \n");
    117.      
    118.                        if(number >  0 && number <  size)
    119.                        {                
    120.                            printf("Enterd number : %d \n", number);
    121.                            break;
    122.                        }
    123.                     }
    124.                }                
    125.          
    126.             printf ( "Double value : %d \n",  array[number] * 2 ) ;
    127.       }
    128.  
    129.     return 0;
    130. }
    131.  
    Program gives following output

    How many pass you want to check : 2
    pass : 2
    Enter array size : 8
    Entered Array size : 8

    Enter array Elements
    100
    200
    300
    400
    500
    600
    700
    800
    value : 100 200 300 400 500 600 700 800
    sum : 3600
    Enter number you want to double : 6
    Enterd number : 6
    Double value : 1400
    Enter array size : 3
    Entered Array size : 3

    Enter array Elements
    1
    2
    3
    value : 1 2 3
    sum : 6
    Enter number you want to double : 4
    Please try again
    number you enterd is not valid
    1. number shouldn't be more then size
    2. You can't enter neagtive value

    Enter number you want to double :2
    Please try again
    number you enterd is not valid
    1. number shouldn't be more then size
    2. You can't enter neagtive value
    Enterd number : 2
    Double value : 6
     
    Last edited by a moderator: Aug 6, 2018
  7. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    I am stuck I don't have any idea how to remove last commas.
    I tried to follow that style but I was getting so many errors so I used enclosing braces
    I would try my best for code formatting
     
  8. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    What in the problem specifications says anything about making multiple passes?

    The first part of solving a problem is making sure you understand the problem -- it is also often the hardest part of problem solving, particularly in the real world.

    So let's review the problems specifications very carefully:

    1) Write a program that asks the user for five integer values.
    2) Print them out as a comma-separated list of values on one line.
    3) Print out the sum of the five values on the next line.
    4) Ask the user which value they want to double, with 1 being the first value entered and 5 being the last value entered.
    5) Print out the five values again.
    6) Print out the sum of the five values on the next line.

    This problem is very narrow in it's focus. Don't go expanding it until you can solve this narrow version of it.

    The point of the problem is to practice using arrays to solve problems.

    In step #1 you are told to ask the user for five integer values. You are not told to ask the user for how many values they want to enter. You are told to ask them for five values. Nothing more, nothing less.
    In step #2 you are told to print out those five values as a comma-separated list on one line.
    In step #3 you are told to print out the sum of those five values on the next line.
    In step #4 you are told to ask the user which of the original five values they want to double, with a 1 being the first value and 5 being the last value.
    In step #5 you are told to print the list of values again. This should also be as a comma-separated list on one line and should be identical to the original list except that one of the values should be twice as large.
    In step #6 you are told to print out the sum of the five values on the next line. This number should be equal to the original sum printed out earlier plus the original value of the number they chose to double.

    Other than error checking (and graceful death is perfectly acceptable at this stage), your program should do NOTHING beyond what the problem specifies. In fact, it is perfectly reasonable to initially solve the problem assuming that nothing will go wrong and add the error checking later (though another school of thought says to do the input validation first before writing any code that actually solves the problem -- both approaches have pros and cons).

    You've got many of the pieces in place, but you keep going off on a tangent and ignoring the details of the problem. Focus on the specifics of the problem.
     
  9. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    I tried to make universal program to complete following requirement
    1. Ask user how many pass they want limit (0 – 8)
    2. Ask user for array size limit (0-32)
    3. If the array size is not valid then ask user until he doesn’t enter correct array size
    4. if the array size is valid then store number into array
    5. Print out the sum of the array values on the next line
    6. Ask the user which value they want to double, with 0 being the first value entered and size being the last value entered.
    7. Print the double value
    8. Repeat process as user want -pass value
    If you want the program as you said I will do it but, Is it not complete requirement you said?

    if you type input as you said it will give output you wanted. I am sure because I have tested it many time on my computer GCC tool
     
    Last edited: Aug 6, 2018
  10. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    So let's consider this aspect of the problem in detail.

    Problem:

    Given n values stored in an int array, print them out as a single-line comma-separated list.

    So let's flesh out exactly what has to happen to make a single-line comma-separated list of values.

    #1) Print out the first value.
    #2) FOR each remaining value.
    #2a) Print a comma followed by a space.
    #2b) Print the value.
    #3) Print the end of line (newline character).

    Let's assume that we have int variables i and n declared where n is equal to the number of values stored in the array. We also have an int array names data that is appropriately dimensioned and already has the data stored in it.

    Let's do exactly what our list above says

    Code (Text):
    1. printf("%d" data[0])
    2. for(i = 1; i < n; i++)
    3. {
    4.    printf(", ");
    5.    printf("%d", data[i]);
    6. }
    7. printf("\n");
    Do you see what I did? I broke the problem into a set of small tasks such that each task could be translated easily into a code fragment that performs that small task.

    Is this the only way to solve this problem? No. There are many ways. Let's look at a couple.

    #1) FOR each value.
    #1a) Print the value.
    #1b) IF the value is not the last value.
    #1b1) Print a comma followed by a space.
    #2) Print the end of line (newline character).

    The code that this translates to is:

    Code (Text):
    1. for(i = 0; i < n; i++)
    2. {
    3.    printf("%d", data[i]);
    4.    if ( i != n - 1 )
    5.       printf(", ");
    6.  
    7. }
    8. printf("\n");
    Here's another variant:

    #1) FOR each value.
    #1a) IF the value is not the first value
    #1a1) Print a comma followed by a space.
    #1b) Print the value.
    #2) Print the end of line (newline character).

    Code (Text):
    1. for(i = 0; i < n; i++)
    2. {
    3.    if ( i != 0 )
    4.       printf(", ");
    5.    printf("%d", data[i]);
    6. }
    7. printf("\n");
    Yet another variant that represents a little bit more refined approach:

    #1) FOR each value.
    #1a) Print the value.
    #1b) IF the value is the last value.
    #1b1) Print the end of line (newline character).
    #1c) ELSE
    #1c1) Print a comma followed by a space.

    Which becomes:

    Code (Text):
    1. for(i = 0; i < n; i++)
    2. {
    3.    printf("%d", data[i]);
    4.    if ( i == n - 1 )
    5.       printf("\n");
    6.    else
    7.       printf(", ");
    8. }
    As a teaser of things you can do (so don't be concerned if this looks confusing right now -- you'll get to it at some point), you can tighten this up quite a bit as follows:

    Code (Text):
    1. for(i = 0; i < n; i++)
    2.    printf("%d%s", data[i], (i == n-1)? "\n" : ", ", data[i]);
    This used the "conditional operator", also known as the "ternary" operator. When you get to that point, come back and see if you can understand what this is doing.

    Oh -- and note that I haven't compiled and run these snippets, so it's possible that a mistake snuck and that I didn't catch. I'm more than happy to correct anything that gets spotted.

    That's fine. It's a valid approach, but you do need to be able to read and write code that doesn't enclose single statements, both because you will see a lot of code that uses that style and because, if you can't, that means that you really don't know program structure and syntax very well. But it isn't something that has to happen overnight.
     
    anukalp likes this.
  11. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    If you want to solve a different problem, fine. But notice how you posted the program requirements as I stated them, then claimed that you had written a program that satisfied those requirements, the posted code that solved some other unstated set of requirements and NOT the program requirements as posted. That's a recipe for nothing but confusion.

    Also note that the requirements listed above do not match what your program does. Your program prints out the values on a single line with only a space between them. Which of the requirements above involves doing that?

    You also have created additional problems similar to ones you had before. You ask the user for an array size with a limit of 0 to 32. But you dimension your array for 20. If the user enters 30, where does the rest of the data go?

    Run your program and enter 0 as the array size. Does it do what you expect? Now run it and enter 32 as the array size. Does it do what you expect?
     
    anukalp likes this.
  12. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    I am stuck in step five. How to replace double value with original value
    Code (C):
    1. #include<stdio.h>
    2. int main ()
    3. {
    4.     int n = 5, sum = 0;
    5.     int i, j, k, number, array[n];
    6.  
    7.     printf ("Enter Value \n");
    8.  
    9.     for (i = 0; i < n ; i++)
    10.        scanf("%d", &array[i]);
    11.    
    12.     for(i = 0; i < n; i++)
    13.     {
    14.         printf("%d", array[i]);
    15.         if ( i == 5 - 1 )
    16.             printf("\n");
    17.         else
    18.             printf(", ");
    19.     }
    20.  
    21.     for (k = 0; k < n ; k++)
    22.         sum = sum + array[k];
    23.         printf ("sum : %d", sum);
    24.    
    25.     printf ("\nEnter number \n");
    26.     scanf ("%d", &number);
    27.  
    28.     if (number >0 && number <5)
    29.       printf ("Double value : %d \n", array[number-1] * 2 );
    30.    
    31.   return 0;
    32. }
    Program output
    Enter Value
    42
    93
    17
    80
    71
    42, 93, 17, 80, 71
    sum : 303
    Enter number
    1
    Double value : 84
     
  13. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    You need to double the value that is stored in the chosen element.

    Consider the simple case of a single variable (not an array).

    If asked to enter a value for x and the user enters 42, then the value stored in x should be 42 and you then print out the value stored in x.

    If asked to double it, you do what is needed to make it so that the value stored in x becomes 84 and then you print out the value stored in x.
     
  14. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    Here is program for single variable
    Code (C):
    1. #include<stdio.h>
    2.  
    3. int main ()
    4. {
    5.     int x, Double;
    6.    
    7.     printf ("\nEnter value \n");
    8.     scanf ("%d", &x);
    9.  
    10.     printf ("x = %d \n", x);
    11.  
    12.     printf ("x = %d", x * 2);
    13.    
    14.   return 0;
    15. }
    I am stuck with array I don't understand how to replace only one value that has been double
     
  15. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    You are not doing what was specified.

    "you do what is needed to make it so that the value stored in x becomes 84 and then you print out the value stored in x."

    You are not changing the value stored in x. It is remaining whatever it was that the user entered. You are not printing out the value stored in x (in the second printf() statement, you are printing out the value stored in x multiplied by 2.

    Notice that in both lines of the specification, the print portion was identical.

    If asked to enter a value for x and the user enters 42, then the value stored in x should be 42 and you then print out the value stored in x.

    If asked to double it, you do what is needed to make it so that the value stored in x becomes 84 and then you print out the value stored in x.

    So whatever code prints out the value stored in x the first time should be identical to the code that prints out the value stored in x the second time.

    Code (C):
    1. #include<stdio.h>
    2.  
    3. int main ()
    4. {
    5.     int x, Double;
    6.  
    7.     printf ("\nEnter value \n");
    8.     scanf ("%d", &x);
    9.  
    10.     printf ("x = %d \n", x);
    11.     /* Put in one line of code here that CHANGES the
    12.         value that is stored in x so that it is twice the
    13.         value that was originally stored in x. */
    14.     printf ("x = %d \n", x);
    15.  
    16.   return 0;
    17. }
     
  16. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    I hope this is what you are asking
    Code (C):
    1. #include<stdio.h>
    2. int main ()
    3. {
    4.     int x;
    5.     printf ("\nEnter value \n");
    6.     scanf ("%d", &x);
    7.     printf ("x = %d \n", x);
    8.     x = x * 2;
    9.     printf ("x = %d \n", x);
    10.   return 0;
    11. }
    Enter value
    12
    x = 12
    x = 24
     
  17. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    Yes. Now apply that same approach to the array-based problem.
     
  18. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    I am trying. but It is difficult to replace array value with a new value. I have been trying many time but I couldn't complete it
     
  19. WBahn

    Moderator

    Mar 31, 2012
    23,153
    6,971
    Show your attempt -- I'm still not very good at reading minds.

    It is really no different than working with single variables.

    If you have a single variable x, then doubling the value stored in it can be done in several ways.

    x = 2 * x;
    x = x + x;
    x += x;
    x *= 2;

    If you want to do the same to the values stored in element 4 of an array named fred, you do the same thing. The name of the variable is merely fred[4].

    fred[4] = 2 * fred[4];
    fred[4] = fred[4] + fred[4];
    fred[4] += fred[4];
    fred[4] *= 2;

    The real power of arrays is that you can compute the index at run time, so if you set the variable i equal to 4, the following does the same thing.

    i = 4;
    fred = 2 * fred;
    fred = fred + fred;
    fred += fred;
    fred *= 2;

    And since i can be controlled by a loop counter, you can create a loop to do the same thing to every element of the array.
     
  20. anukalp

    Thread Starter Member

    Jul 28, 2018
    90
    0
    This is my attempt
    Code (C):
    1. #include<stdio.h>
    2. int main ()
    3. {
    4.     int n = 5, sum = 0;
    5.     int i, j, k, number, array[n];
    6.     printf ("Enter Value \n");
    7.     for (i = 0; i < n ; i++)
    8.        scanf("%d", &array[i]);
    9.  
    10.     for(i = 0; i < n; i++)
    11.     {
    12.         printf("%d", array[i]);
    13.         if ( i == 5 - 1 )
    14.             printf("\n");
    15.         else
    16.             printf(", ");
    17.     }
    18.     for (k = 0; k < n ; k++)
    19.         sum = sum + array[k];
    20.         printf ("sum : %d", sum);
    21.  
    22.     printf ("\nEnter number \n");
    23.     scanf ("%d", &number);
    24.     if (number >0 && number <5)
    25.      
    26.       array[number-1] = array[number-1] * 2;
    27.       printf ("Double value : %d \n", array[number-1]);
    28.    
    29.    array[j] = array[number-1];
    30.    for (j = 0; j < n ; j++)
    31.        printf(" value : %d ", array[j]);
    32.    
    33.   return 0;
    34. }
     
Loading...