Home / Notes / Class 11 / Computer Science / Programming in C

Programming in C: Class 11 Computer Science

Written by Usman Tariq (Computer Science)

Structure of a C program, data types, variables and constants, operators, input and output with printf and scanf, if and switch statements, loops, and simple programs with common compile errors.

Key points

C is a high-level, general-purpose language developed by Dennis Ritchie in the early 1970s. It is fast, close to the hardware and is the base of many other languages. A program written in C must be compiled into machine code before it runs.

Structure of a simple C program:

  • #include <stdio.h> adds the standard input and output library.
  • int main() is the function where execution starts.
  • Statements go inside braces { } and each ends with a semicolon.
  • return 0; tells the system the program ended normally.
  • Comments are written as // for one line or /* ... */ for several lines.

A first program: #include <stdio.h> then int main() { printf("Hello\n"); return 0; }. The \n is a newline escape sequence. Other common ones are \t for a tab and \\ for a backslash.

Basic data types:

  • int: whole numbers, usually 4 bytes, format code %d.
  • float: decimal numbers with about 6 digits of accuracy, 4 bytes, format %f.
  • double: decimal numbers with more accuracy, 8 bytes, format %lf for input and %f for output.
  • char: a single character in single quotes such as 'A', 1 byte, format %c.

A variable is a named memory location and must be declared before use, for example int age; or float price = 99.5;. Names may have letters, digits and underscore, must not start with a digit, cannot be a keyword such as int or while, and are case sensitive. A constant does not change and is made with const or #define PI 3.14.

Operators in C:

  • Arithmetic: + - * / and % (remainder, integers only).
  • Relational: < > <= >= == !=, giving 1 for true and 0 for false.
  • Logical: && (and), || (or), ! (not).
  • Assignment: = and shortcuts such as += and -=.
  • Increment and decrement: ++ and --.

Remember that = assigns a value while == compares two values. Dividing two integers gives an integer, so 7 / 2 is 3, not 3.5. To get 3.5 use 7 / 2.0. Precedence puts * / % before + −, and brackets override it.

Input uses scanf and output uses printf. For example scanf("%d", &n); reads an integer into n. The & gives the address of the variable and must be used for numbers and characters. printf("Sum = %d", s); prints text with the value of s.

The if statement runs code only when a condition is true. if-else gives two paths and else if gives more. The switch statement picks among fixed values of an int or char, with case labels, break to leave the switch, and default for no match.

Loops repeat code. for (i = 1; i <= 5; i++) has initialisation, condition and update in one line. while (condition) tests before each pass. do { } while (condition); runs once first and tests after. break leaves a loop and continue skips to the next pass.

Example, sum of 1 to n: int n, i, s = 0; scanf("%d", &n); for (i = 1; i <= n; i++) s = s + i; printf("%d", s); For n = 5 this prints 15.

Errors are of three kinds. Syntax errors break the language rules, such as a missing semicolon, and the compiler reports them. Runtime errors happen while running, such as division by zero. Logical errors let the program run but give wrong output, for example using + instead of *.

Study tip: Write programs on paper neatly with correct braces and semicolons, and always include the header, main and return 0. Trace output questions step by step with a table of variable values. Learn format codes: %d, %f, %c.

Definitions and flashcards

Say the meaning first, then open the card to check.

Compiler

A program that translates source code into machine code.

Variable

A named memory location that stores a value.

Data type

The kind of value a variable can hold, such as int or char.

Operator

A symbol that performs an operation on values.

Escape sequence

A backslash code such as \n that stands for a special character.

Loop

A statement that repeats a block of code.

Syntax error

A mistake against the rules of the language.

Keyword

A reserved word with a fixed meaning in C.

Header file

A file such as stdio.h that has ready declarations for library functions.

Formula sheet

NameFormulaWhat it means
Area of circlearea = 3.14159 * r * r;C statement with float variables
Average of threeavg = (a + b + c) / 3.0;The .0 avoids integer division
Even testn % 2 == 0True when n is even
Swap using tempt = a; a = b; b = t;Exchanges two values

Short questions with model answers

These are the kind of questions asked for 2, 3 and 5 marks. Try each one before opening the answer.

What is the use of #include <stdio.h>? (2 marks)

It is a preprocessor directive that adds the standard input and output header file to the program. This file declares functions such as printf and scanf, which are needed for output and input.

Differentiate between = and ==. (2 marks)

The = operator assigns the value on its right to the variable on its left, as in x = 5. The == operator compares two values and gives 1 if they are equal, otherwise 0, as in x == 5. Using = inside an if condition by mistake is a common error.

Write the difference between while and do-while loops. (3 marks)

A while loop tests its condition before running the body, so the body may never run. A do-while loop runs the body first and tests afterwards, so it always runs at least once. The do-while ends with a semicolon.

Name the four basic data types of C with an example of each. (3 marks)

int stores whole numbers such as 25. float stores decimal numbers such as 3.5. double stores decimals with higher accuracy such as 3.14159265. char stores one character such as 'Z'. Each takes a fixed amount of memory.

Write a C program that reads a number and prints whether it is positive, negative or zero. (5 marks)

#include <stdio.h> int main() { int n; scanf("%d", &n); if (n > 0) printf("Positive"); else if (n < 0) printf("Negative"); else printf("Zero"); return 0; } The program reads n, then an if-else-if ladder tests the three cases in turn and prints the matching message.

What are syntax, runtime and logical errors? (3 marks)

A syntax error breaks the rules of C, for example a missing semicolon, and the compiler stops. A runtime error appears while the program runs, for example dividing by zero. A logical error does not stop the program, but the result is wrong because the logic is wrong, such as using the wrong formula.

Numericals with worked steps

What does this print: int a = 7, b = 2; printf("%d %d", a / b, a % b);
  1. Both are integers, so 7 / 2 is integer division: 3
  2. 7 % 2 is the remainder of 7 ÷ 2: 1

Answer: 3 1

How many times does the loop run: for (i = 1; i <= 10; i += 3)? Give the values of i.
  1. i = 1: true, run
  2. i = 4: true, run
  3. i = 7: true, run
  4. i = 10: true, run
  5. i = 13: false, stop

Answer: 4 times, with i = 1, 4, 7, 10

Find the value of x after: int x = 5; x += 3; x = x * 2; x--;
  1. x += 3 makes x = 8
  2. x = x * 2 makes x = 16
  3. x-- makes x = 15

Answer: x = 15

Common mistakes

  • Forgetting the semicolon at the end of a statement.
  • Leaving out & in scanf for int, float and char variables.
  • Writing 7 / 2 and expecting 3.5. Integer division gives 3.
  • Using = instead of == in a condition.
  • Forgetting break in a switch, so execution falls through to the next case.

Practise this chapter

Practice questions and timed test Printable worksheet

Previous: Algorithms and flowcharts Next: Operating systems