In C programming language: Write a simple C program - consecutive.c - that will
ID: 3679810 • Letter: I
Question
In C programming language:
Write a simple C program - consecutive.c - that will read from a .txt file - foo.txt - which has one integer per line (unknown number of lines, up to tens of thousands of lines). The C program will compare each integer with the integer on the next line and check to see if it is exactly one greater than it. If the next line is not eactly 1 greater, then that number will be printed to console. This will check every line of foo.txt
Example:
__________________________________________________
"foo.txt"
3
4
5
6
6
7
8
.
.
.
145
146
146
147
.
.
____________________________________ Output: 6, 146,..
Explanation / Answer
Code:
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE * fp;
char *line;
fp = fopen("test.txt", "r"); // open input file
int count=1;
size_t len = 0;
ssize_t read;
int prev; // maintain variable for previous value
while ((read = getline(&line, &len, fp)) != -1) { //read until last line encounter
if(line==" ")
break;
int val= atoi(line);
if(count==1)
{
prev =val;
count++;
continue;
}
if(prev+1 != val ) //checking condition if current value is not greator than previous value then print the previous value
printf("%d ",prev); //prit prev variable if "if" condition is satisfied
prev=val; //updating prev variable to current value
count++;
}
fclose(fp);
}
If you have any doubt then please comment below