A personal greeting
Read a first name (a single word) and print Hello, <name>!.
AnaHello, Ana!In C, input/output operations are not part of the language: there are no dedicated statements, only functions added through the standard library. This separation gives flexibility, but shifts onto the programmer the responsibility of correctly specifying the format of the data.
printf and scanfscanf functionTransfers to and from physical devices happen through logical devices called streams. There are two categories: text streams, which transfer characters organized into lines, and binary streams, which transfer bytes with no imposed structure.
| Stream | Type | Associated with | Can be redirected? |
|---|---|---|---|
stdin | text | the keyboard - standard input | yes |
stdout | text | the monitor - standard output | yes |
stderr | text | the monitor - the error output | yes |
stdprn | binary | the printer (DOS PRN device) | no |
stdaux | binary | auxiliary input/output (DOS AUX) | no |
program > result.txt)
errors still show up on the screen, instead of being hidden in the file.| Function | Role | Notes |
|---|---|---|
int getchar(void) | reads a character from stdin | waits for Enter; returns EOF at end of file |
int getch(void) | reads a character with no echo | does not wait for Enter; specific to conio.h, non-portable |
int getche(void) | reads a character with echo on screen | does not wait for Enter; non-portable |
int putchar(int c) | writes a character to stdout | returns the character written |
getchar() must be able to
signal the end of the stream through the value EOF (usually −1), which does not
fit in the unsigned char range. If the result is stored in a char,
the test c != EOF may never work.| Function | Role | Risk |
|---|---|---|
gets(s) | reads an entire line, including spaces | dangerous - does not limit the length; removed from the standard |
fgets(s, n, stdin) | reads at most n−1 characters | safe; keeps the trailing '\n' character |
puts(s) | prints a string and adds a newline | - |
scanf("%s", s) | reads a word (stops at whitespace) | cannot read sentences with spaces |
fgets instead of gets.
To remove the leftover newline character:
s[strcspn(s, "\n")] = '\0';%[flag][width][.precision][modifier]type %-8.3f │││ │ └── type: f = real ││└─┴──── precision: 3 decimals │└─────── minimum width: 8 characters └──────── flag: - = left alignment
| Specifier | Data type | Example output |
|---|---|---|
%d, %i | int | -42 |
%u | unsigned int | 4294967254 |
%f | float / double | 3.141593 |
%.2f | real with 2 decimals | 3.14 |
%e | scientific notation | 3.141593e+00 |
%c | char | A |
%s | character string | text |
%x, %X | hexadecimal | ff / FF |
%o | octal | 377 |
%p | address (pointer) | 0x7ffd3a2c |
%% | a literal percent character | % |
Choose a specifier and a value, then watch exactly what printf
prints. Try mismatched combinations - for example %c with the value 65 - to
understand why the compiler does not warn you.
scanf("%d", n); instead of scanf("%d", &n); passes the value of
the variable instead of its address. The program compiles, but crashes badly at run time.scanf("%d", &n);, the Enter key is left unread in stdin. An
immediately following scanf("%c", &c); will pick up that '\n',
not the intended character. Solution: scanf(" %c", &c); - the space in the
format skips over whitespace characters.printf("%d", 3.14); produces no compile error, but prints a meaningless value,
because it interprets the bits of a double as an int.scanf returns 0 and leaves
the text in the buffer, which can lead to an infinite loop. The value returned by scanf says how many values it actually read: 1 means success, 0 means something other than a number was in front. The safe_read.c program below prints it; how to react to it, with if and while, comes in labs 5 and 6.
#include <stdio.h>
int main(void)
{
int c1, c2, c3; // int, NOT char: getchar() can also return EOF
printf("Type three characters: ");
c1 = getchar(); // each call takes the next character from stdin
c2 = getchar();
c3 = getchar();
printf("First: '%c' has code %d\n", c1, c1);
printf("Second: '%c' has code %d\n", c2, c2);
printf("Third: '%c' has code %d\n", c3, c3);
putchar(c1); // putchar prints a single character
putchar('\n');
printf("The constant EOF is %d - it does not fit in an unsigned char,\n", EOF);
printf("which is why the result of getchar() is kept in an int.\n");
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[50];
int age = 0;
int count;
printf("Full name: ");
fgets(name, sizeof(name), stdin); // safe: limits the length
name[strcspn(name, "\n")] = '\0'; // remove the newline
printf("Age: ");
count = scanf("%d", &age); // how many values it managed to read
printf("scanf returned %d\n", count); // 1 = a number was read, 0 = not
printf("\n%-20s %3d years old\n", name, age);
return 0;
}
#include <stdio.h>
int main(void)
{
printf("%-12s %8s %10s\n", "Product", "Qty", "Price");
printf("--------------------------------\n");
printf("%-12s %8d %10.2f\n", "Resistor", 120, 0.15);
printf("%-12s %8d %10.2f\n", "Capacitor", 45, 0.80);
printf("%-12s %8d %10.2f\n", "Microcontroller", 8, 24.50);
// the same number, in different bases
int v = 255;
printf("\n%d in decimal = %o in octal = %X in hex\n", v, v, v);
// printing a literal percent sign
printf("Progress: %d%%\n", 75);
return 0;
}
Output formatting is learned by experimenting. Change the numbers inside
the specifiers (%8.3f, %-12s) and watch the columns move.
scanf, in order. In a real program, the user
would type them one at a time.This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.
Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.
Read a first name (a single word) and print Hello, <name>!.
AnaHello, Ana!Read a full name, which may contain spaces, with fgets. Print it between square brackets, followed by its number of characters (without the newline).
Ion Popescu[Ion Popescu] 11Read a positive integer n. Print it in decimal, in octal with the prefix 0 and in hexadecimal with the prefix 0x and capital letters for the digits, for example 255 0377 0xFF.
255255 0377 0xFFRead a name (one word) and a real grade. Print a table row: the name left-aligned in 10 characters, then |, then the grade right-aligned in 6 characters with two decimals. Example: Ana | 9.50.
Spacing matters here: the output is compared character by character (only trailing spaces are ignored).
Ana 9.5Ana | 9.50The first line holds an integer n and the second a character c. Print n=<n> c=<c>.
5
xn=5 c=xProblems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.
Read exactly three lines name quantity price (the name is one word, the quantity an integer, the price a real number). Print each product on one line: the name left-aligned in 12 characters, the quantity in 4, the text x , the price in 7 characters with two decimals, = and the value in 9 characters with two decimals. At the end print TOTAL left-aligned in 12 characters and the total in 26 characters, with two decimals. (No loops: they come in Lab 6.)
Spacing matters here: the output is compared character by character (only trailing spaces are ignored).
paine 2 3.5
lapte 1 7.99
mere 3 2.4paine 2 x 3.50 = 7.00
lapte 1 x 7.99 = 7.99
mere 3 x 2.40 = 7.20
TOTAL 22.19Read a date written day.month.year (for example 5.3.2026). Print it on one line in the ISO format yyyy-mm-dd and then in the US format mm/dd/yyyy, with leading zeros. Example: 2026-03-05 03/05/2026.
5.3.20262026-03-05 03/05/2026Read a first name and a last name (one word each, at least two letters long). On one line print: the last name, a comma, the initial of the first name followed by a dot, then, in parentheses, the total number of letters. Example: for Ion Popescu print Popescu, I. (10 letters).
Ion PopescuPopescu, I. (10 letters)Read a real number x. Print it on five lines: with a sign and three decimals (%+.3f), in scientific notation with three decimals, in 10 characters right-aligned with two decimals and framed by |, then the same but left-aligned, and finally the integer part padded with zeros up to 6 digits.
Spacing matters here: the output is compared character by character (only trailing spaces are ignored).
3.14159+3.142
3.142e+00
| 3.14|
|3.14 |
000003fgets and print it with puts." %c".printf.printf("%d", 3.14) prints and explain the result.stdio.h and ctype.h.