BCAMCABSc ITB.Tech CSE

C Programming — syllabus, exam questions and lab programs

Your scheme may call it Introduction to Programming — C.

C is the first language nearly every computer degree in Punjab starts with, and it is a strange choice to start with — it hides nothing, forgives nothing, and gives you a segmentation fault instead of an error message. That is also the reason it is still there. A student who understands what a pointer is has understood what a variable is, and everything after this paper becomes easier.

The paper itself divides cleanly. The first half — data types, operators, control flow, functions, arrays — is straightforward and almost everyone passes it. The second half is pointers, strings as character arrays, structures, dynamic memory and file handling, and that is where the marks go and where the backlog comes from. If you are short of time, spend it there.

One warning about how this is usually taught: a lot of classes teach C by making you memorise programs. That gets you through the practical and leaves you unable to write anything you have not already seen. Write the programs badly first, then fix them. A program you debugged is worth ten you copied.

We teach this

C Programming is one of the papers we teach at WebPrims

This is not only a page about C Programming. It is a subject we teach in a classroom on Majitha Road — tuition for C Programming, if that is the word you were searching for — and a good share of every batch is college students taking it alongside their own semester. Bring your scheme and we cover what is on it.

What that means in practice: the whole syllabus gets covered rather than the parts that make a good demo, you write code on a machine instead of copying it into a file, and the lab work gets done here rather than the night before submission.

What we will not say is that this guarantees you marks or a job. We do not run placements and we do not promise results. Come and sit in a class, decide for yourself.

₹4,500 / month— one rate, any subjectMon–Sat, batches at 11, 1, 3 and 5Majitha Road, Amritsar

The syllabus, unit by unit

What each unit actually contains, and whether it is there because it matters or because it is on the paper. Unit order and numbering vary between GNDU, PTU and your batch’s scheme — check your own before you plan a revision week.

1

Problem solving, algorithms and flowcharts

Steps of problem solving, writing an algorithm, drawing a flowchart, the standard flowchart symbols, and dry-running a flowchart on paper.

Genuinely useful, and the cheapest marks in the paper. Draw the flowchart with a ruler and the examiner has nothing to take off.

2

C fundamentals — data types, operators, input and output

The structure of a C program, keywords, identifiers, int/float/char/double, the modifiers short, long, signed and unsigned, type conversion, all the operator families, and printf and scanf with their format specifiers.

Learn the format specifiers properly. Most first-year runtime bugs are %d against a float, or a scanf missing its ampersand.

3

Control structures

if, if-else, nested if, switch-case, while, do-while, for, and the break, continue and goto statements.

Every language you meet afterwards has these. The exam asks you to trace loops by hand, so practise on paper, not only on a screen.

4

Functions, storage classes and recursion

Declaration, definition, call by value, return types, scope, the storage classes auto, register, static and extern, and recursion with factorial, Fibonacci and the Towers of Hanoi.

Recursion is worth real time. Once you can see a call stack in your head, data structures next year stops being frightening.

5

Arrays and strings

One and two dimensional arrays, passing arrays to functions, strings as character arrays terminated by a null, and the string.h functions strlen, strcpy, strcat and strcmp.

Write your own versions of strlen and strcpy before you use the library ones. It is a standard exam question and it teaches you what a string really is.

6

Pointers

Address and dereference operators, pointer arithmetic, pointers and arrays, arrays of pointers, pointer to pointer, and passing pointers to functions to get call by reference.

This is the unit. Everything difficult later — linked lists, trees, dynamic memory — is this unit applied. If you learn one thing properly this semester, learn this.

7

Structures, unions and dynamic memory

Defining a structure, array of structures, structure inside a structure, passing structures to functions, pointers to structures with the arrow operator, unions, and malloc, calloc, realloc and free.

Structures plus pointers plus malloc is exactly what a linked list is. Do this properly and next year's paper is half done.

8

File handling

File pointers, fopen modes, fclose, fgetc, fputc, fgets, fputs, fscanf, fprintf, fread, fwrite and fseek.

Comes up as a full question most years, and nobody revises it because it is the last unit. That makes it cheap marks.

What is worth keeping after the exam

Revise all of it — the marks are the marks. But it is worth knowing which half of this paper you will still be using in two years, and which half exists because it is on the paper.

Stays with you

  • +Pointers and memory — everything you ever do with a data structure, in any language, rests on this
  • +Reading a call stack, which is how you will debug for the rest of your career
  • +Knowing roughly what a line of code costs, which people who started with Python rarely learn
  • +File I/O concepts, which are the same in every language with different spelling

For the exam, and then gone

  • −goto — it is in the syllabus and it is in nobody's code
  • −The register storage class, which modern compilers ignore
  • −Reciting the full operator precedence table; in real code you use brackets
  • −Towers of Hanoi beyond understanding the recursion

Questions that come up year after year

Not a guess paper, and not a promise about what will be set. These are the questions this subject keeps asking because they are the ones that test whether you understood it.

  1. 01Write a program to reverse a string without using any library function
  2. 02Explain call by value and call by reference with an example (swap two numbers)
  3. 03Difference between an array and a pointer
  4. 04Write a program to find the largest element in a two-dimensional array
  5. 05Explain malloc, calloc, realloc and free with syntax
  6. 06Write a program to copy the contents of one file into another
  7. 07Recursion versus iteration, with factorial as the example
  8. 08Structure versus union, with a memory diagram

What students get wrong

From teaching this paper, not from a list somewhere. Each of these costs marks every year.

Wrong — Writing scanf("%d", n) and wondering why the program crashes.

Right — scanf needs the address, so it is scanf("%d", &n). The one exception is a string read into a char array, because the array name is already an address.

Wrong — Using == to compare two strings.

Right — That compares two addresses, and they are never equal. Use strcmp, which returns 0 when the strings match — note that 0 means equal, which reads backwards the first few times.

Wrong — Declaring char name[5] and storing "Rahul" in it.

Right — Five characters need six bytes, because of the terminating null. This is the single most common cause of a program that works on one machine and corrupts memory on another.

Wrong — Returning the address of a local variable from a function.

Right — That variable dies when the function returns. Either return the value, or allocate with malloc and let the caller free it.

Wrong — Learning programs by heart for the practical exam.

Right — Examiners change one line — read from a file instead of the keyboard, or descending instead of ascending — and a memorised program collapses. Write it from the logic each time.

Lab file programs

These compile and run as written — type them in, break them, and fix them. Copying a program into a file you never ran is how a practical viva goes badly.

Reverse a string without a library function

Asked in practicals every year. The point is that you know a string is an array and where it ends.

c
#include <stdio.h>

int main(void) {
    char s[100];
    int i, n = 0;
    char t;

    printf("Enter a string: ");
    scanf("%99[^\n]", s);

    /* Find the end ourselves instead of calling strlen. */
    while (s[n] != '\0') {
        n++;
    }

    /* Swap from both ends, meeting in the middle. */
    for (i = 0; i < n / 2; i++) {
        t = s[i];
        s[i] = s[n - 1 - i];
        s[n - 1 - i] = t;
    }

    printf("Reversed: %s\n", s);
    return 0;
}

Swap two numbers using call by reference

The standard way of showing you understand pointers. Write the call-by-value version beside it and show it does not work.

c
#include <stdio.h>

void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void) {
    int x, y;

    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);

    swap(&x, &y);     /* pass the addresses, not the values */

    printf("After swap: x = %d, y = %d\n", x, y);
    return 0;
}

Copy one file into another

The file-handling practical. Handles the file-not-found case, which is where marks are usually lost.

c
#include <stdio.h>

int main(void) {
    FILE *in, *out;
    int ch;

    in = fopen("source.txt", "r");
    if (in == NULL) {
        printf("Cannot open source.txt\n");
        return 1;
    }

    out = fopen("target.txt", "w");
    if (out == NULL) {
        printf("Cannot create target.txt\n");
        fclose(in);
        return 1;
    }

    while ((ch = fgetc(in)) != EOF) {
        fputc(ch, out);
    }

    fclose(in);
    fclose(out);
    printf("Copied.\n");
    return 0;
}

Long questions, answered the way they are marked

Not model answers to reproduce. What the examiner is checking for, and where the marks actually sit in each one.

What is a pointer? Explain with an example.

A pointer is a variable that holds the address of another variable rather than a value. Declare it with the type it points at — int *p — take an address with &, and read the value at that address with *. The marks are in the example and the diagram: draw two boxes, one holding 10 at address 2000, the other holding 2000. An answer with a correct diagram and a three-line program gets full marks; an answer that only defines the term gets half.

Differentiate between call by value and call by reference.

Call by value copies the argument, so the function works on its own copy and the caller's variable is untouched. Call by reference passes the address, so the function reaches the original. C is always call by value — passing a pointer is still passing a copy of an address, which is how it achieves the effect. Say that last sentence; it is the part that separates a full answer from an average one. Use swap as the example, both versions.

Explain the difference between structure and union.

Both group different data types under one name. A structure gives every member its own memory, so its size is roughly the sum of its members. A union gives all members the same memory, so its size is that of its largest member and only one member holds a valid value at a time. Draw the memory layout for both with the same three members — the diagram is where the marks are, and it makes the point faster than a paragraph.

What is dynamic memory allocation? Explain malloc, calloc, realloc and free.

Memory taken from the heap while the program runs, when you do not know the size at compile time. malloc(n) gives n bytes, uninitialised. calloc(count, size) gives the same but zeroed. realloc(ptr, n) resizes an existing block and may move it, so always assign its return value back. free(ptr) returns the block. Two marks people miss: malloc returns void* so it is cast to the target type, and every malloc must have a matching free or the program leaks.

Difference between — the ones that get asked

Every one of these is a five-mark question somewhere on this syllabus, and the marks are rarely in the first line. They are in the consequences underneath it.

Structure vs Class

In C++ there is exactly one technical difference: members of a struct are public by default and members of a class are private by default. In C, a struct holds data and has no methods at all.

 structclass
Default accesspublicprivate
Default inheritancepublicprivate
Member functionsAllowed in C++. Not in C.Allowed.
ConventionPlain data grouped together, no invariants to protect.Data plus behaviour, with an interface worth hiding.
In CData only. No access specifiers, no functions, no inheritance.Does not exist in C.

Where people lose the marks

Be specific about which language the question means. In C++ the difference is two defaults and nothing else — a struct can have constructors, methods and inheritance. In C, a struct is a way of laying out bytes and the comparison with a class does not apply.

C vs C++

C++ began as C with classes and kept almost all of C while adding object orientation, templates and a standard library. Most C programs compile as C++; the reverse is not true.

 CC++
ParadigmProcedural.Procedural, object oriented and generic.
Classes and objectsNone.Yes, with inheritance and polymorphism.
Memorymalloc and free.new and delete, plus smart pointers and RAII.
Function overloadingNot supported.Supported.
ExceptionsNo — return codes and errno.try, catch, throw.
Standard librarySmall — stdio, stdlib, string.Large — STL containers, algorithms, streams.

Where people lose the marks

Learning C first is not wasted effort even if you end up writing C++. Pointers, memory and the shape of a program are clearer in C precisely because nothing is hidden, and every one of those ideas carries straight over.

cin vs cout

cin reads input, cout writes output. The arrows point the way the data flows.

 cincout
DirectionInput — from keyboard into your variable.Output — from your variable to the screen.
Operator>> (extraction), pointing into the variable.<< (insertion), pointing into the stream.
Classistreamostream
Headeriostreamiostream

Where people lose the marks

The arrow direction is the memory aid, and it is reliable: cin >> x moves data into x, cout << x moves x out to the screen. Students who guess the operator rather than reading the arrows get it wrong about half the time.

Multiple choice, with the reason

Universities set an objective section and campus written rounds are almost nothing else. The answer is marked, and every one of them says why — an answer key you can only memorise is worth nothing in a viva.

  1. 01

    What is the output of: printf("%d", sizeof(char));

    • a1
    • b2
    • c4
    • dDepends on the compiler

    Why — The C standard fixes sizeof(char) at exactly 1 byte, always. Every other type's size can vary between compilers; char cannot, because the byte is defined as whatever a char occupies.

  2. 02

    Which of these is NOT a valid storage class in C?

    • aauto
    • bregister
    • cvolatile
    • dextern

    Why — volatile is a type qualifier, not a storage class. The four storage classes are auto, register, static and extern. This distinction is asked constantly because the two lists look alike.

  3. 03

    What does the expression a[i] actually mean to the compiler?

    • a*(a + i)
    • b*(a) + i
    • ca + *(i)
    • d&(a + i)

    Why — Array indexing is pointer arithmetic with different punctuation. Because addition commutes, i[a] compiles and means the same thing — which is the follow-up question examiners enjoy.

  4. 04

    If a function needs to change a variable belonging to its caller, it must receive:

    • aThe variable
    • bA copy of the variable
    • cThe address of the variable
    • dA global version of it

    Why — C passes everything by value, so the function gets a copy and changing the copy changes nothing. Passing the address lets it reach the original through the pointer.

  5. 05

    What does malloc return when it cannot allocate the memory asked for?

    • a0
    • bNULL
    • c-1
    • dThe program crashes

    Why — It returns NULL, which is why every malloc should be followed by a check. Writing through an unchecked NULL pointer is the most common cause of a segmentation fault in first-year code.

  6. 06

    How much memory does char name[5] reserve, and how long a string can it hold?

    • a5 bytes, 5 characters
    • b5 bytes, 4 characters
    • c6 bytes, 5 characters
    • d4 bytes, 4 characters

    Why — Five bytes, but one of them must hold the terminating null, so only four characters fit. Storing five characters writes past the end of the array.

  7. 07

    Which statement about a union is true?

    • aIts size is the sum of its members
    • bAll members can hold valid values at once
    • cIts size is that of its largest member
    • dIt cannot contain a pointer

    Why — All members share one block of memory, so the union is as large as its largest member and only the member written last holds a meaningful value.

  8. 08

    What is the value of i after: int i = 5; i = i++ + ++i;

    • a11
    • b12
    • c13
    • dUndefined behaviour

    Why — i is modified twice between sequence points, which the standard leaves undefined. Different compilers print different numbers and all of them are correct. The examiner is testing whether you know that, not whether you can guess the number.

Viva questions, and what a good answer sounds like

GNDU’s own scheme says the viva runs one-to-one beside the practical exam, about the code you are writing at that moment. These are the questions that get asked, and what the examiner is listening for in the reply.

“Why does scanf need an ampersand but printf does not?”

printf only reads the value, so a copy is enough. scanf has to write into your variable, so it needs the address. The exception is a string into a char array, where the array name is already an address.

“Your program compiled. Why did it still crash?”

Compilation checks grammar, not meaning. A segmentation fault is a run-time event — dereferencing a NULL or uninitialised pointer, writing past the end of an array, or using memory after free.

“What is the difference between a declaration and a definition?”

A declaration tells the compiler a name exists and what type it is. A definition also allocates memory for it. extern int x; declares; int x; defines.

“Can a function return a pointer to a local variable?”

It can be written, and it is a bug. The local dies when the function returns, so the caller holds the address of memory that is no longer valid. Return a value, or allocate with malloc and let the caller free it.

“What happens if you free the same pointer twice?”

Undefined behaviour, and in practice a crash or silent heap corruption. Setting the pointer to NULL after freeing it makes the second free harmless, because free(NULL) is defined to do nothing.

“Show me where your program would break if I gave it a longer input.”

The honest answer names the fixed-size array and the scanf that fills it. If you used %s with no width, any input longer than the array overflows it. %99s on a char[100] is the fix, and knowing that is what the examiner is checking.

Past the syllabus

Your paper stops somewhere, and a job interview does not. If you want the version of this subject that goes further than the scheme asks for, there is a full course for it.

CallWhatsAppFree demo