<aside> ⚠️ One important skill of computer scientists is to understand a piece of given source codes easily. Therefore, you will find four code snippets in the C programming language. Your task is to analyze these snippets and write them into the input field without a debugger. You can assume that all provided code examples can be compiled correctly and they won’t produce a runtime error. To make the code snippets easier, we might not put it in a main function or include headers. You can assume, that the code is working.
❗Your answer will be tested automatically; make sure that you write the exact output (including whitespace), otherwise, you won't get the point.
</aside>
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr + 2;
*ptr += 10;
ptr--;
printf("%d", *ptr);
// Output: 2
void swap(int *a, int *b)
{
int tmp = *a;
*b = *a;
*a = tmp;
}
int main()
{
int x = 5, y = 10;
int *ptr1 = &x, *ptr2 = &y;
swap(ptr1, ptr2);
printf("%d %d", *ptr1, *ptr2);
return 0;
}
// Output: 5 5
int findHighestNumber(int data[], int length)
{
int highest = data[0];
for (int i = 1; i < length; ++i)
if (data[i] > highest)
highest = data[i];
return highest;
}
int main ()
{
int numbers[] = { 4, 5, 2, 10, 12, 3 };
printf ("%d", findHighestNumber(numbers, sizeof (numbers) / sizeof(int*)));
return 0;
}
// Output: 5
Find the errors of the following code snippet and fix them. The online compiler will give you already a few good hints. Do not change the ordering of the functions or delete function calls. Do not change the struct.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Person_
{
char name[50];
int age;
} Person;
void initializePerson (struct _Person_ *person, const char *name, int age)
{
person->name = name;
person->age = age;
}
void printPerson (struct Person *person)
{
printf ("Name: %s, Age: %d\\n", person->name, person->age);
}
int main ()
{
Person person;
initializePerson (person, "John", 25);
printPerson (person);
return 0;
}
The output should be exactly this: Name: John, Age: 25
In the program below, items (in this example, the items are smartphones) are saved in a singly linked list. An item is represented as a struct called Item
, which contains the following members:
char name_[30]
: the name of the itemchar brand_[30]
: the maker of the itemunsigned price_in_cents_
: the price of the item (in Euro cents instead of Euros, to prevent rounding errors)Item* next_
: a pointer to the next item in the listIn the program, the list of items must always be sorted in ascending order according to the items' price. This means that a list with items always starts with the cheapest item, and each further item fulfills the requirement that it is at least as expensive as the preceding item in the list.