EE 30 Lecture 2: C Data Types and Operations

Course Scope and Required Reading Materials

  • Topics covered encompass fundamental C data types, arithmetic operations, variable declarations, assignment statements, mathematical library functions, interactive input methods, and formatted standard output.

  • Required textbook readings from C for Engineers and Scientists: An Introduction to Programming with ANSI C by Gary Bronson:

    • Chapter 2: Data Types and Operations

    • Section 2.1: Data Types

    • Section 2.2: Arithmetic Operations

    • Section 2.3: Variables and Declarations

    • Section 2.4: Assignment Statements

    • Chapter 3: Completing the Basics

    • Section 3.1: Mathematical Library Functions

    • Section 3.2: Interactive Input

    • Section 3.3: Formatted Output

    • Section 3.4: Symbolic Constants

Fundamental C Program Structure and Syntax

  • A computer program consists of a sequence of instructions followed sequentially by a computer. In C, these individual instructions are termed statements.

  • Rules governing C statements:

    • Every statement in C must terminate with a semicolon (;).

    • Statements include function call statements (such as printf("Hello World!");) and declaration statements (such as int int_variable;).

  • Direct comparison between compiled C execution and interpreted Python execution:

    • Interpreted languages like Python process statements dynamically via shell interfaces (e.g., executing print("Hello, EE30 !") inside a Python 3.9.133.9.13 interactive prompt).

    • C requires structured compilation where code is wrapped inside a mandatory entry function and compiled prior to execution.


    Python Interactive Execution
  • Line-by-line syntax components of a standard C program:

    • Header File Inclusion: #include <stdio.h> imports standard input/output library definitions.

    • Blank Lines: Whitespace lines are ignored by the compiler and are inserted to enhance code readability.

    • Main Function Entrance: int main() serves as the unique execution starting point.

    • Code Block Delimiters: An open brace { marks the beginning of a function body, while a closing brace } marks its conclusion.

    • Variable Declaration: int number; specifies variable storage, indented for clarity, ending in a semicolon.

    • Standard Output: printf("Hello, the World! Welcome to C programming! "); displays text on the screen.

    • Interactive Input: scanf_s("%d", &number); captures user input into memory.

    • Return Statement: return 0; signals successful program execution to the operating system; non-zero values (such as −1-1) indicate execution failure.

  • Structural demonstration in Program 2.22.2 (Pgm2-2.cpp by G. Bronson, dated 6/15/066/15/06):

    • Multi-line comment block: /* ... */ providing file details, description, programmer name, and creation date.

    • Preprocessor directive: #include <stdio.h>.

    • Main block invoking function call printf("Hello there world!"); enclosed in double quotes and ending with return 0;.


    Program 2.2 Structure

Variables, Declarations, and Constants

  • Variable Definition:

    • A named storage location in the computer's memory used to hold a data value that can change during program execution.

    • Replaces direct memory management using complex numerical addresses with human-readable identifiers to easily store, retrieve, and manipulate data.

  • Strongly-Typed System:

    • C is a strongly-typed language, requiring explicit declaration of the data type a variable will store before it is used.

  • Two-Step Variable Utilization Process:

    1. Declaration: Informs the compiler of the variable name and type, prompting memory allocation of a designated size.

    2. Initialization: Assigns an initial data value to the allocated memory location using the assignment operator =.

    • Combined Declaration and Initialization Syntax: type variableName = value;

    • Examples:

    • int myNum = 10; (allocates an integer for whole numbers)

    • float myFloatNum = 6.99; (allocates a single-precision floating-point number)

    • char myLetter = 'A'; (allocates a single character)

  • Constants in C:

    • Variables whose values must remain fixed throughout execution are defined as constants.

    • The const keyword modifies a variable declaration to make it read-only and unchangeable.

    • Syntax Comparison:

    • Standard variable declaration: float pai = 3.14156;

    • Constant declaration: const float pai = 3.14156;

  • Complete Walkthrough of Program 2.12.1 (Circumference Calculation):

    • Standard I/O inclusion: #include <stdio.h>

    • Variable declaration: float radius, circumference;

    • Value assignment: radius = 2.0;

    • Computation using literal constants: circumference = 2.0 * 3.1416 * radius;

    • Output statement: printf("The circumference of the circle is %f ", circumference);

    • Exit code: return 0;


    Program 2.1 Code Example

    Program 2.1 Constant Annotation

C Data Types and Memory Representation

  • Data types determine both the byte size allocated in memory and the mathematical operations permissible on the stored value.

  • Standard C Data Types Overview Table:


    C Data Types Summary Table
    • int: Size 22 or 44 bytes, stores whole numbers without decimals (e.g., 1).

    • float: Size 44 bytes, stores fractional numbers with 11 or more decimals, supporting 6–76\text{--}7 decimal digits of precision (e.g., 1.99).

    • double: Size 88 bytes, stores fractional numbers with 11 or more decimals, supporting 1515 decimal digits of precision (e.g., 1.99).

    • char: Size 11 byte, stores a single character/letter/number or ASCII value (e.g., 'A').

  • Detailed Specifications for Integer and Character Data Types:

    • Integer (int):

    • Represents signed whole numbers (e.g., 00, −10-10, 253253, −26351-26351).

    • Memory allocation: Typically 44 bytes (3232 bits).

    • Integer variants: short, long, unsigned short, unsigned int, unsigned long, long long.

    • Character (char):

    • Stores single ASCII-encoded characters enclosed in single quotes (e.g., 'A', '$', 'b', '!').

    • Memory allocation: 11 byte (88 bits).

    • Signedness: Can be explicitly declared as signed char or unsigned char to hold small numeric values.

    • Example signed character usages: signed char my_number1 = -18; or char my_number2 = 20;.

  • Detailed Specifications for Floating-Point Data Types:

    • Represents real numbers (zero, positive, or negative) containing an explicit decimal point (e.g., +10.625+10.625, 5.5., −6.2-6.2, 3251.923251.92, +2.0+2.0).

    • Data Type Precisions:

    • float: Single-precision real number allocated 44 bytes (3232 bits).

    • double: Double-precision real number allocated 88 bytes (6464 bits).

    • long double: Extended double-precision real number allocated 12–1612\text{--}16 bytes.

    • IEEE 754754 32-Bit Floating-Point Representation Mechanics:

    • Normal binary format: +1.xxxxxxxxtwo×2yyyytwo+1.xxxxxxxx_{two} \times 2^{yyyy_{two}}

    • Bit allocation across 3232 bits (11 word):

      • Bit 3131 (11 bit): Sign Bit SS (00 for positive, 11 for negative).

      • Bits 30–2330\text{--}23 (88 bits): Exponent field representing exponent value y$.\n * Bits 22 ext{--}0((23bits):Significand(mantissa)fieldrepresentingfractionvaluesbits): Significand (mantissa) field representing fraction valuesx$.

    • Magnitude Range: Capable of representing floating-point values as small as 2.0×10−382.0 \times 10^{-38} up to as large as 2.0×10382.0 \times 10^{38}.


    Floating Point Binary Representation
    • Floating-Point Literal Suffixes:

    • Default unadorned decimal literal (e.g., 9.234) is interpreted as double.

    • Appending f or F (e.g., 9.234f) explicitly designates a float literal.

    • Appending l or L (e.g., 9.234L) explicitly designates a long double literal.

Program Interaction Categories and Standard Output with printf()

  • Standard Categories of Program Communication/Interaction:

    • User Interaction: Exchanging inputs and outputs with human operators via standard routines like printf() and scanf_s().

    • System Interaction: Executing code sequentially via line-by-line interpreters or translating entire source blocks into machine binaries via compilers.

    • Memory Interaction: Automatically allocating, reading, and freeing variable memory without manual hardware tracking.

    • Cross-Language Interaction: Linking heterogeneous software components using unified language bindings or shared interfaces.

  • Mechanics of Standard Output using printf():

    • Standard Destination: Formats data streams and dispatches them to the standard output device (stdout), typically the monitor console.

    • Execution Requirements:

    1. Must include the standard header file <stdio.h>.

    2. Must utilize appropriate format specifiers matching target variable data types (e.g., printf("%d ", myIntNum);).

    3. String parameters must be wrapped in double quotes "" (e.g., printf("Hello there world!");).

    4. Escape sequence inserts a newline character.

    • Formal Parameter Terminology: Supplying arguments into printf() is formally termed passing data to the function.

  • Syntax and Format Specifier Declarations:

    • Standard Call Syntax: printf("%specifier", variable);

    • Multi-Variable Output Demonstration:

    • printf("%d ", myNum); (for int myNum = 10;)

    • printf("%f ", myFloatNum); (for float myFloatNum = 6.99;)

    • printf("%c ", myLetter); (for char myLetter = 'A';)

    • Combined call syntax: printf("%d %f %c ", myNum, myFloatNum, myLetter);

    • Format Specifiers Reference Table:


    Format Specifiers Table
    • %d or %i: Assigned to int (signed integers).

    • %f or %F: Assigned to float (floating-point decimals).

    • %lf: Assigned to double (double-precision floating-point).

    • %c: Assigned to char (single characters).

    • %s: Assigned to text strings (character arrays).

Standard Input Functions in C

  • Overview of Standard Input (stdin):

    • Primary mechanism receiving user-entered data streams from hardware input devices (keyboard).

    • Three core standard library functions handle keyboard stream processing: scanf() / scanf_s(), gets_s(), and getchar().

  • Formatted Input via scanf() and scanf_s():

    • Reads formatted inputs from stdin, parsing diverse primitive data types based on specified format flags (%d, %f, %s).

    • Delimiter Behavior: Automatically terminates string extraction upon encountering the first whitespace character (space, tab, or newline).

    • Syntax for Scalar Variables: Requires the address-of operator & prefixed to target scalar variables.

    • Example: scanf_s("%d", &age);

    • Syntax for String/Array Variables: Omits the address-of operator & because array names inherently evaluate to memory addresses.

    • Example: scanf_s("%s", name);

  • Safe Line-Oriented Input via gets_s():

    • Introduced as a bounds-checked, secure substitute for the legacy unsafe gets() function.

    • Header requirement: <stdio.h>.

    • Format Specifiers: Does not use format specifiers like %s.

    • Delimiter Behavior: Reads an entire sequence of text characters including spaces until encountering a newline character () or End-Of-File (EOF).

    • Newline Handling: Extracts and safely discards the trailing rather than storing it inside the target array.

    • Array Bounds Protection: Demands an explicit buffer length parameter sizeof() to prevent buffer overflow vulnerabilities.

    • Syntax: gets_s(char_variable, sizeof(char_variable));

    • Example: gets_s(fullName, sizeof(fullName)); where fullName is declared as char fullName[50].

  • Single-Character Input via getchar():

    • Reads a single character (returned as char or int) from stdin per call.

    • Requirements: Includes <stdio.h>, requires no format specifiers, and requires no buffer size parameter.

    • Syntax: variable = getchar();

    • Example: choice = getchar(); (storing character input like 'Y' or 'N').

    • Stream Flushing Loop: Frequently employed to discard leftover characters or clear trailing newline characters from input buffers:

    • Idiomatic syntax: while ((c = getchar()) != ' ' && c != EOF) { } where EOF represents End-Of-File (defined as −1-1).

  • Feature Comparison: gets_s() vs. scanf_s():


    gets_s vs scanf_s Comparison Table
    • Purpose:

    • gets_s(): Reads a full line of text (string).

    • scanf_s(): Reads formatted input (single values or strings).

    • Termination Trigger (Stops At):

    • gets_s(): Stops strictly at a Newline ().

    • scanf_s(): Stops at any Whitespace (space, tab, newline, etc.).

    • Security Requirement:

    • gets_s(): Requires buffer size parameter to prevent overflow.

    • scanf_s(): Requires buffer size parameter specifically when reading strings.

    • Null-Termination Behavior:

    • gets_s(): Automatically appends \0 at string end.

    • scanf_s(): Automatically null-terminates extracted strings.

    • Whitespace/Space Handling:

    • gets_s(): Fully handles spaces (reads entire line including spaces).

    • scanf_s(): Cannot handle spaces within strings (stops at first space).

    • Format Specifier Requirement:

    • gets_s(): No format specifiers required (designed exclusively for strings).

    • scanf_s(): Requires format specifiers (e.g., %s, %c, %d).