Advertisement
userxbw

while loop and arrays in C

Aug 17th, 2022
665
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. /*
  4. loops and condistionals,
  5. how to get out of a loop
  6. using them
  7. */
  8.  
  9. int main() {
  10.  
  11. char run='y';
  12. int a=0,b=0,sum=0,ct=0;
  13. int arrayFOReveryThing[2];
  14.  
  15. while(run == 'y'){
  16. /*
  17.  request input for
  18.  processing
  19. */
  20. printf("Enter an integer amount\n");
  21. scanf("%d", &a);
  22. /*just killing 2 birds with
  23.  one stone using assignment
  24.  
  25. printf to see what ct is doing */
  26.  
  27. printf("1: in loop ct=%d\n",ct);
  28.  
  29. arrayFOReveryThing[ct]=a;
  30. printf("Enter another integer amount\n");
  31. scanf("%d",&b);
  32. printf("2: in loop ct=%d\n",ct);
  33.  
  34. arrayFOReveryThing[++ct]=b;
  35. printf("Would you like to "
  36. "change the values? y/n \n");
  37. scanf(" %c",&run);
  38.  
  39. /* using a condisinal for
  40.  stopping the loop or not
  41.  
  42.  in case anything other than y
  43.  was inputed thats user error,
  44.  stop the loop anyways */
  45. if(run != 'y')
  46.     run='n';
  47. else
  48.  ct=0; // reset your counter
  49. printf("3: in loop ct=%d\n",ct);
  50. } // while loop
  51. printf("array el 0=%d\n", arrayFOReveryThing[0]);
  52. printf("array e2 1=%d\n", arrayFOReveryThing[1]);
  53.  
  54. /* printing out the sum in your
  55.    printf function */
  56. printf("Total is %d\n",(a+b));
  57. /* doing the math ahead of time */
  58. sum=a+b;
  59. printf("sum = %d\n",sum);
  60. /*reset sum to zero because
  61.    it is being used again*/
  62. sum=0;
  63. /* using an array because you can
  64.   and maybe you want to pratice
  65.   arrays and loops
  66.  
  67.  lets not forget arrays are zero
  68.  based */
  69.  
  70. /* with a loop */
  71. printf("ct = %d\n",ct);
  72. /* add 1 to ct because
  73.  it was pre Incremented
  74.  inside of array element
  75.  to move it up 1 */
  76. for(int i=0;i<ct+1;i++)
  77.    sum+=arrayFOReveryThing[i];
  78. printf("sum = %d\n",sum);
  79. /*using printf function,
  80.   knowing which elements
  81.   hold the values */
  82.  
  83. printf("sum = %d\n",arrayFOReveryThing[0]+
  84. arrayFOReveryThing[1]);
  85.  
  86. /* knowing where and how you
  87.    can break off a line of
  88.    code to put it on
  89.    the next line down. not
  90.    having to rely on word wrap
  91.    in your IDE and why it still
  92.    compiles is a good
  93.    thing to know as well.
  94. */
  95.  return 0;
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement