In: Computer Science
Complete Question 1a-c
1a) Write a C program that displays all the command line
arguments that
appear on the command line when the program is invoked. Use
the
file name cl.c for your c program. Test your program with
cl hello goodbye
and
cl 1 2 3 4 5 6 7 8
and
cl
1b) Write a C program that reads in a string from the
keyboard.
Use scanf with the conversion code %s. Recall that the 2nd
arg in scanf should be the address of the location in
memory into which the inputted string should be stored.
Recall that the name of an array without square brackets is
the address of the first slot of the array.
1c) Write a program that reads in this file (example.txt) and
counts
and displays the number of lowercase e's in the file. Use the
fread function to read the entire file with just one call of
fread.
Use google to get info on fread.
Part a)
C code:
#include <stdio.h>
//argc stores number of command line arguments
//char** argv is an array of strings that stores arguments
//argv[0] is the name of the program itself
int main(int argc, char** argv) {
//loop through all arguments and print them to console
int i;
for(i = 0; i < argc; ++i) {
printf("%s\n", argv[i]);
}
return 0;
}
Sample IO:
Part B)
C code:
#include <stdio.h>
int main(int argc, char** argv) {
char str[100]; // declaring character array (string)
scanf("%s", str); // take input from console
printf("%s\n", str); //print string to screen (optional)
return 0;
}
Sample IO:
Part C)
C Code:
#include <stdio.h>
int main() {
FILE* infile; // file pointer for input file stream
infile = fopen("examples.txt", "r"); // open examples.txt in read mode
char buffer[1000]; // buffer will store data read from file
//using fread() to read one character at a time and maximum 500(or whatever you want)
// times from infile. fread() returns the total number of successful reads;
int charCount = fread(buffer, 1, 500, infile);
int low_e_count = 0; // variable to count lowercase 'e'
// loop through all characters and count lowercase 'e'
int i;
for(i = 0; i < charCount; ++i) {
if(buffer[i] == 'e') low_e_count++;
}
// print answer to console
printf("Number of lowercase 'e' in examples.txt = %d\n", low_e_count);
}
Sample IO:
examples.txt:
Console: