Upload files to 'Exercise 3 - Virtual Initialization (Week 4)'

This commit is contained in:
Manish 2021-04-28 08:26:48 +02:00
parent 0d4bb59657
commit cab8a393f7
5 changed files with 106 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,8 @@
42 7
93 9
11 4
-1 -1
7
8
9
-1

View File

@ -0,0 +1,96 @@
/* License: AGPLv3 or later. https://www.gnu.org/licenses/licenses.html
*
* Exercise 3 - Virtual Initialization (Week 4)
* Name: Manish
* Student Login: *****
*
* Compile as:
* $ gcc -std=c11 -Wall -o ex3 ex3.c
*
* Assumption: Where input is 0 indexed and not starting from 1
*/
#include <stdio.h>
#include <stdlib.h>
int data[100];
int forward[100];
int backward[100];
int valid_indexes = -1;
int main(void)
{
printf("Enter file name: ");
char filename[257];
// Assuming filename/file path won't be longer than 256 characters
scanf("%256s", filename);
FILE* file = fopen(filename, "r");
if (!file)
{
perror(filename);
exit(EXIT_FAILURE);
}
int what = -10;
int where = -10;
// Trailing whitespaces to consume all subsequent ' ', \t, \n, \r
/* NOTE: Not using file position checks to detect when stuck in a loop
* assuming input to be in exact format as specified
*/
while (fscanf(file, " %d ", &what) != EOF
&& fscanf(file, " %d ", &where) !=EOF)
{
if (what == -1 && where == -1)
{
break;
}
// Where/index cannot be less than 0
if (where < 0 || where >= 100)
{
fprintf(
stderr,
"Where index is %d but arrays index is only up to 99. "
"Ignoring this input.\n",
where);
continue;
}
data[where] = what;
forward[++valid_indexes] = where;
backward[where] = valid_indexes;
}
int probe;
// Trailing whitespace to consume all subsequent ' ', \t, \n, \r
while(fscanf(file, " %d ", &probe) != EOF)
{
if (probe == -1)
{
break;
}
// Probe/index cannot be less than 0
if (probe < 0 || probe >= 100)
{
printf("Position %d does not exist.\n",probe);
continue;
}
if (backward[probe] <= valid_indexes
&& forward[backward[probe]] == probe)
{
printf(
"Position %d has been initialized to value %d.\n",
probe,
data[probe]
);
}
else
{
printf("Position %d has not been initialized.\n", probe);
}
}
fclose(file);
return 0;
}

View File

@ -0,0 +1,2 @@
ex3: ex3.c
gcc -std=c11 -Wall -o ex3 ex3.c