Systems Programming - C Language Formatted Input/Output
Learning Outcomes
Write computer programs in C language to:
Print statements for requesting user input, ensuring clear communication with users by providing prompts indicating the type of data expected.
Scan data from the user through formatted input and store in variables efficiently, allowing for varied data types.
Perform calculations with arithmetic operators (such as addition, subtraction, multiplication, and division) and comparisons using relational operators (like
>,<,==) and logical operators (like&&,||,!) for making logical decisions.Print output in a specific format using
printf, including formatted numerical output and string data.Utilize selection structures (
if,if...else, andswitch) for decision-making to execute different blocks of code based on specific conditions, improving program interactivity.Implement repetition structures such as (
for,while,do...while, and sentinel-controlled repetition), necessary for iterating over data or repeatedly performing operations until a condition is met.Create and call user-defined functions for modular programming, facilitating code reuse and improving readability by organizing code into logical blocks.
Formatted Input/Output
Input/output operations in C are managed by functions in the C standard library, which is included using
#include <stdio.h>, enabling the program to execute basic input and output operations.Key formatted input/output functions include:
scanf: designed to read input data from the standard input stream according to specified format.
printf: designed to send formatted output to the standard output stream, allowing developers to display information on screen.
gets, puts, getchar, putchar: these functions are used for input and output operations with strings and individual characters, useful for handling simple text input/output tasks.
Formatting Output with printf
printfFunction: This essential function allows for precise output formatting with various options, accommodating a wide range of data presentation needs.Conversion Specifications: Set field widths for aligning output, precision for displaying decimal places, rounding of numbers, and alignment (left/right).
Format Control String: A string that outlines the desired output format; each specification commences with
%, followed by a character that indicates the type of data.
Example usage:
printf(format-control-string, other-arguments);Common conversion specifiers for integers include:
dori: for printing signed decimal integers, which can be positive, negative, or zero.o: for printing unsigned octal integers.u: for unsigned decimal integers.xorX: for printing unsigned hexadecimal integers with either lowercase or uppercase letters, respectively.horl: used to specify short or long integers in the print output.
Printing Integers
Integers: Whole numbers without any fractional component, which can be positive, negative, or zero (for example,
25,0,-9). Integers are essential for counting and indexing operations in programming.Example of Usage:
printf( "%d\n", 455 );
printf( "%i\n", 455 );
printf( "%hd\n", 32000 );
Printing Floating-Point Numbers
Floating-Point Numbers: These numbers include decimal points or can be denoted in exponential notation, allowing for a wider range of values, essential in scientific calculations.
Common format specifiers include:
eorE: for displaying numbers in exponential notation, which is critical for representing very large or small values.f: for fixed-point notation, displaying the value to a specified number of decimal places.gorG: provides a general format, utilizing eitherforebased on the magnitude of the number, enhancing flexibility in data representation.
Example:
printf( "%f\n", 1234567.89 );
printf( "%e\n", 1234567.89 );
Printing Strings and Characters
Format Specifiers:
%c: utilized to print a single character, enabling precise character output in user interfaces.%s: utilized to print a string, extracting characters until a NULL character is encountered, essential for handling user input and displaying text.
String Initialization:
char string[] = "This is a string";
const char *stringPtr = "This is also a string";
Field Width and Precision in Printing
Field Width: Denotes the total space allocated for output; by default, it is right-justified unless specified otherwise. It ensures alignment in tabular data outputs.
Precision: Dictates the minimum number of digits displayed for integers and the number of digits after the decimal point for floating-point numbers, critical for financial and scientific applications.
Use dot notation to define precision (e.g.,
%.3f).Example of Precision Usage:
printf( "%.4d\n", 873 );
printf( "%.3f\n", 123.94536 );
Escape Sequences
These are special character representations used in strings, allowing the insertion of formatting characters.
\n: signifies a new line, allowing for line breaks in output.\t: signifies horizontal tabulation, assisting in formatting tabular data.\": allows the inclusion of double quotes within strings, essential for displaying quotes in text messages.
Formatting Input with scanf
scanfFunction: This function is crucial for reading formatted input data from the user, allowing programs to accept dynamic input and interact with users.Conversion Specifiers, similar to
printf, include:d,i,o,x: used for integers, enabling varied input formats.f,g: utilized for floating-point numbers, accommodating input precision needs.
Example:
scanf( "%d %i %o %x", &a, &b, &c, &d );
Control Structures in C
Sequence Structures: This represents the default execution flow in C, establishing a straightforward path for code execution.
Selection Structures: These structures allow the program to choose different execution paths based on conditions:
if,if...else, andswitchenable branching based on variable states or conditions, enhancing program responsiveness.
Repetition Structures: These structures include
while,do...while, andfor, allowing the program to execute instructions repeatedly, which is crucial for tasks like iterating over arrays.
The if Selection Statement
This statement permits the execution of a block of code based on a condition being true.
Syntax:
if (condition) { // Action }
Example:
if (grade >= 60) printf("Passed\n");
The if...else Selection Statement
This extends the
ifstatement to define an alternate path for when the initial condition is false, enhancing decision-making capabilities in code.Syntax:
if (condition) { // If true } else { // If false }
Example:
if (grade >= 60) printf("Passed\n"); else printf("Failed\n");
Nested if...else Statements
These are beneficial for making multi-way decisions by nesting
if...elsestatements within each other to handle complex conditions.Syntax:
if (condition1) {
// action1
} else if (condition2) {
// action2
}
Example: To determine letter grades based on numeric grades, enhancing the program's functionality.
The switch Statement
A selection structure that simplifies multi-way branching based on a single variable's value.
Syntax:
switch (expression) {
case value1: /* Actions */ break;
case value2: /* Actions */ break;
default: /* Actions */ break;
}
Utilizing flowchart representations can aid in visualizing decision-making processes effectively.
Discussion: Integer vs Float
It is essential to use the appropriate format specifiers to prevent type mismatch errors when printing, ensuring accurate representation of data types.
Example:
printf("%f\n", 10000.0);
versus using integers.
Discussion: Typecasting
Typecasting is crucial in C programming, as it facilitates explicit conversions between data types in calculations (e.g., float to int or vice versa).
Example of explicit typecasting:
float avg = (float) total / count;
These notes summarize key aspects of formatted input/output, control structures, and data types in C. Mastery of these concepts is essential for practical programming tasks throughout this course, equipping learners with the necessary skills to develop robust applications effectively.
Learning Outcomes
Write computer programs in C language to:
Print statements for requesting user input, ensuring clear communication with users by providing prompts indicating the type of data expected.
Scan data from the user through formatted input and store in variables efficiently, allowing for varied data types.
Perform calculations with arithmetic operators (such as addition, subtraction, multiplication, and division) and comparisons using relational operators (like
>,<,==) and logical operators (like&&,||,!) for making logical decisions.Print output in a specific format using
printf, including formatted numerical output and string data.Utilize selection structures (
if,if...else, andswitch) for decision-making to execute different blocks of code based on specific conditions, improving program interactivity.Implement repetition structures such as (
for,while,do...while, and sentinel-controlled repetition), necessary for iterating over data or repeatedly performing operations until a condition is met.Create and call user-defined functions for modular programming, facilitating code reuse and improving readability by organizing code into logical blocks.
Formatted Input/Output
Input/output operations in C are managed by functions in the C standard library, which is included using
#include <stdio.h>, enabling the program to execute basic input and output operations.Key formatted input/output functions include:
scanf: designed to read input data from the standard input stream according to specified format.
printf: designed to send formatted output to the standard output stream, allowing developers to display information on screen.
gets, puts, getchar, putchar: these functions are used for input and output operations with strings and individual characters, useful for handling simple text input/output tasks.
Formatting Output with printf
printfFunction: This essential function allows for precise output formatting with various options, accommodating a wide range of data presentation needs.Conversion Specifications: Set field widths for aligning output, precision for displaying decimal places, rounding of numbers, and alignment (left/right).
Format Control String: A string that outlines the desired output format; each specification commences with
%, followed by a character that indicates the type of data.
Example usage:
printf(format-control-string, other-arguments);Common conversion specifiers for integers include:
dori: for printing signed decimal integers, which can be positive, negative, or zero.o: for printing unsigned octal integers.u: for unsigned decimal integers.xorX: for printing unsigned hexadecimal integers with either lowercase or uppercase letters, respectively.horl: used to specify short or long integers in the print output.
Printing Integers
Integers: Whole numbers without any fractional component, which can be positive, negative, or zero (for example,
25,0,-9). Integers are essential for counting and indexing operations in programming.Example of Usage:
printf( "%d\n", 455 );
printf( "%i\n", 455 );
printf( "%hd\n", 32000 );
Printing Floating-Point Numbers
Floating-Point Numbers: These numbers include decimal points or can be denoted in exponential notation, allowing for a wider range of values, essential in scientific calculations.
Common format specifiers include:
eorE: for displaying numbers in exponential notation, which is critical for representing very large or small values.f: for fixed-point notation, displaying the value to a specified number of decimal places.gorG: provides a general format, utilizing eitherforebased on the magnitude of the number, enhancing flexibility in data representation.
Example:
printf( "%f\n", 1234567.89 );
printf( "%e\n", 1234567.89 );
Printing Strings and Characters
Format Specifiers:
%c: utilized to print a single character, enabling precise character output in user interfaces.%s: utilized to print a string, extracting characters until a NULL character is encountered, essential for handling user input and displaying text.
String Initialization:
char string[] = "This is a string";
const char *stringPtr = "This is also a string";
Field Width and Precision in Printing
Field Width: Denotes the total space allocated for output; by default, it is right-justified unless specified otherwise. It ensures alignment in tabular data outputs.
Precision: Dictates the minimum number of digits displayed for integers and the number of digits after the decimal point for floating-point numbers, critical for financial and scientific applications.
Use dot notation to define precision (e.g.,
%.3f).Example of Precision Usage:
printf( "%.4d\n", 873 );
printf( "%.3f\n", 123.94536 );
Escape Sequences
These are special character representations used in strings, allowing the insertion of formatting characters.
\n: signifies a new line, allowing for line breaks in output.\t: signifies horizontal tabulation, assisting in formatting tabular data.\": allows the inclusion of double quotes within strings, essential for displaying quotes in text messages.
Formatting Input with scanf
scanfFunction: This function is crucial for reading formatted input data from the user, allowing programs to accept dynamic input and interact with users.Conversion Specifiers, similar to
printf, include:d,i,o,x: used for integers, enabling varied input formats.f,g: utilized for floating-point numbers, accommodating input precision needs.
Example:
scanf( "%d %i %o %x", &a, &b, &c, &d );
Control Structures in C
Sequence Structures: This represents the default execution flow in C, establishing a straightforward path for code execution.
Selection Structures: These structures allow the program to choose different execution paths based on conditions:
if,if...else, andswitchenable branching based on variable states or conditions, enhancing program responsiveness.
Repetition Structures: These structures include
while,do...while, andfor, allowing the program to execute instructions repeatedly, which is crucial for tasks like iterating over arrays.
The if Selection Statement
This statement permits the execution of a block of code based on a condition being true.
Syntax:
if (condition) { // Action }
Example:
if (grade >= 60) printf("Passed\n");
The if...else Selection Statement
This extends the
ifstatement to define an alternate path for when the initial condition is false, enhancing decision-making capabilities in code.Syntax:
if (condition) { // If true } else { // If false }
Example:
if (grade >= 60) printf("Passed\n"); else printf("Failed\n");
Nested if...else Statements
These are beneficial for making multi-way decisions by nesting
if...elsestatements within each other to handle complex conditions.Syntax:
if (condition1) {
// action1
} else if (condition2) {
// action2
}
Example: To determine letter grades based on numeric grades, enhancing the program's functionality.
The switch Statement
A selection structure that simplifies multi-way branching based on a single variable's value.
Syntax:
switch (expression) {
case value1: /* Actions */ break;
case value2: /* Actions */ break;
default: /* Actions */ break;
}
Utilizing flowchart representations can aid in visualizing decision-making processes effectively.
Discussion: Integer vs Float
It is essential to use the appropriate format specifiers to prevent type mismatch errors when printing, ensuring accurate representation of data types.
Example:
printf("%f\n", 10000.0);
versus using integers.
Discussion: Typecasting
Typecasting is crucial in C programming, as it facilitates explicit conversions between data types in calculations (e.g., float to int or vice versa).
Example of explicit typecasting:
float avg = (float) total / count;
These notes summarize key aspects of formatted input/output, control structures, and data types in C. Mastery of these concepts is essential for practical programming tasks throughout this course, equipping learners with the necessary skills to develop robust applications effectively.