Understand
Identify the inputs, required outputs, constraints and exceptional cases.
I SEMESTER · C PROGRAMMING · UNIT 01
Understand the logic. Learn the language.
Run your first programs.
LESSON 01
A computer follows instructions precisely. Problem solving means turning a requirement into a sequence of unambiguous operations, then checking that the result is correct. Code is the final expression of that plan.
Identify the inputs, required outputs, constraints and exceptional cases.
Choose a method. Write an algorithm and draw its flowchart.
Translate the plan into C, compile it, and fix reported errors.
Test normal, boundary and invalid inputs. Compare actual and expected output.
For a circle, the output is area; the input is radius; the rule is area = π × radius × radius. A radius of zero is valid. A negative radius is outside the problem domain. Writing these facts first prevents avoidable mistakes.
An algorithm is a finite sequence of clearly defined steps for solving a problem. It may take zero or more inputs and must produce a result. Its operations must be definite, feasible to carry out, and terminate for valid inputs. A program implements an algorithm in a programming language.
A dry run executes the steps by hand, recording variable values. It checks your reasoning before you rely on a compiler. A compiler can reject invalid syntax; it cannot guarantee that your algorithm solves the intended problem.
LESSON 02
A flowchart represents an algorithm with connected symbols. Follow arrows in the direction of execution, and label the outcomes of a decision. The chart and algorithm should describe the same computation.
An oval or rounded rectangle marks entry or exit.
A rectangle represents an assignment or calculation.
A parallelogram represents accepting or displaying data.
A diamond tests a condition. Label its branches Yes/No or True/False.
A labelled circle links separated parts of a large chart.
An arrow shows which operation happens next.
FOLLOW THE VALUES
A = πr². Use r ≥ 0 and return the area in square units.
Input: 3 → area: 28.27 (rounded to two decimal places).
Press Next step to follow the algorithm.
| Step | What happens |
|---|
#include <stdio.h>
#define PI 3.141592653589793
int main(void)
{
double radius, area;
/* STDIN: enter one non-negative radius, for example 3. */
if (scanf("%lf", &radius) != 1 || radius < 0) {
printf("Enter a non-negative radius.\n");
return 1;
}
area = PI * radius * radius;
printf("Area = %.2f\n", area);
return 0;
}
Area = 28.27
Keep the largest value seen so far. This works with negative values and ties.
Input: 12, 7, 20 → largest: 20. Try −8, −2, −11, or three equal numbers.
Press Next step to follow the algorithm.
| Step | What happens |
|---|
#include <stdio.h>
int main(void)
{
double a, b, c, largest;
/* STDIN: three numbers separated by spaces. */
if (scanf("%lf %lf %lf", &a, &b, &c) != 3) {
printf("Enter three numbers.\n");
return 1;
}
largest = a;
if (b > largest) {
largest = b;
}
if (c > largest) {
largest = c;
}
printf("Largest = %.2f\n", largest);
return 0;
}
Largest = 20.00
Read N values and add each value to a running total. Here N is the count, not one of the values.
Input: N = 3 and values 5, 8, 2 → sum: 15. The tracer derives N from your list.
Press Next step to follow the algorithm.
| Step | What happens |
|---|
#include <stdio.h>
int main(void)
{
int n, i;
double number, sum = 0;
/* STDIN: count N (1 to 100), followed by N numbers. */
if (scanf("%d", &n) != 1 || n < 1 || n > 100) {
printf("Enter a count from 1 to 100.\n");
return 1;
}
for (i = 1; i <= n; i++) {
if (scanf("%lf", &number) != 1) {
printf("A number is missing or invalid.\n");
return 1;
}
sum = sum + number;
}
printf("Sum = %.2f\n", sum);
return 0;
}
Sum = 15.00
The example above adds N supplied values. If the question asks for the first N natural numbers, add 1 + 2 + … + N instead. For N = 5 this gives 15; the formula is N × (N + 1) / 2. Always state which problem your algorithm solves.
The C examples preview if and for so that you can see your algorithms become programs. Selection and repetition are studied in more detail in the later units.
LESSON 03
C is a general-purpose, procedural programming language. Dennis Ritchie developed it at Bell Labs in the early 1970s as Unix was evolving. Its roots run through BCPL and B. The name C followed B; it is not an abbreviation.
Earlier languages influenced C’s syntax and design.
C combined types with low-level operations useful for systems programming.
ANSI standardized C in 1989; ISO adopted it in 1990.
| Feature | Practical meaning |
|---|---|
| Structured, procedural style | Use functions and sequence, selection and repetition to organize a solution. |
| Compiled execution | A toolchain translates source code into an executable program. |
| Portability | Standard C can be recompiled on many platforms. Sizes, libraries and compiler extensions can still differ. |
| Rich operations | Arithmetic, comparisons, bit operations, arrays, pointers and user-defined structures support many tasks. |
| Standard library | Headers declare facilities for input/output, strings, mathematics and other common work. |
| Low-level control | Pointers and explicit storage management allow close control of memory, but require care. |
The informal term “middle-level language” describes C’s mix of high-level control structures and low-level operations; it is not a formal standards category. C is case-sensitive: total and Total are different identifiers.
LESSON 04
A textbook often divides a program into documentation, header inclusion, symbolic definitions, global declarations, the main function and other functions. These are useful organizational sections, not a requirement to fill every section in every program.
#include <stdio.h>
int main(void)
{
printf("Hello, BCA!\n");
return 0;
}
Hello, BCA!
| Part | What it does |
|---|---|
#include <stdio.h> | Makes the standard input/output declarations, including printf, available. A preprocessing directive does not end with a semicolon. |
int main(void) | Defines the entry function for this hosted C program. It returns int and takes no arguments. Use this form rather than void main(). |
{ … } | Braces group the function body. Statements are executed in order. |
printf("Hello, BCA!\n"); | Writes text to standard output. The escape sequence \n produces a newline. |
return 0; | Returns a success status to the environment. |
/* comment */ | A comment explains code to the reader; it is not an executable instruction. This comment form is supported by ANSI C. |
.c extension.#include and #define.gcc -std=c90 -Wall -Wextra main.c -o main
# Linux / macOS: ./main
# Windows terminal: .\main.exeThese examples use C90-compatible syntax. Modern compilers may default to a newer standard. GCC on many Unix-like systems needs -lm when linking some functions from math.h, for example gcc main.c -o main -lm.
| Kind | Example | How to investigate |
|---|---|---|
| Compile-time error | A missing semicolon or an undeclared identifier. | Read the first diagnostic and check that line and the preceding line. |
| Execution / runtime problem | Division by zero or accessing memory outside an array. | Check inputs and valid ranges; some invalid operations have undefined behavior rather than a predictable error message. |
| Logic error | Using 2 × π × r when the requirement is area. | Compare with expected results; trace variables and revisit the algorithm. |
LESSON 05
The basic source character set includes letters A–Z and a–z, digits 0–9, whitespace and punctuation such as + - * / = ; , ( ) { } [ ] #. Letters form names; digits form numbers; symbols express operations and structure. A token is a lexical unit recognized from the source.
For introductory study, group tokens as keywords, identifiers, constants, string literals, operators and punctuators (special symbols). Formally, C groups operators such as + with punctuators. Whitespace and comments help separate source text but are not ordinary program tokens.
CLICK A TOKEN
Select a token to learn its role in int score = 10;.
A keyword has a reserved meaning and cannot be used as an ordinary variable name. ANSI C / C90 has the following 32 keywords. Later C editions add more.
autobreakcasecharconstcontinuedefaultdodoubleelseenumexternfloatforgotoifintlongregisterreturnshortsignedsizeofstaticstructswitchtypedefunionunsignedvoidvolatilewhileAn identifier names an object, function or other program entity. A simple identifier starts with a letter or underscore, followed by letters, digits or underscores. Keywords cannot be identifiers. For your own names, begin with a letter and avoid leading underscores because many underscore forms are reserved.
| Valid example | Invalid example | Reason |
|---|---|---|
total | 2total | A name cannot start with a digit. |
student_marks | student marks | Spaces do not belong inside an identifier. |
radius2 | float | float is a keyword. |
grandTotal | grand-total | A hyphen is an operator, not part of the name. |
| Form | Example | Meaning |
|---|---|---|
| Integer constant | 42, 077, 0x2A | Decimal, octal (leading 0) and hexadecimal (0x prefix). 077 is not decimal 77. |
| Floating constant | 3.5, 1.2e3, 2.0f | A fractional or exponential value. 1.2e3 means 1200; f selects float. |
| Character constant | 'A', '\n' | Single quotes describe a character constant; \n is a newline escape. |
| String literal | "BCA" | Double quotes form a character array that includes a terminating null character. It differs from a single character. |
\n means newline, \t horizontal tab, \\ a backslash, and \" a double quote inside a string. For example, printf("Name\tMarks\n"); prints two headings separated by a tab and then starts a new line.
In int score = 10;, score is the identifier for a variable and 10 is a constant value used to initialize it. The variable can later receive another value, for example score = 12;.
LESSON 06
A data type determines the values an object can represent and the operations that apply. A declaration introduces the name and type; a definition reserves storage; initialization supplies an initial value as the object is created. Most simple local declarations below are also definitions.
| Type | Example declaration | Typical use |
|---|---|---|
char | char grade = 'A'; | Character-sized integer storage. sizeof(char) is always 1 C byte; a byte is not guaranteed to be exactly 8 bits. |
int | int count = 4; | Whole numbers such as counts and indices. |
float | float price = 12.5f; | Floating-point values; the f suffix makes the literal a float. |
double | double radius = 3.25; | Floating-point values with at least as much precision as float. |
void | int main(void) | No value/type of result in contexts such as a void-returning function; void in this parameter list means no parameters. |
short and long modify integer types; signed and unsigned select signedness where allowed. long double is another floating type. Do not assume int is always two or four bytes: exact sizes and ranges depend on the implementation. Use sizeof to inspect object sizes, and limits.h / float.h for limits. In later study, you will meet derived types such as arrays and pointers and user-defined structures, unions and enumerations.
#include <stdio.h>
int main(void)
{
int count = 4;
float price = 12.5f;
char grade = 'A';
double radius = 3.25;
printf("Count = %d\n", count);
printf("Price = %.2f\n", price);
printf("Grade = %c\n", grade);
printf("Radius = %.2f\n", radius);
return 0;
}
Count = 4
Price = 12.50
Grade = A
Radius = 3.25
int count; /* declaration and definition */
count = 4; /* assignment after creation */
double rate = 2.5; /* definition with initialization */
int x = 0, y = 0; /* initialize each variable */An uninitialized automatic local variable has an indeterminate value; do not read it before setting it. Objects with static storage duration are zero-initialized if no initializer is supplied. In int x, y = 0;, only y is explicitly initialized.
| Object type | printf format | scanf format |
|---|---|---|
int | %d | %d with int * |
float | %f (promoted to double) | %f with float * |
double | %f | %lf with double * |
char | %c | %c with char *; a leading space skips earlier whitespace |
The input example scanf("%lf", &radius) passes the address of radius so scanf can store the value. Check scanf’s return value: 1 means one successful conversion here. %.2f in printf displays two digits after the decimal point; it does not change the stored value.
#define PI 3.141592653589793
const int MAX_STUDENTS = 60;A #define object-like macro gives a name to replacement text before compilation. It has no declared type or trailing semicolon. A const-qualified object has a type and cannot be modified through that declaration. They are related tools, but are not interchangeable in every C context. Parenthesize compound macro replacements, for example #define LIMIT (10 + 5).
int count = 2.9; discards the fractional part; use a floating type when that part matters.5 / 2 is 2. Use 5.0 / 2 for a floating result.'\0'.LESSON 07
A header supplies declarations, types or macros that your program needs. Standard headers are included with angle brackets, such as #include <stdio.h>. Including a header does not paste the compiled library implementation into your executable; linking resolves needed library definitions.
| Syllabus header | Purpose and examples | Portability |
|---|---|---|
stdio.h | Standard input/output: printf, scanf, getchar, putchar, file operations. | Standard C. |
conio.h | Console facilities in some DOS/Windows toolchains, often getch and clrscr. Names differ across implementations. | Not an ANSI/ISO C header. Usually unavailable in GCC-based online Linux compilers. |
math.h | Mathematics: sqrt, pow, sin, cos, fabs. Trigonometric functions use radians. | Standard C. The syllabus spelling “maths” should be written math.h in C. |
string.h | String/byte operations: strlen, strcmp, strcpy, memcpy. strlen does not count the final null character. | Standard C; destination storage must be large enough for copying. |
ctype.h | Character classification and case conversion: isalpha, isdigit, isspace, toupper, tolower. | Standard C. Arguments must be EOF or a value representable as unsigned char. |
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main(void)
{
char word[] = "BCA";
char letter = 'b';
double value = 9.0;
printf("Word length = %lu\n", (unsigned long)strlen(word));
printf("Uppercase = %c\n", toupper((unsigned char)letter));
printf("Square root = %.1f\n", sqrt(value));
return 0;
}
Word length = 3
Uppercase = B
Square root = 3.0
Some examples use void main(), clrscr() and getch(). For the playground use int main(void), return 0; and the standard input/output library. You do not need to clear the screen or pause execution to see the output. If your course specifically requires Turbo C, treat those console functions as toolchain-specific additions.
LESSON 08
Choose an example, load it into the embedded C compiler, then change the code and run it. Inside the compiler, select I/O before pressing Run. The sample STDIN is loaded with each example; change it to test your own inputs.
Load the compiler when you’re ready to practise.
Edit real C code and see real compiler output.
Compiler provided by OneCompiler. Opening the editor connects to that service; code and input you run are processed there. If the embed is unavailable, open the C compiler in a new tab and paste the example below.
#include <stdio.h>
int main(void)
{
printf("Hello, BCA!\n");
return 0;
}
−8 −2 −11 and 7 7 7. Why does initializing largest to zero fail for an all-negative input?4 followed by 1.5 −2 3 0. The expected sum is 2.50.%.2f to %.1f. Compare display rounding with the stored value.CHECK YOUR UNDERSTANDING
Start with a precise definition. Add the relevant syntax or symbol. Give a small example, then explain its result. For algorithms state input, output and assumptions; dry-run at least one normal case and one boundary case. Label every decision branch in a flowchart. For data types avoid claiming fixed sizes for every compiler.
READ ALONG
E. Balagurusamy, Programming in ANSI C, Eighth Edition, McGraw Hill Education (India) Private Limited. ISBN 9789353165130.
Use your copy for further reading on computing and problem solving, the overview of C, constants, variables and data types. This page is an original, syllabus-aligned study companion; its explanations, flowcharts, questions and programs are newly written. It does not reproduce the textbook’s chapter text or claim page-by-page correspondence.