Week 06 Tutorial Questions
Part 1: Tutorial Performance Hurdle,
So far in this course we have only used scanf and printf to scan input and print output in our programs.
-
How do we use
getcharandputchar? How doesgetcharsignal to us that it has reached the end of the input? -
Why does
getcharreturn anintinstead of achar? -
How do we use
fgets? How doesfgetssignal to us that it has reached the end of the input? -
When
fgetsscans in a line of text, will it include a'\n'at the end of the line? Is this always the case?
-
What does the following function do?
int secret_function(char *word) { int i = 0; int result = 0; while (word[i] != '\0') { if (word[i] >= 'a' && word[i] <= 'z') { result++; } i++; } return result; }
- Can you explain the stopping case in the while loop? Why does it work and what is the significance of the
'\0'?
#include <stdio.h>
int main(void) {
char str[10];
str[0] = 'H';
str[1] = 'i';
printf("%s", str);
return 0;
}
What will happen when the above program is compiled and executed?
- How do you correct the program?
-
Write a program
sum_digits.cwhich reads characters from its input and counts digits.When the end of input is reached it should print a count of how many digits occurred in its input and their sum.
The only functions you can use are
getchar,printfand a very useful function calledisdigit()from thectype.hlibrary which you should#include.
strlenis a function that returns the length of a string. Write your own C functionmyStrlento do the same.
int myStrlen(char string[]);
Part 2: Command line arguments
Tutor demo!
In this section we'll have a look at command line arguments and how they can be used to pass input to a C program when it is executed.
We'll be using this starter code:
#include <stdio.h>
int main(int argc, char *argv[]) {
return 0;
}
The following diagram may be useful as a guide for explaining how command line arguments work:
Your turn!
In groups we will write pseudocode or a flowchart for one of the following programs:
Sum of Command Line Arguments: Write a C program that takes multiple integers as command-line arguments and prints their sum.
Count Characters in Command Line Arguments: Write a C program that counts the total number of characters in all the command-line arguments passed to it.
Reverse Command Line Arguments: Write a C program that prints all the command-line arguments passed to it in reverse order.
Check for Command Line Arguments: Write a C program that checks if any command-line arguments were provided except for the program name. If none were provided, print a message indicating so; otherwise, print the number of arguments.