Informatics3-2024/Solutions1

A MathWikiből

Tartalomjegyzék

Solutions

Only the solutions we discussed on the practical will be here. All the other tasks are perfect to practice for the written exam.

1. Conditional print
#include<stdio.h>
 
int main(void) {
  /* declare and give values to variables x and y */
  int x; // this could be int x = 5;
  int y; // the it would be a variable definition
  x = 5;
  y = 2;
 
 
  printf("value of X: %d\n", x); // we print the values
  printf("value of Y: %d\n", y); // of the variables
 
  printf("\n"); // this is just an empty line in the output
 
  /* using conditionals make it so only true statements are printed */
  if (x > y) { // a simple condition
    printf("%d is greater than %d\n", x, y);
  } else if (x < y) { // there's no elif, we need to use else if
    printf("%d is greater than %d\n", y, x);
  } else {
    printf("%d is equal to %d\n", x, x);
  }
 
  return 0;
}

Now with using scanf:

#include<stdio.h>
 
int main(void) {
  /* declare and give values to variables x and y */
  int x; // this could be int x = 5;
  int y; // the it would be a variable definition
  x = 5;
  y = 2;
 
  printf("Provide a value for x: ");
  scanf("%d", &x);
  printf("Provide a value for y: ");
  scanf("%d", &y);
 
  printf("value of X: %d\n", x); // we print the values
  printf("value of Y: %d\n", y); // of the variables
 
  printf("\n"); // this is just an empty line in the output
 
  /* using conditionals make it so only true statements are printed */
  if (x > y) { // a simple condition
    printf("%d is greater than %d\n", x, y);
  } else if (x < y) { // there's no elif, we need to use else if
    printf("%d is greater than %d\n", y, x);
  } else {
    printf("%d is equal to %d\n", x, x);
  }
 
  return 0;
}


2. For cycle
#include<stdio.h>
 
int main(void) {
  /* variable definitions */
  int i; // no need to give any initial value to this, we'll do it in the cycle
 
  for (i = 1 ; i <= 100; i++) { // it's an equally good solution if we start
    if (i % 2 == 0) {           // from 2, and use a step size of two
      printf("%d\n", i);        // by using i += 2 instead of i++
    }
  }
  return 0;
}


3. Do / while cycle
#include<stdio.h>
 
int main(void) {
  int x;       // we'll read the input numbers into this variable
  float s = 0; // the sum will be stored here
  int n = 0;   // we'll count how many numbers we've seen here
 
  scanf("%d", &x);
  while(x != 0) {
    s += x;
    n++;
    scanf("%d", &x); // we read a new number at the end of every cycle
  }
  printf("%f\n", s / n); // %f can be used to print a float
                         // the float / int division results in a float
                         // but for example int / int would result in an int
                         // try to modify the type of s to int
  return 0;
}
Személyes eszközök