I SEMESTER · C PROGRAMMING · UNIT 01

From problem
to C program.

Understand the logic. Learn the language.
Run your first programs.

Complete Unit 1 syllabus3 algorithm tracers7 runnable examples6 self-check questions

LESSON 01

Think before you write code.

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.

01

Understand

Identify the inputs, required outputs, constraints and exceptional cases.

02

Plan

Choose a method. Write an algorithm and draw its flowchart.

03

Build

Translate the plan into C, compile it, and fix reported errors.

04

Check

Test normal, boundary and invalid inputs. Compare actual and expected output.

Work backwards from the 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.

What makes a good algorithm?

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

Make the logic visible.

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.

Start / Stop

Terminator

An oval or rounded rectangle marks entry or exit.

Calculation

Process

A rectangle represents an assignment or calculation.

Read / Print

Input / output

A parallelogram represents accepting or displaying data.

True?

Decision

A diamond tests a condition. Label its branches Yes/No or True/False.

A

Connector

A labelled circle links separated parts of a large chart.

Flow line

An arrow shows which operation happens next.

Drawing rules

  • Use a clear entry and explicit exit; place the main path from top to bottom where practical.
  • Write a short action inside each symbol. Put calculations in process boxes, not decision diamonds.
  • Give every decision its possible outgoing paths. Make repetition return to a condition that can eventually become false.
  • Use connectors to avoid confusing crossings. Dry-run the finished chart with sample inputs.

FOLLOW THE VALUES

Three syllabus examples

Area of a circle

A = πr². Use r ≥ 0 and return the area in square units.

Algorithm

  1. Start.
  2. Read the radius r.
  3. Calculate area = π × r × r.
  4. Display area.
  5. Stop.

Input: 3 → area: 28.27 (rounded to two decimal places).

Press Next step to follow the algorithm.

circle algorithm flowchartStartRead radius rarea = PI × r × rPrint areaStop
Blue marks the current step. This visual tracer follows the fixed algorithm; use the C playground to compile and run editable code.
See the C program
Area of a circlemain.c
#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;
}
EXPECTED OUTPUTArea = 28.27

Try this program

“Sum N numbers” has two common meanings

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.

Run the natural-number version

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

Meet C.

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.

1960s

BCPL → B

Earlier languages influenced C’s syntax and design.

1970s

C & Unix

C combined types with low-level operations useful for systems programming.

1989 / 1990

ANSI / ISO C

ANSI standardized C in 1989; ISO adopted it in 1990.

Features and what they mean

FeaturePractical meaning
Structured, procedural styleUse functions and sequence, selection and repetition to organize a solution.
Compiled executionA toolchain translates source code into an executable program.
PortabilityStandard C can be recompiled on many platforms. Sizes, libraries and compiler extensions can still differ.
Rich operationsArithmetic, comparisons, bit operations, arrays, pointers and user-defined structures support many tasks.
Standard libraryHeaders declare facilities for input/output, strings, mathematics and other common work.
Low-level controlPointers 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

Read your first C program.

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.

Hello, BCAmain.c
#include <stdio.h>

int main(void)
{
    printf("Hello, BCA!\n");
    return 0;
}
EXPECTED OUTPUTHello, BCA!

Try this program
PartWhat 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.

Create, compile, execute

Write main.cPreprocessCompileAssembleLinkRun
  1. Use a plain-text editor to save the source with a .c extension.
  2. The preprocessor handles directives such as #include and #define.
  3. The compiler translates the source and diagnoses problems. The assembler produces object code in a typical native toolchain.
  4. The linker combines object code and needed library code into an executable.
  5. Run the executable, supply any input, and inspect the output.

With GCC on your own computer

gcc -std=c90 -Wall -Wextra main.c -o main
# Linux / macOS: ./main
# Windows terminal: .\main.exe

These 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.

Three kinds of failure

KindExampleHow to investigate
Compile-time errorA missing semicolon or an undeclared identifier.Read the first diagnostic and check that line and the preceding line.
Execution / runtime problemDivision 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 errorUsing 2 × π × r when the requirement is area.Compare with expected results; trace variables and revisit the algorithm.

LESSON 05

Characters become tokens.

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;.

Keywords

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.

autobreakcasecharconstcontinuedefaultdodoubleelseenumexternfloatforgotoifintlongregisterreturnshortsignedsizeofstaticstructswitchtypedefunionunsignedvoidvolatilewhile

Identifiers

An 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 exampleInvalid exampleReason
total2totalA name cannot start with a digit.
student_marksstudent marksSpaces do not belong inside an identifier.
radius2floatfloat is a keyword.
grandTotalgrand-totalA hyphen is an operator, not part of the name.

Constants and strings

FormExampleMeaning
Integer constant42, 077, 0x2ADecimal, octal (leading 0) and hexadecimal (0x prefix). 077 is not decimal 77.
Floating constant3.5, 1.2e3, 2.0fA 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.

Useful escape sequences

\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.

Variable versus value

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

Choose a type, then a name.

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.

TypeExample declarationTypical use
charchar grade = 'A';Character-sized integer storage. sizeof(char) is always 1 C byte; a byte is not guaranteed to be exactly 8 bits.
intint count = 4;Whole numbers such as counts and indices.
floatfloat price = 12.5f;Floating-point values; the f suffix makes the literal a float.
doubledouble radius = 3.25;Floating-point values with at least as much precision as float.
voidint 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.

Variables and data typesmain.c
#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;
}
EXPECTED OUTPUTCount = 4 Price = 12.50 Grade = A Radius = 3.25

Try this program

Declaration, initialization and assignment

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.

Match input and output formats

Object typeprintf formatscanf 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.

Symbolic constants

#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).

Common traps

  • Writing int count = 2.9; discards the fractional part; use a floating type when that part matters.
  • In integer arithmetic 5 / 2 is 2. Use 5.0 / 2 for a floating result.
  • C has no built-in string type. A string is commonly stored in an array of char with a terminating '\0'.
  • Do not use a format specifier that disagrees with the value or pointer type.

LESSON 07

Know your library headers.

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 headerPurpose and examplesPortability
stdio.hStandard input/output: printf, scanf, getchar, putchar, file operations.Standard C.
conio.hConsole 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.hMathematics: sqrt, pow, sin, cos, fabs. Trigonometric functions use radians.Standard C. The syllabus spelling “maths” should be written math.h in C.
string.hString/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.hCharacter classification and case conversion: isalpha, isdigit, isspace, toupper, tolower.Standard C. Arguments must be EOF or a value representable as unsigned char.
Standard library headersmain.c
#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;
}
EXPECTED OUTPUTWord length = 3 Uppercase = B Square root = 3.0

Try this program

Old classroom examples and modern compilers

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

Edit it. Run it. Understand it.

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.

Sample input (STDIN)

No input needed.

Expected output

Hello, BCA!

Load the compiler when you’re ready to practise.

Your C workspace

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.

View / copy the selected source
#include <stdio.h>

int main(void)
{
    printf("Hello, BCA!\n");
    return 0;
}

Try these experiments

  • Circle: try radius 0, 3.5 and −1. Explain each result.
  • Largest: try −8 −2 −11 and 7 7 7. Why does initializing largest to zero fail for an all-negative input?
  • Sum: try 4 followed by 1.5 −2 3 0. The expected sum is 2.50.
  • Hello: remove the semicolon after printf. Run it, read the compiler diagnostic, then repair the code.
  • Types: change the displayed precision from %.2f to %.1f. Compare display rounding with the stored value.

CHECK YOUR UNDERSTANDING

Finish with a self-check.

1. Which symbol represents a flowchart decision?
2. Which is a valid variable name?
3. What is initialized in int a, b = 0; ?
4. Which header is not part of ANSI/ISO C?
5. What scanf format reads into a double object?
6. Which problem does a successful compilation still not rule out?

Written exam practice

  1. Define an algorithm. Explain its characteristics and distinguish it from a program.
  2. Draw the standard flowchart symbols and explain their purposes.
  3. Write an algorithm and draw a flowchart for circle area, largest of three numbers, and summing N values.
  4. Describe the history and features of C, and explain the sections of a simple C program.
  5. Explain the translation steps from source file to executable and distinguish compile-time, runtime and logic errors.
  6. Define a token. Explain keywords, identifiers, constants, variables and string literals with examples.
  7. Explain declaration, initialization, symbolic constants and the basic data types.
  8. State the uses of stdio.h, conio.h, math.h, string.h and ctype.h, and identify the portability issue.
What a complete answer should include

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

Your textbook companion.

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.

Back to the C Programming guide