Course Code: BBC103
Course: AKTU BCA 1st Year, Semester I
Unit: Programming Foundations and Basics of C
Unit I Overview
Develop a clear solution before writing code. Learn algorithms, flowcharts and structured programming, then study C source structure, build stages, lexical elements, types, standard I/O, operators and expressions.
Topics Covered
| Syllabus area | Pages |
|---|---|
| Problem solving and program development | 2-4 |
| Algorithms, flowcharts and structure | 4-6 |
| C history, features and program structure | 6-8 |
| Build process, character set and tokens | 8-10 |
| Keywords, constants, variables and types | 10-14 |
| Standard I/O and arithmetic | 14-16 |
| Logical, assignment and bitwise operators | 16-18 |
| Expression grouping and conversion | 18-19 |
| Worked examples and C programs | 19-22 |
| Exam questions with answers | 23-25 |
| Quick revision and glossary | 26-27 |
Learning Outcomes
-
1. Develop algorithms and labelled flowcharts.
-
2. Explain C structure and the build process.
-
3. Classify tokens and choose suitable data types.
-
4. Use matching input/output formats.
-
5. Evaluate expressions with correct C rules.
Included in These Notes
32 explained sections; 26 labelled diagrams and charts; 10 colourful context images; 16 worked cases; 16 complete C programs; 24 short answers; 6 structured long answers; comparison tables and quick revision.
Study Approach
Understand. Define input, processing, output and valid assumptions.
Compare. Connect algorithm steps to C syntax and types.
Apply. Trace values, build with diagnostics and test results.
Core idea: correct C begins with a clear algorithm. Types, conversions, matching I/O formats and expression sequencing determine what the program actually does.
1. Define the problem before writing a program
A program expresses instructions that a computing system can execute. Problem solving begins with a precise requirement, not with typing statements. Identify what is known, what must be calculated and what result should be produced.
Input-process-output (IPO). To find the area of a rectangle, inputs are length and breadth, processing is multiplication and output is area. Specify units and a valid input domain. A program that multiplies two numbers can still be wrong if the requested quantity or units were misunderstood.

Constraints and assumptions. Decide whether values may be negative, fractional, missing or too large. State rounding requirements and the expected output form. Examples clarify a requirement, but one example is not a complete specification.
Plan first. Write a small test case by hand, outline a method and only then translate it into C. This separates mathematical reasoning from syntax errors and makes the final answer easier to explain in an examination.

2. Approaches to problem solving and decomposition
Understand and analyse. Restate the task, list inputs/outputs and identify constraints. Look for a direct formula, a repeated action or a decision. Avoid selecting an approach merely because a familiar code fragment exists.
Top-down decomposition breaks a large task into smaller responsibilities. A marks-processing task can be divided into reading valid marks, calculating totals/averages and displaying results. Each part should have a clear purpose and interface.

Bottom-up development builds a solution by combining useful, tested components. Top-down planning and bottom-up construction can work together. Trial and improvement is useful when guided by tests; random changes without understanding are not a dependable method.
Choose and compare. Consider correctness, clarity, effort and resource use. A simple direct formula may be better than unnecessary iteration. Detailed searching/sorting and function design appear in later units; Unit I establishes the reasoning that supports them.

3. High-level languages and systematic development
A high-level programming language expresses operations using abstractions such as variables, expressions and control structures. Its source program is translated for execution by a suitable implementation. C reduces the need to write every operation directly in machine instructions.
Development stages. Requirement analysis -> design -> coding -> translation/build -> testing -> documentation and maintenance. A failed test can send the programmer back to design or requirements; the process is iterative rather than a one-way checklist.

Algorithm and implementation. The algorithm states the method; C supplies concrete syntax, types and library facilities. The same broad algorithm can be implemented in different languages, but language rules and machine limits affect the actual program.
Good habits. Use meaningful names, consistent indentation, small logical steps, compiler diagnostics and representative tests. Portability requires respecting the language rules and implementation limits, not simply copying source code to another machine.
4. Testing, dry runs and classes of error
A dry run follows the proposed instructions by hand while recording values. A test executes the program with chosen input and compares actual output with an independently determined expected result. Both help expose incorrect assumptions.
Error categories. A syntax/constraint violation can require a compiler diagnostic; a missing external definition can cause a link failure; validly translated logic can produce an incorrect answer. Not every problem is detected during compilation.
Test design. Include ordinary, boundary and invalid cases where the requirement defines a response. For averaging values, fractional results can reveal accidental integer division. Comparing two values should include equal values, not only one larger than the other.
Undefined behaviour. Some invalid operations, such as signed integer overflow or integer division by zero, have no required result in the language model. Do not teach an observed crash or wraparound as a universal answer. Warnings are useful evidence, not proof that a program is correct.
| Check | Purpose | Example |
|---|---|---|
| Dry run | Trace planned values | Follow total and average |
| Compile | Check translation diagnostics | Missing declaration |
| Link | Resolve external definitions | Missing function definition |
| Test | Compare behaviour with requirements | Fractional average case |
5. Algorithms: meaning and essential properties
An algorithm is a finite, unambiguous sequence of effective steps for solving a defined class of problems. Its description states any required inputs and the intended outputs. It is a method rather than a particular source-code listing.
Core properties. Steps must be definite, feasible and organised toward a result. The algorithm must terminate for inputs in its stated domain. Correctness means that it produces the required result under its assumptions; finiteness alone does not establish correctness.

Example: sum of two values. Start; obtain a and b; compute sum = a + b; display sum; stop. A computer implementation must additionally choose representations and handle relevant limits or invalid input.
Quality. Clarity, correctness, generality and suitable efficiency help make a method useful. Distinguish the number of conceptual steps from the duration of one machine instruction. Complexity analysis is developed further in later study.
6. Pseudocode and trace tables
Pseudocode describes an algorithm in readable language with consistent logical structure. There is no single universal pseudocode grammar. It should show calculations and decisions clearly without pretending to be compilable C.
Average example. READ a, b, c; total <- a + b + c; average <- total / 3; DISPLAY average. In this mathematical description, division is chosen for the intended real-valued average. Translating all three inputs and the divisor into C integers can change the result.

Trace. For 4, 5 and 7, total becomes 16 and the mathematical average is 16/3. Recording the type and value at each step helps identify a mismatch between mathematical intention and C evaluation.
Assignment notation. A left arrow in pseudocode means store a computed value. In C, = is the assignment operator and == is equality comparison. The notation is different, so explain the meaning rather than mechanically copying symbols.
| Step | State for inputs 4, 5, 7 |
|---|---|
| Read | a = 4, b = 5, c = 7 |
| Total | total = 16 |
| Mathematical average | 16/3 = 5.333… |
| C with integer division | 16/3 = 5 before later conversion |
7. Flowcharts: symbols and construction rules
A flowchart displays an algorithm using symbols connected by directed flow lines. An oval/rounded terminal marks Start or Stop, a rectangle represents processing, a parallelogram input/output and a diamond a decision.
Connections. Arrows show the next step. Label decision exits with conditions such as Yes/No. A connector can continue flow where necessary, but it should not conceal missing logic. Crossing lines and unlabelled exits make a chart difficult to interpret.

Construction. Begin with a clear task, choose the required symbols and draw the logical path. A decision has alternative outcomes; a loop has a condition and a route that eventually makes progress toward termination under the stated assumptions.
Value and limitation. Flowcharts support communication and dry runs, especially for small algorithms. Very large charts become awkward to maintain. They complement written reasoning and code; they do not replace a precise requirement or testing.

8. Sequence, selection and iteration in algorithms
Sequence executes steps in a defined order. Reading dimensions, multiplying them and displaying area is a sequence. Selection chooses a path according to a condition, such as whether a number is even.
Iteration repeats a group of steps while or until a condition applies. A count-controlled example increases a counter toward a limit. An incorrect condition or missing update can create an unintended non-terminating loop.

Examples. The sum flowchart has one straight path. The even/odd flowchart tests remainder after division by 2. A sum-from-1-to-n method repeatedly adds the next counter value under a non-negative-integer input assumption.
Scope. These are control-structure concepts required for Unit I algorithms. Detailed C if/switch and loop syntax belongs to Unit II. A flowchart can explain the logic before those statements are studied.
9. Structured programming: concept and role
Structured programming organises a solution through clear sequence, selection and iteration, with manageable blocks and well-defined responsibilities. It promotes understandable flow instead of uncontrolled jumps between unrelated locations.
Benefits. Logical organisation supports reading, testing, debugging, maintenance and teamwork. Top-down refinement helps connect a large requirement to smaller steps. Consistent indentation displays structure, although whitespace alone does not make bad logic correct.

Modularity. Related operations can be collected into functions with defined inputs/results. Unit II develops function syntax and calls. Modular design and structured control flow are related ideas, but they are not identical terms.
Qualification. C supports structured programming; it also provides features such as goto and low-level access. A language supporting structure does not guarantee that every program written in it is structured, correct or safe.
10. History of C and language standards
Dennis Ritchie developed C at Bell Laboratories in the early 1970s alongside Unix. The broad lineage is BCPL -> B -> C. The especially productive development period is commonly associated with 1972, rather than treating a language as one instant invention.
Context. C added a richer type system while retaining useful implementation-level operations. Its role in Unix helped demonstrate that substantial system software could be written in a language more portable than machine-specific assembly.

Standards. ANSI C was standardised in 1989 and an ISO edition followed in 1990. Later revisions added facilities and changed some details. A keyword count or supported feature must be tied to a language version.
Convention in these notes. Runnable examples use an ordinary hosted C17 compilation mode and a portable beginner subset. C11 draft wording is useful for the shared fundamentals. The examples do not rely on an old Turbo C environment, non-standard conio.h or void main.

11. Salient features, applications and limitations of C
C is a general-purpose, procedural language with typed objects, expressions, functions and structured control facilities. It is commonly implemented using compilation and linking. C source is case-sensitive: total and Total are different identifiers.
Useful features. A compact core, standard library, arithmetic/bitwise operations and access to memory through later-studied pointer facilities suit systems and application work. Calling C a middle-level language is an informal teaching description, not a formal language-standard category.
Applications. System software, embedded firmware, libraries, utilities and performance-sensitive components are common areas. Portability is supported by standardised semantics, but representations, implementation-defined choices and external interfaces can still vary.
Limits. C does not automatically check every operation for range or memory validity. Programmer discipline is important. Efficiency depends on the algorithm and implementation; the language name does not guarantee that every C program is fast.
| Feature | Meaning | Qualification |
|---|---|---|
| Procedural | Organises work using procedures /functions | Design quality still matters |
| Portable source | Standards support movement between implementations | Machine assumptions can reduce portability |
| Low-level facilities | Useful bit/memory operations | Invalid use can have undefined behaviour |
| Standard library | Common I/O and utility interfaces | Headers and correct types are required |
12. Structure of a C program
A small hosted C program usually contains relevant preprocessing directives, declarations and a definition of main. Functions contain declarations and statements inside braces. A larger source file can contain additional function definitions and other declarations.
Header inclusion. #include <stdio.h> makes the standard I/O declarations available through the header mechanism. It is not a function call and is not normally followed by a semicolon. Including a declaration is not the same as providing every library function implementation.

Entry point. int main(void) defines main with an int return type and no parameters in the chosen hosted form. return 0; reports successful termination to the host environment. main is an identifier with a special hosted role, not a keyword.
Layout. Semicolons terminate many declarations and expression statements, while braces group a function body or block. Not every line ends with a semicolon. The later function-call syntax and the statement grammar determine what is required.
Instructions and statements. Introductory books often group declarations, arithmetic updates and control actions as instructions. In formal C grammar a declaration and a statement are distinct. Expression statements, compound blocks, selection, iteration and jump statements have different roles; return is a jump statement.
13. First complete program and its execution
The example below displays one line and exits successfully. printf is declared by stdio.h; it is a standard-library function name, not a built-in keyword. The string literal is enclosed in double quotes.
Newline. The escape sequence \n represents a newline character in the string. Writing the two source characters backslash and n tells the translator which escape is intended; it does not print those two characters literally in this example.
Read the layers. Source text describes the program, the build tools prepare an executable, and the host starts its execution. A source file displayed in an editor is not itself proof that translation succeeded.
Expected output. Hello, C! followed by a newline. A return status of 0 is normally not printed as a separate result by the program; it is delivered to the host environment.
Complete C example
#include <stdio.h>
int main(void)
{
printf(“Hello, C!\n”);
return 0;
}
Output for the stated example: Hello, C!
14. Compiling: source, preprocessing and object code
Build stages. In a common GCC toolchain, preprocessing handles directives/macros, compilation proper translates to assembly, assembly produces object code and linking creates a suitable executable from required objects/libraries. The user-facing compile command can drive several stages.
Example commands. gcc -std=c17 -Wall -Wextra -Wpedantic hello.c -o hello builds the example in a specified mode with useful diagnostics. gcc -c hello.c -o hello.o stops before linking. File naming conventions and shell commands can differ across environments.

Preprocessing versus execution. A directive such as #include affects translation, not a repeated runtime operation. The compiler checks many language constraints and may optimise the resulting implementation while preserving required observable behaviour for valid programs.
Meaning of object code. An object file can contain machine instructions and unresolved external references; it is not automatically a complete runnable program. An IDE commonly invokes a toolchain behind its build button.

15. Linking, running and diagnosing a failed build
The linker combines object files and resolves required external definitions according to the toolchain. A function declaration can allow a call to compile while its missing definition later prevents a successful link.
Run. On a typical Unix-like shell, ./hello starts an executable named hello in the current directory. Windows and other environments use their own conventions. An IDE Run action may build first, but an editor alone is not a compiler.

Diagnose in order. Fix the first meaningful diagnostic, rebuild and then inspect any remaining issue. A missing brace can trigger several later messages. A successfully built executable can still fail a requirement test.
Error examples. A missing semicolon may produce a compilation diagnostic; an undefined called function can cause link failure; calculating an integer average when a real average is required can be a logic error. Runtime behaviour is not always a crash when an operation is invalid.
16. Character set, whitespace, comments and escapes
C source uses letters, digits, punctuation and whitespace to form language elements. Common identifiers in this unit use basic Latin letters, digits and underscore. The execution character encoding is implementation-dependent; ASCII is common but not a universal language guarantee.
Whitespace and case. Space, tab and newline help separate tokens and format source. int count is not the same token sequence as intcount. Whitespace inside a string literal belongs to its content. Case sensitivity applies to identifiers and keywords.

Comments. /* … */ is a block comment and // introduces a line comment in C99 and later. Comments should explain intent, assumptions or a non-obvious step. Block comments do not nest in the ordinary way; a comment is not executed as a statement.
Escapes. \n is newline, \t horizontal tab, \ backslash, and ” a double quote inside a string. A character literal such as ‘A’ differs from the string literal “A”. The latter includes a terminating null character in its array representation.

17. Tokens: the building units of C source
A token is a lexical unit recognised during translation. A beginner classification includes keywords, identifiers, constants, string literals, operators and punctuators. Some operators are classified as punctuator tokens in the formal language grammar.
Example. int total = a + 10; contains int, total, =, a, +, 10 and ;. The semicolon is a token; ordinary separating whitespace is not an extra token in this count. Comments are removed/replaced during translation rather than becoming executable tokens.

Read complete tokens. >= is one operator, while > followed by = as separate tokens has a different meaning or may be invalid in a context. Quoted text remains a string-literal token even when it contains spaces.
Why useful? Token classification explains how an identifier differs from a keyword and why punctuation changes meaning. It also helps diagnose accidental spelling, missing separators and the confusion between = and ==.
| Source element | Category |
|---|---|
| int | Keyword |
| total, a | Identifiers |
| 10 | Integer constant |
| “Total” | String literal |
| +, = | Operator punctuators |
| ; | Punctuator |
18. Keywords and valid identifiers
Keywords have reserved language meanings. Examples include int, return, if and while. The classic C90 base contains 32 keywords; later standards add more. printf, scanf and main are not keywords even though they are important names in many programs.
Identifiers name objects, functions and other entities. For the basic names used here, start with a letter or underscore and continue with letters, digits or underscores. Do not start with a digit, insert spaces/hyphens or reuse a keyword.

Choose clear names. student_count and total_marks communicate purpose better than unexplained x1. Avoid leading underscores and standard-library names in beginner user code because reservation rules and collisions can apply. A syntactically shaped name is not automatically available in every scope.
Version awareness. C99 added inline, restrict, _Bool, _Complex and _Imaginary; C11 added _Alignas, _Alignof, _Atomic, _Generic, _Noreturn, _Static_assert and _Thread_local. These notes use C17 mode, while listing the classic 32 separately for familiar introductory questions.
| Valid basic name | Invalid example | Reason |
|---|---|---|
| total_marks | total-marks | Hyphen is not a name character |
| value2 | 2value | Leading digit |
| student_count | student count | Embedded space |
| return_value | return | Reserved keyword |
Classic C90 base: 32 keywords
| Group 1 | Group 2 | Group 3 | Group 4 |
|---|---|---|---|
| auto | break | case | char |
| const | continue | default | do |
| double | else | enum | extern |
| float | for | goto | if |
| int | long | register | return |
| short | signed | sizeof | static |
| struct | switch | typedef | union |
| unsigned | void | volatile | while |
19. Constants, literals and symbolic constants
A constant denotes a value that is not changed by assigning a different value to that literal. Integer examples include 25, 031 (octal) and 0x1F (hexadecimal). In the C17 subset here, a leading zero on an integer literal changes its interpretation to octal.
Floating constants include 3.5 and 2.0e3. An unsuffixed ordinary floating constant has type double; suffix f or F selects float. Integer literal type depends on value, base and suffix, not merely how many digits are displayed.

Character and string. ‘A’ is an ordinary character constant of type int in C. “A” is a string-literal array containing A and a terminating null character. C has no separate built-in string scalar type. Do not use single and double quotes interchangeably.
Named values. A macro such as #define RATE 0.05 performs preprocessing substitution; const double rate = 0.05; declares a const-qualified object. They are different mechanisms, and a const object is not automatically an integer constant expression in C.
20. Variables, declarations, initialisation and assignment
A variable is a named object whose stored value can change within the applicable language rules. A declaration gives its type and name. int count = 3; declares and initialises an int object; count = 5; later assigns a new value.
Initialisation versus assignment. Initialisation establishes a value as the object is created. Assignment is an expression that stores a value into an existing modifiable object. The type constrains which values can be represented and how conversions apply.

Uninitialised values. An uninitialised automatic local object does not acquire a dependable default zero. Reading such a value is not a portable way to obtain a random number and can cause undefined behaviour. Initialise values before their first relevant use.
Trace the update. In the example, count begins at 3; count = count + 2; reads the old value, computes 5 and stores it. The assignment symbol is not a mathematical equation that requires both sides to remain permanently equal.
Complete C example
#include <stdio.h>
int main(void)
{
int count = 3;
count = count + 2;
printf(“%d\n”, count);
return 0;
}
Output for the stated example: 5

21. Data types and the kinds of value they represent
Types determine representation-related properties and permitted operations. The introductory arithmetic types include character, signed/unsigned integer and floating types. void has special uses such as indicating no function result; it is not a general storage type for an ordinary value object.
Integer families. char, signed char, unsigned char, short, int, long and long long serve different purposes/ranges. Plain char has its own signedness choice. C99 introduced _Bool; in C17, stdbool.h provides convenient bool, true and false macros.

Floating families. float, double and long double represent real-valued approximations over implementation-defined ranges/precision. They do not store every decimal value exactly. Use a suitable type and output precision for the requirement.
Other type categories. Arrays, pointers, functions, structures, unions and enumerations are developed in later units. A string is commonly represented with a character array, not a separate primitive string type. Data-type choice should follow the value domain rather than a memorised fixed byte table.
| Kind | Example | Use |
|---|---|---|
| Integer | int count = 12; | Whole-number count |
| Floating | double mean = 2.5; | Fractional calculation |
| Character storage | char grade = ‘A’; | Character-code value |
| Boolean | _Bool ready = 1; | Logical state |
| void | int main(void) | No parameters in this form |

22. Type modifiers, sizeof and representation limits
Modifiers such as signed, unsigned, short and long form relevant arithmetic type variants. Their combinations are governed by the language; unsigned double is not a valid ordinary C type. Larger names do not guarantee the same byte count on every system.
sizeof produces the size of an object/type in C bytes and has result type size_t. sizeof(char) is always 1, while a byte has CHAR_BIT bits from limits.h and is at least 8 bits. Four-byte int is a common implementation choice, not a universal requirement.

Limits. limits.h supplies integer limits such as INT_MAX; float.h describes floating properties. Unsigned arithmetic reduces results modulo one greater than the maximum value for that unsigned type. Signed integer overflow has undefined behaviour.
Use measurements carefully. sizeof(int) reports storage size, not every semantic property or the number of useful decimal digits. For ordinary non-variable-length expressions, sizeof does not evaluate its operand; variable-length array cases are a later qualification.
| Fact | Portable statement |
|---|---|
| sizeof(char) | Always 1 C byte |
| int size | Implementation-dependent within standard requirements |
| char signedness | Implementation-dependent |
| Unsigned overflow | Defined modulo arithmetic |
| Signed overflow | Undefined behaviour |
23. Standard output with printf
Standard I/O uses interfaces declared in stdio.h. printf writes formatted output to stdout. Its format string controls text and conversions; ordinary text is displayed directly, while conversion specifications describe the corresponding arguments.
Common formats. %d for int, %u for unsigned int, %c for a character code argument, %f for a double argument in printf, and %zu for size_t. Float arguments undergo promotion to double in this variadic call. Matching format and argument type is essential.

Precision. %.2f displays a floating result with two digits after the decimal point, subject to formatting/rounding rules. It changes the displayed form, not the stored value. %% displays a literal percent sign without consuming an extra value argument.
Example output. The program displays Count=4, Mean=2.50, Grade=A and Progress=50%, each on a new line. Do not assume that formatting a floating result makes the underlying decimal arithmetic exact.
Complete C example
#include <stdio.h>
int main(void)
{
int count = 4;
double mean = 2.5;
char grade = ‘A’;
printf(“Count=%d\n”, count);
printf(“Mean=%.2f\n”, mean);
printf(“Grade=%c\n”, grade);
printf(“Progress=50%%\n”);
return 0;
}
Output for the stated example: Count=4 Mean=2.50 Grade=A Progress=50%

24. Standard input: scanf and character I/O
scanf reads formatted input and stores converted values through suitable pointer arguments. For int value, scanf(“%d”, &value) uses its address. The & here provides where to store the value; detailed pointer study follows in Unit III.
Type matching. scanf %d expects int*, %f expects float* and %lf expects double*. This differs from printf, where %f prints a double argument. scanf returns the number of successful assignments or an input-failure indication; check it before using the destination.
Character input. %c does not automatically skip preceding whitespace. A leading space in ” %c” asks scanf to skip whitespace first. getchar returns int so that character values can be distinguished from EOF; putchar outputs a character value.
Example contract. The program accepts one decimal integer representable as int, prints it and rejects a failed conversion with a nonzero status. The simple if guard previews Unit II. This check is not a complete strategy for out-of-range numeric text or arbitrary hostile input.
String I/O preview. puts writes a string followed by a newline. scanf %s reads a whitespace-delimited sequence and needs an adequately sized character array plus a width limit, such as %19s for a 20-element buffer. Detailed arrays/strings belong to Unit III. Do not use removed gets or assume fflush(stdin) is a portable input-clearing operation.
| Destination/value type | printf conversion | scanf conversion |
|---|---|---|
| int | %d | %d with int* |
| unsigned int | %u | %u with unsigned int* |
| float | %f after promotion | %f with float* |
| double | %f | %lf with double* |
| char value/object | %c | %c with char* |
Complete C example
#include <stdio.h>
int main(void)
{
int value;
if (scanf(“%d”, &value) != 1)
return 1;
printf(“Value=%d\n”, value);
return 0;
}
Output for the stated example: Value=12
25. Arithmetic operators and integer division
The operators +, -, *, / and % perform addition, subtraction, multiplication, division and integer remainder where their operand types permit them. * is multiplication in an arithmetic expression; its meaning depends on context when pointers are studied later.
Integer division. With integer operands in this C17 model, 7/2 gives 3, discarding the fractional part toward zero. 7.0/2 produces a floating result 3.5. Assigning the already-computed integer quotient to double does not restore the lost fraction.

Remainder. % requires integer operands. For representable division, a = (a/b)*b + a%b. With negative integers, -7/2 is -3 and -7%2 is -1. Division/remainder by zero is invalid; some extreme signed divisions also cannot be represented.
Safe reasoning. State operand types and representability assumptions before evaluating. Do not infer that all arithmetic uses real-number algebra: type conversion, range and floating approximation affect actual C expressions.
Complete C example
#include <stdio.h>
int main(void)
{
printf(“%d %d\n”, 7 / 2, 7 % 2);
printf(“%.1f\n”, 7.0 / 2);
printf(“%d %d\n”, -7 / 2, -7 % 2);
return 0;
}
Output for the stated example: 3 1 3.5 -3 -1

26. Unary, increment and decrement operators
Unary operators act on one operand. Unary + and – describe arithmetic sign; ! forms logical negation and ~ forms bitwise complement. ++ and — update an appropriate modifiable operand by one within the relevant representability rules.
Prefix. In b = ++a;, a is incremented and the expression yields its new value for b. Postfix. In b = a++;, the expression yields the previous value while the increment updates a. Explain both the stored state and expression result.

Separate operations. The example resets a before demonstrating each form, producing 6 6 and then 6 5. These are separate full expressions with defined sequencing. The demonstration does not depend on argument evaluation order.
Avoid traps. Expressions such as i++ + ++i modify the same scalar without the needed sequencing and have undefined behaviour in C. Do not assign a single numerical output to them. Writing several distinct statements is clearer.
Complete C example
#include <stdio.h>
int main(void)
{
int a = 5;
int b = ++a;
printf(“%d %d\n”, a, b);
a = 5;
b = a++;
printf(“%d %d\n”, a, b);
return 0;
}
Output for the stated example: 6 6 6 5
27. Relational, equality and logical operators
Relational operators <, <=, > and >= compare values; == and != test equality/inequality. Their results are int values 0 or 1. = assigns a value, so it is not a replacement for == in a comparison.
Logical operators. && means logical AND, || logical OR and ! logical NOT. Zero is false and a nonzero scalar value is true in the relevant logical context. The logical result is normalised to 0 or 1.

Short-circuit. && evaluates its right operand only if the left is true; || evaluates it only if the left is false. This is useful for a guard such as denominator != 0 && numerator/denominator > 2, provided the division is otherwise representable.
Range check. Mathematical notation 0 < x < 10 does not express the intended range test in C. Write x > 0 && x < 10. Bitwise & and | perform a different kind of operation and do not provide the same short-circuit rule.
| A truth | B truth | A && B | A || B |
|---|---|---|---|
| False | False | 0 | 0 |
| False | True | 0 | 1 |
| True | False | 0 | 1 |
| True | True | 1 | 1 |
28. Assignment and compound assignment
The assignment operator = stores a converted value into a modifiable left operand. In x = x + 3;, the right expression uses the old x, then the result is assigned. A const-qualified object cannot be modified by ordinary assignment.
Compound forms. +=, -=, *=, /= and %= combine an operation with assignment; bitwise/shift compound forms also exist. For a simple int x, x += 3; has the intended update meaning. In general, compound assignment evaluates its left operand once, so it is not always a safe textual substitution.
Chaining. a = b = 5 associates to the right and assigns the converted result through the chain. Read it according to the types, not as a permanent mathematical equality. Clear separate assignments can be easier for beginners.
Type effect. Integer x /= 2 performs the relevant integer arithmetic and stores an integer result; it does not magically make x floating. These operators are introduced here under Unit I operators and revisited with loops in Unit II.
Complete C example
#include <stdio.h>
int main(void)
{
int x = 10;
x += 5;
x *= 2;
x /= 4;
printf(“%d\n”, x);
return 0;
}
Output for the stated example: 7
29. Conditional operator, comma and other useful operators
The conditional operator condition ? expr1 : expr2 evaluates the condition and selects one of the two result expressions. Only the selected alternative is evaluated. Types of the alternatives determine the resulting type according to the language rules.
Example. max = a > b ? a : b; selects a larger value for the two given int operands. It is an expression, whereas if is a statement. The example here uses fixed values; general decision statements are covered in Unit II.
Comma operator. In an expression such as (a = 2, a + 3), the left operand is evaluated before the right and the expression yields the right result. A comma separating function arguments is not the comma operator and does not impose the same argument-evaluation order.
Other contexts. sizeof queries type/object size; & can obtain an address and * can dereference a pointer in appropriate contexts. These are not all arithmetic operations. Recognise syntax now and study full pointer rules in the assigned later unit.
Complete C example
#include <stdio.h>
int main(void)
{
int a = 8, b = 5;
int larger = a > b ? a : b;
printf(“%d\n”, larger);
return 0;
}
Output for the stated example: 8
30. Bitwise operators and shift operations
Bitwise &, |, ^ and ~ operate on integer bit representations after relevant promotions/conversions. They mean bitwise AND, OR, exclusive OR and complement. Use unsigned operands for clear beginner examples and avoid confusing them with logical truth operations.
Example. With unsigned values 6 (binary 110) and 3 (011), AND gives 2 (010), OR gives 7 (111) and XOR gives 5 (101). The displayed three low bits are enough for these particular positive values.

Shifts. 3u << 1 gives 6 and 6u >> 1 gives 3. The shift count must be non-negative and less than the width of the promoted left operand. Signed shifts have additional restrictions/implementation choices; do not use a vague always-multiply/divide rule.
Width matters. ~0u produces the maximum value of unsigned int, not a universal small decimal value. A diagram showing four low bits is not a declaration that every C integer has four bits.
Complete C example
#include <stdio.h>
int main(void)
{
unsigned int a = 6u, b = 3u;
printf(“%u %u %u\n”,
a & b, a | b, a ^ b);
printf(“%u %u\n”, 3u << 1, 6u >> 1);
return 0;
}
Output for the stated example: 2 7 5 6 3
31. Precedence, associativity and evaluation order
Precedence determines how an expression groups when parentheses are absent. * and / bind more tightly than + and -, so 2 + 34 groups as 2 + (34). Parentheses can explicitly change grouping.
Associativity resolves grouping at the same precedence level. a-b-c groups as (a-b)-c; assignment groups right to left. It is not a universal rule that operands execute in that left/right order.

Evaluation order concerns when subexpressions and side effects occur. Many operand and function-argument orders are unspecified in C; certain operators such as &&, || and the comma operator provide sequencing rules. Precedence alone cannot justify a side-effect puzzle.
Practical method. Parenthesise the intended relationship, identify operand types, avoid conflicting side effects and compute in small clear steps. Code should communicate a correct algorithm rather than rely on memorising a clever ambiguous-looking expression.
32. Conversions, casts and reliable expression reasoning
Implicit conversions occur in arithmetic, assignment and calls according to the relevant rules. The usual arithmetic conversions find common arithmetic types; integer promotions can affect char and short operands. Mixing signed and unsigned types deserves care.
Explicit cast. (double)total / count converts total before division, so the example computes a real-valued quotient. (double)(total/count) converts only the already-calculated integer quotient. The position of the cast matters.

Assignment conversion. Converting a representable floating value to int truncates the fractional part toward zero. An out-of-range conversion is not a portable wraparound rule. Floating calculations can incur rounding, and an exact-looking decimal output does not remove that fact.
Final checklist. State value domains, types, units and valid input assumptions; use matching formats; initialise objects; understand grouping and sequencing; build with diagnostics; test independently. This connects Unit I problem solving to reliable C code.
Complete C example
#include <stdio.h>
int main(void)
{
int total = 16, count = 3;
double x = (double)total / count;
double y = (double)(total / count);
printf(“%.2f %.2f\n”, x, y);
return 0;
}
Output for the stated example: 5.33 5.00
SOLVED EXAMPLES AND APPLICATIONS
The following are original teaching examples. Identify the relevant role, working principle and assumptions before interpreting the result.
Solved example 1.1: IPO design
Specify IPO and assumptions for calculating simple interest.
-
1. Inputs. Principal P, annual rate R expressed as a percent and time T in years.
-
2. Process/output. SI = P x R x T / 100; output SI in the principal currency. State valid non-negative ranges and a suitable numeric representation.
Answer. An explicit input contract and units prevent confusion between percent and fractional rate.
Solved example 1.2: Algorithm for rectangle area
Give a finite algorithm for area when dimensions are valid non-negative real values.
-
1. Input. Obtain length L and breadth B in the same unit.
-
2. Calculation/result. Compute A = L x B; display A in square units; stop.
Answer. The algorithm is language-independent; the C implementation also chooses types, input checks and representable ranges.
Solved example 1.3: Token count
Classify the tokens in int total = price + 25;.
-
1. Separate. int, total, =, price, +, 25, ;.
-
2. Classify. Keyword; identifier; assignment punctuator; identifier; additive punctuator; integer constant; semicolon punctuator.
Answer. Seven tokens. Ordinary separating spaces do not create additional tokens in this example.
Solved example 1.4: Identifier correction
Which of sum_2, 2sum, total-value and while can be used as a new basic user identifier?
-
1. Apply shape rules. sum_2 has a permitted basic shape. 2sum starts with a digit; total-value contains a hyphen.
-
2. Check reservation. while is a keyword and cannot be used as the new identifier.
Answer. sum_2 is suitable here, subject to the usual scope/conflict rules.
Solved example 1.5: Literal bases
Interpret the integer constants 25, 031 and 0x19.
-
1. Decimal. 25 has decimal value 25.
-
2. Other bases. 031 is octal: 3 x 8 + 1 = 25; 0x19 is hexadecimal: 1 x 16 + 9 = 25.
Answer. All three have decimal value 25, although their source representations differ.
Solved example 1.6: Integer average trap
int a = 4, b = 5, c = 7; double mean = (a + b + c)/3; What value is assigned?
-
1. Evaluate integers. The integer total is 16 and integer division 16/3 gives 5.
-
2. Assignment. That integer result converts to double 5.0. A real average needs conversion before division or a suitable floating operand.
Answer. mean receives 5.0, not 5.333… . A later assignment conversion cannot recover the discarded fraction.
Solved example 1.7: Arithmetic grouping
Evaluate 18 – 6 / 3 * 2 with int operands and representable intermediate results.
-
1. Multiplicative group. / and * have the same precedence and group left to right: (6/3)*2 = 4.
-
2. Subtract. 18 – 4 = 14.
Answer. 14. This grouping example has no side-effect evaluation-order puzzle.
Solved example 1.8: Remainder with negative input
Evaluate -9/4 and -9%4 in C17.
-
1. Division. The quotient truncates toward zero, so -9/4 = -2.
-
2. Remainder identity. -9 = (-2)*4 + (-1), so the remainder is -1.
Answer. Quotient -2 and remainder -1 for these representable operations.
Solved example 1.9: Prefix and postfix trace
Start x = 4. Execute y = x++; then z = ++x; as separate statements. Find x, y and z.
-
1. Postfix. y receives 4; x becomes 5.
-
2. Prefix. x becomes 6; z receives 6.
Answer. x = 6, y = 4, z = 6. The separate full expressions define the needed sequencing.
Solved example 1.10: Logical versus bitwise
For int a = 6 and b = 3, compare a && b with a & b.
-
1. Logical. Both operands are nonzero, so a && b gives 1.
-
2. Bitwise. The relevant low bits are 110 and 011; AND gives 010, decimal 2.
Answer. Logical result 1; bitwise result 2. The operators also have different evaluation rules.
Solved example 1.11: Range-test correction
Why does 0 < x < 10 not express the intended open interval in C?
-
1. Grouping. It groups as (0 < x) < 10. The first comparison gives 0 or 1.
-
2. Correct expression. Use x > 0 && x < 10 for the intended condition, with an appropriate x type/value domain.
Answer. The chained mathematical notation is inappropriate; write both comparisons joined with logical AND.
Solved example 1.12: Short-circuit guard
For denominator = 0, does denominator != 0 && numerator/denominator > 2 evaluate its right operand?
-
1. First operand. denominator != 0 is false.
-
2. Rule. Logical AND skips the right operand when its left operand is false.
Answer. No. This guard avoids that zero division; it does not justify every other possible signed division input.
Solved example 1.13: Conditional expression
For int a = 12 and b = 7, evaluate a > b ? a – b : b – a.
-
1. Condition. 12 > 7 is true.
-
2. Selected expression. Evaluate a – b = 5; the unselected alternative is not evaluated.
Answer. The expression yields int value 5 for these operands.
Solved example 1.14: Bitwise operations
Using unsigned 5u and 3u, find AND, OR and XOR.
-
1. Represent the low bits. 5 is 101; 3 is 011.
-
2. Operate. AND = 001 = 1; OR = 111 = 7; XOR = 110 = 6.
Answer. Results are 1u, 7u and 6u. The displayed bits are not the entire implementation integer width.
Solved example 1.15: Correct formatted input
A double temperature is read using scanf(“%f”, &temperature). Correct the mismatch.
-
1. Destination type. &temperature has type double*.
-
2. Required conversion. Use scanf %lf for double*. scanf %f expects float*. Check the successful assignment count before using the value.
Answer. The correct conversion is %lf for this destination. printf %f has different argument conventions.
Solved example 1.16: Undefined-expression question
Can a single guaranteed value be given for i++ + ++i in C?
-
1. Identify side effects. Both operands modify i without the sequencing required between those modifications.
-
2. Conclusion. The expression has undefined behaviour; precedence and a particular observed compiler result do not repair it.
Answer. No guaranteed numerical result. Rewrite the intended updates as clear separate statements.
Complete practice programs
Each example states its input contract. The small if guard checks failed conversion; full decision syntax is developed in Unit II.
Practice program 1.1: Rectangle area
Read two non-negative dimensions representable as double. This teaching input contract excludes overflow and malformed out-of-range numeric text.
#include <stdio.h>
int main(void)
{
double length, breadth;
if (scanf(“%lf %lf”,
&length, &breadth) != 2)
return 1;
double area = length * breadth;
printf(“Area=%.2f\n”, area);
return 0;
}
Sample input: 3 4 Output: Area=12.00
Practice program 1.2: Average of three values
Fixed values 4, 5 and 7 demonstrate a fractional mean using double operands.
#include <stdio.h>
int main(void)
{
double a = 4, b = 5, c = 7;
double mean = (a + b + c) / 3.0;
printf(“Mean=%.2f\n”, mean);
return 0;
}
Sample input: None (fixed values) Output: Mean=5.33
Practice program 1.3: Split a duration
Split fixed 3665 seconds using division and remainder.
#include <stdio.h>
int main(void)
{
int total = 3665;
printf(“%d:%02d:%02d\n”,
total / 3600,
(total % 3600) / 60, total % 60);
return 0;
}
Sample input: None (fixed values) Output: 1:01:05
Practice program 1.4: Swap two values
Exchange two int values using a temporary object.
#include <stdio.h>
int main(void)
{
int a, b;
if (scanf(“%d %d”, &a, &b) != 2)
return 1;
int temporary = a;
a = b;
b = temporary;
printf(“%d %d\n”, a, b);
return 0;
}
Sample input: 7 11 Output: 11 7
Practice program 1.5: Celsius to Fahrenheit
Apply F = C x 9/5 + 32 using floating operands. This is a unit-conversion exercise, not medical guidance.
#include <stdio.h>
int main(void)
{
double celsius;
if (scanf(“%lf”, &celsius) != 1)
return 1;
double fahrenheit =
celsius * 9.0 / 5.0 + 32.0;
printf(“F=%.2f\n”, fahrenheit);
return 0;
}
Sample input: 25 Output: F=77.00
Practice program 1.6: Simple-interest calculation
For this numerical exercise, P is a principal, R an annual percentage and T a number of years. No compounding is included.
#include <stdio.h>
int main(void)
{
double p, r, t;
if (scanf(“%lf %lf %lf”,
&p, &r, &t) != 3)
return 1;
double interest = p * r * t / 100.0;
printf(“SI=%.2f\n”, interest);
return 0;
}
Sample input: 1000 5 2 Output: SI=100.00
EXAM QUESTIONS WITH ANSWERS
Practice questions covering the definitions, comparisons and applications in Unit I.
Short-answer practice
Q1. Define an algorithm.
Answer. A finite, unambiguous method with effective steps that produces the specified result for inputs in its stated domain.
Q2. What is IPO analysis?
Answer. Identification of inputs, required processing and outputs, with units, constraints and assumptions.
Q3. Top-down versus bottom-up?
Answer. Top-down decomposes a task into smaller responsibilities. Bottom-up combines useful components. They can support the same development process.
Q4. What is pseudocode?
Answer. A consistent, readable description of an algorithm independent of a particular programming-language syntax.
Q5. Name the main flowchart symbols.
Answer. Terminal for start/stop, process rectangle, input/output parallelogram, decision diamond and directed flow lines.
Q6. What is structured programming?
Answer. Organising control using clear sequence, selection and iteration with manageable blocks and responsibilities.
Q7. Who developed C?
Answer. Dennis Ritchie at Bell Labs in the early 1970s, following the BCPL/B lineage and alongside Unix.
Q8. Is C formally a middle-level language?
Answer. Middle-level is an informal teaching label. C is a general-purpose procedural language with both high-level abstractions and lower-level facilities.
Q9. What is a token?
Answer. A lexical unit recognised during translation, such as a keyword, identifier, constant, string literal or punctuator.
Q10. Are main and printf keywords?
Answer. No. main is an identifier with a special hosted entry role; printf is a standard-library function name.
Q11. What is an identifier?
Answer. A name for a language entity. Basic names start with a letter/underscore and continue with letters, digits or underscores, subject to reservation rules.
Q12. Initialisation versus assignment?
Answer. Initialisation establishes an object value when created; assignment later stores a converted value into an existing modifiable object.
Q13. Does a local int default to zero?
Answer. An uninitialised automatic local int has no dependable default zero value; initialise it before relevant use.
Q14. Is int always four bytes?
Answer. No. Its size/range depends on the implementation within the standard requirements. sizeof(char) is always one C byte.
Q15. What does sizeof return?
Answer. A size in C bytes with result type size_t; a byte has CHAR_BIT bits.
Q16. What is the role of stdio.h?
Answer. It supplies declarations and related facilities for standard input/output interfaces.
Q17. scanf %f versus %lf?
Answer. scanf %f expects float*, while %lf expects double*. printf %f receives a double argument after relevant promotions.
Q18. Why check scanf return value?
Answer. It indicates successful assignments or input failure, helping prevent use of a destination after an unsuccessful conversion.
Q19. Integer versus floating division?
Answer. Integer operands produce an integer quotient truncated toward zero. A suitable floating operand changes the arithmetic domain.
Q20. Prefix versus postfix increment?
Answer. Prefix yields the updated value; postfix yields the previous value while updating the operand, within valid sequencing/range rules.
Q21. Logical versus bitwise AND?
Answer. Logical AND tests truth, yields 0/1 and short-circuits. Bitwise AND combines integer bits and does not use that same short-circuit rule.
Q22. Precedence versus evaluation order?
Answer. Precedence controls grouping. Evaluation order controls when computations/side effects occur; grouping does not specify every order.
Q23. Why cast before division?
Answer. Converting an operand before integer division can produce a fractional quotient; casting an already-truncated quotient cannot restore its fraction.
Q24. What is undefined behaviour?
Answer. Behaviour for which the language imposes no required result, such as a relevant signed overflow or an unsequenced conflicting modification.
Structured long-answer practice
Use a definition, clearly separated points, a relevant example and a labelled diagram or comparison where appropriate. Match the length to the marks and the question rather than memorising a fixed word count.
Long question 1. Explain systematic problem solving, algorithms and flowcharts.
Answer
-
1. Specification. A problem definition identifies inputs, intended results, valid domains, units and constraints. IPO analysis separates what is read, computed and displayed.
-
2. Method. Top-down decomposition creates manageable responsibilities; bottom-up construction combines suitable components. An algorithm gives definite effective steps and terminates for its stated valid input domain.
-
3. Representation. Pseudocode expresses the method in readable structured text. Flowcharts use terminals, processes, input/output symbols, labelled decisions and directed paths.
-
4. Verification. A dry run records intermediate state. Tests compare the implementation with independently expected outputs, including suitable ordinary, boundary and invalid cases.
-
5. Implementation. C types, expressions, I/O and build tools turn the algorithm into a program. Compilation success alone does not establish mathematical or requirement correctness.
Long question 2. Discuss structured programming and the features/history of C.
Answer
-
1. Structure. Sequence, selection and iteration organise control. Clear blocks, meaningful names and refinement help testing and maintenance. Function-based modularity supports structure without being the same concept.
-
2. History. Dennis Ritchie developed C at Bell Labs in the early 1970s following BCPL and B. Its growth alongside Unix helped demonstrate useful systems implementation and portability.
-
3. Standards. ANSI C89 and ISO C90 established an early standard basis; later revisions added facilities. These notes use C17 mode, and keyword/feature claims are qualified by version.
-
4. Features. Typed objects, functions, expressions, standard-library interfaces and bit/memory facilities support general-purpose procedural programming. Middle-level is an informal descriptive term.
-
5. Limits. Portability depends on respecting the language and implementation limits. C does not automatically prevent every invalid memory or arithmetic operation; efficient, maintainable code needs suitable design and testing.
Long question 3. Explain program structure and the compile-link-run process.
Answer
-
1. Source organisation. A small hosted program includes required headers, declarations and main with a braced body. Many declarations/expression statements end in semicolons, while directives and compound bodies follow different syntax.
-
2. Entry and output. int main(void) is a hosted no-parameter entry form. printf uses the declaration available through stdio.h. return 0 communicates successful termination rather than printing an extra value.
-
3. Translation. In the illustrated GCC pipeline, preprocessing handles directives, compilation proper generates assembly and assembly creates object code. A driver command can run several stages.
-
4. Linking and running. The linker combines required objects/definitions into an executable. The host starts that executable using its environment conventions. A source editor or object file alone is not a complete running program.
-
5. Diagnosis. Compiler diagnostics, unresolved link references and incorrect runtime results are different problems. Rebuild after correcting a meaningful diagnostic and then test the executable against the requirement.
Long question 4. Explain lexical elements, variables and data-type selection.
Answer
-
1. Tokens. Keywords, identifiers, constants, strings and punctuators form the source. int total = a + 10; has seven tokens. Whitespace separates where needed; comments are not executed instructions.
-
2. Names and literals. Names follow identifier/reservation rules and are case-sensitive. Character and string literals differ. Integer bases, floating suffixes and language version affect interpretation.
-
3. Objects. Declarations establish type/name information. Initialisation and later assignment are distinct. Uninitialised automatic objects must not be read as if they supplied a dependable zero.
-
4. Types and limits. Integer, floating and character values require appropriate types. Width and plain-char signedness vary; sizeof(char) is one C byte. Header limits describe the implementation.
-
5. Conversions. Arithmetic and assignment can convert values. Signed/unsigned mixtures, truncation, overflow and floating rounding require attention. A suitable type follows the value domain rather than a universal fixed-byte assumption.
Long question 5. Explain standard formatted input and output.
Answer
-
1. Library interfaces. stdio.h provides declarations. stdin/stdout represent standard input/output streams. printf writes formatted output; scanf converts input and assigns through appropriate pointer arguments.
-
2. Output matching. printf %d matches int, %u unsigned int, %f double, %c a character-code argument and %zu size_t. Float arguments promote to double. %.2f changes display precision, not storage.
-
3. Input matching. scanf %d needs int*, %f float* and %lf double*. For a scalar destination its address is supplied with &. Successful-assignment checks precede relevant use.
-
4. Whitespace and strings. %c does not skip whitespace automatically; a leading format space can request skipping. String input needs suitable storage and a width limit. getchar returns int to distinguish character values from EOF.
-
5. Scope. The examples declare representable valid-input contracts and illustrate basic guards. A scanf assignment-count check is not a complete out-of-range numeric-text parser; obsolete unsafe functions are not required to demonstrate standard I/O.
Long question 6. Explain C operators, expressions and conversion pitfalls.
Answer
-
1. Arithmetic and update. Arithmetic depends on operand types. Integer division truncates toward zero; remainder follows the quotient identity. Prefix/postfix update results differ, and separate statements make sequencing clear.
-
2. Tests and truth. Relational/equality tests yield int 0 or 1. Logical operators use truth and short-circuit rules. Bitwise operators combine integer representations and differ from logical operators.
-
3. Assignment and selection. Assignment stores converted values. Compound forms update while evaluating their left operand once. The conditional operator selects one evaluated alternative; the comma operator sequences its own operands.
-
4. Grouping. Precedence and associativity determine expression grouping. Parentheses communicate intent. They do not establish every operand/function-argument evaluation order.
-
5. Reliable evaluation. Convert before division when a real quotient is required, state range/width assumptions and avoid unsequenced conflicting modifications. Signed overflow, invalid shifts and division by zero are not portable numerical-output puzzles.
QUICK REVISION – UNIT I
The complete unit at a glance
| Syllabus area | Essential understanding |
|---|---|
| Problem solving | IPO, domain/units, decomposition, systematic development, dry runs and tests. |
| Algorithm / flowchart | Finite definite method; proper symbols; sequence, selection and iteration. |
| Structured programming | Clear control flow, blocks and responsibilities support maintainable programs. |
| C foundations | History, features, hosted main, declarations, statements and library interfaces. |
| Build | Preprocess, compile proper, assemble, link and run; different error classes. |
| Lexical elements | Characters, tokens, keywords, identifiers, constants and strings. |
| Objects and types | Declaration, initialisation, assignment, implementation limits and conversion. |
| Standard I/O | Matching formats, input assignment checks, character/string qualifications. |
| Operators / expressions | Arithmetic, updates, comparisons, logic, assignment, conditional, comma, bitwise and grouping. |
Operator precedence: higher groups first
| Group | Main operators | Grouping association |
|---|---|---|
| Postfix | () call, [] indexing, . ->, postfix ++ — | Left to right |
| Unary / cast | prefix ++ –, + -, ! ~, & *, sizeof, cast | Right to left |
| Multiplicative | * / % | Left to right |
| Additive | + – | Left to right |
| Shift | << >> | Left to right |
| Relational | < <= > >= | Left to right |
| Equality | == != | Left to right |
| Bitwise AND | & | Left to right |
| Bitwise XOR | ^ | Left to right |
| Bitwise OR | | | Left to right |
| Logical AND | && | Left to right |
| Logical OR | || | Left to right |
| Conditional | ?: | Right to left |
| Assignment | = and compound assignments | Right to left |
| Comma operator | , | Left to right |
Important: this table describes grouping, not every operand evaluation order. Parentheses communicate intended grouping; defined sequencing rules and side-effect restrictions still apply.
Frequently confused ideas
| Concept A | Concept B | Distinction |
|---|---|---|
| = | == | Assignment stores; equality compares. |
| Integer quotient | Real quotient | Conversion must occur before division to preserve a fraction. |
| scanf %f | scanf %lf | float* versus double* destination. |
| && / || | & / | | Logical truth with short-circuit versus integer bit operations. |
Abbreviations and key terms
| Term | Meaning | Term | Meaning |
|---|---|---|---|
| IPO | Input-process-output analysis | Keyword | Reserved language word |
| Algorithm | Finite definite solution method | Identifier | Name of a language entity |
| Pseudocode | Readable algorithm description | Literal | Source notation for a value/string |
| Flowchart | Graphical control-flow representation | Variable | Named object with stored value |
| Dry run | Manual state/value trace | Initialisation | Establishes initial object value |
| Structured control | Sequence, selection and iteration | Type | Classifies representation and operations |
| Source file | Program text for translation | size_t | Unsigned integer type for sizes |
| Preprocessor | Handles translation directives | Conversion | Changes value representation/type |
| Object file | Translated unit before final linking | Expression | Operands/operators computing a result |
| Linker | Resolves/combines required definitions | Precedence | Expression grouping priority |
| Executable | Build product started by the host | Short-circuit | Conditionally skips a logical operand |
| Token | Lexical source unit | Undefined behaviour | No required language result |
Common mistakes to avoid
-
Coding before identifying input, output, units and valid domains.
-
Drawing unlabelled flowchart decision exits or loops without progress.
-
Treating main, printf or scanf as C keywords.
-
Assuming every keyword count applies to every language version.
-
Using a local uninitialised variable as if it defaulted to zero.
-
Assuming int always has four bytes or that signed overflow wraps.
-
Confusing single-quoted characters and double-quoted strings.
-
Using mismatched printf or scanf conversion types.
-
Ignoring scanf assignment count or treating it as complete range validation.
-
Expecting a cast after integer division to restore a lost fraction.
-
Writing mathematical chained comparisons instead of two logical tests.
-
Confusing logical and bitwise operators.
-
Using precedence to invent a result for an undefined side-effect expression.
Final check: define the algorithm, identify types/ranges, group the expression, verify sequencing, match formats, compile with diagnostics and compare outputs with independent expectations.