0% found this document useful (0 votes)
12 views17 pages

Introduction to C Programming Guide

VAriavbles

Uploaded by

janfeb32mar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views17 pages

Introduction to C Programming Guide

VAriavbles

Uploaded by

janfeb32mar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Programming

C Programming

Contents
1 Introduction to C Programming 2
1.1 What is C Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Why Do We Need C Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Problem Solving and Problem Analysis Chart 2


2.1 Problem Solving Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Problem Analysis Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

3 Algorithm, Flowchart, and Pseudocode 3


3.1 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.2 Flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.3 Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

4 Program Structure, Compilation, and Execution 4


4.1 Program Structure (C Program) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Files Used in a C Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

5 Compilation and Execution Process 6

6 Interactive and Script Mode 7

7 Comments, Indentation, and Error Messages 8


7.1 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.2 Indentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

8 Error Messages (Bugs) 9


8.1 Syntax Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
8.2 2. Runtime Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
8.3 3. Logical Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

9 Data Types, Constants, Variables, Keywords 10


9.1 C Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.2 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

10 Operators in C 11
10.1 Operator Table with Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
10.2 Unary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
10.3 Increment and Decrement Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
10.4 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
10.5 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

11 Input/Output Functions 13

12 Built-in Functions 14

13 Compiler vs Assembler 14

1
C Programming

1 Introduction to C Programming
1.1 What is C Programming?
Definition
C is a high-level programming language developed in the early 1970s by Dennis Ritchie at Bell
Labs. It is widely used for system programming, creating operating systems, embedded systems, and
general-purpose applications. C allows you to write programs that are efficient, fast, and portable.

1.2 Why Do We Need C Programming?


➤ Efficiency: C programs are fast and use memory efficiently.
➤ Portability: C code can run on different types of computers with minimal changes.
➤ Foundation Language: Many modern languages like C++, Java, and Python are based on C con-
cepts.

➤ System Programming: Ideal for writing operating systems, compilers, and embedded systems.
➤ Control: Provides low-level access to memory and hardware for detailed control.

2 Problem Solving and Problem Analysis Chart


2.1 Problem Solving Process
Process Steps

Computers excel at solving complex, tedious, and routine problems. To enable a computer to address
a problem, a programmer must devise a solution method and a detailed procedure. The problem-
solving process involves:

✓ Detailed study of the problem.

✓ Formulating a mathematical model.


✓ Identifying input data, output requirements, conditions, and limitations.
✓ Exploring alternative methods of solution.
✓ Selecting the most suitable method.

✓ Preparing a list of procedures and steps to obtain the solution.


✓ Developing an algorithm and flowchart once the solution is identified.
✓ Testing and debugging the solution.
✓ Generating the final output.

2.2 Problem Analysis Chart


A Problem Analysis Chart helps structure the problem by identifying key components:

2
C Programming

Component Description
Input Data provided to the program (e.g., numbers, strings).
Output Expected results or deliverables from the program.
Processing Computations or operations to transform input into
output.

Example

Example (Sum of Two Numbers):


• Input: Two numbers, A and B.

• Processing: Compute C = A + B.
• Output: C (the sum).

3 Algorithm, Flowchart, and Pseudocode


3.1 Algorithm
An algorithm is a finite sequence of precise instructions that, given input values, produces an output and
terminates.
Characteristic Description
Finiteness Terminates after a finite number of steps.
Preciseness Instructions are clear and unambiguous.
Input/Output Accepts a finite number of inputs and produces outputs.

Example

Example (Area of Circle):


1. Read the radius.
2. Calculate area = π × radius × radius.

3. Print the area.

3.2 Flowchart
A flowchart is a diagrammatic representation of an algorithm, illustrating the sequence of operations.

Symbol Meaning Use/Description


Oval Start/Stop Represents the beginning (start) or
termination (stop) of program logic.
Parallelogram Input/Output Indicates information entering or leaving the
system (e.g., reading data or displaying
results).
Rectangle Processing Used for arithmetic operations or logical
computations.
Rhombus Decision Denotes a condition or branch with one entry
and two exit paths (True/False or Yes/No).
Arrows Flow Lines Connect symbols to indicate sequence and
direction of control flow.

3
C Programming

Example

Example (Flowchart for Area of Circle):

Start

Read radius

area = 3.14 * radius * radius

Print area

Stop

3.3 Pseudocode
Pseudocode is a high-level description of an algorithm using natural language and programming constructs,
avoiding language-specific syntax.

Example

Example (Pseudocode for Area of Circle):

BEGIN
READ radius
area = 3.14 * radius * radius
PRINT area
END

4 Program Structure, Compilation, and Execution


4.1 Program Structure (C Program)
A C program is composed of declarations and function definitions. The minimum valid program has a main()
function where execution begins.

4
C Programming

General Syntax

1 Preprocessor Directives
2 Global Declarations
3

4 int main ()
5 {
6 Local Variable Declarations ;
7 Executable Statements ;
8 return 0;
9 }
10

11 User - defined Function Definitions

Explanation of Components
Components

❐ Preprocessor Directives: Instructions starting with # such as #include or #define.


❐ Global Declarations: Variables or function prototypes that can be accessed by all functions.
❐ main() Function: The starting point of program execution.

❐ Local Declarations: Variables declared inside a function, accessible only within it.
❐ Executable Statements: Instructions performing actions such as input/output or calcula-
tions.
❐ User-defined Functions: Additional functions created by the programmer to perform specific
tasks.

Example Program

1 /* Example : Demonstrating program structure */


2

3 # include < stdio .h > // Preprocessor directive


4

5 # define PI 3.14159 // Macro definition


6

7 // Function declaration ( prototype )


8 int add ( int a , int b ) ;
9

10 int main ( void ) { // Entry point


11 int x = 5 , y = 7; // Local variables
12 int sum = add (x , y ) ;
13 printf (" Sum = % d \ n " , sum ) ;
14 return 0;
15 }
16

17 // Function definition
18 int add ( int a , int b ) {
19 return a + b ;
20 }

5
C Programming

4.2 Files Used in a C Program


✎ Source File (.c): Contains the programmer’s code, including main().
✎ Header File (.h): Contains function declarations and macros (e.g., <stdio.h>, <math.h>).
✎ Object File (.o/.obj): Machine code generated by the compiler, not yet executable.

✎ Executable File (.exe / [Link]): Final runnable program created by the linker.

5 Compilation and Execution Process


Steps
1. Preprocessing: Handles macros, includes, removes comments.
2. Compilation: Converts preprocessed code to assembly.

3. Assembly: Converts assembly to object code.


4. Linking: Combines object files and libraries to produce an executable.
5. Loading & Execution: OS loads executable and runs main().

Process Diagram
Compilation Process

+------------+ Preprocess +----------------+ Compile +-----------+


| prog.c | --------------> | preprocessed | -----------> | prog.s |
| (source) | | source | | (assembly) |
+------------+ +----------------+ +-----------+
| Assemble
v
+-----------+
| prog.o |
| (object) |
+-----------+
| Link
v
+-----------+
| prog |
| (executable)|
+-----------+
| Load & Execute
v
[ runtime / main() ]

6
C Programming

6 Interactive and Script Mode


1. Definition
Interactive Mode
In this mode, the computer executes each line of code as soon as you type it and shows the result
immediately. Example: Python interpreter or online C compilers like OnlineGDB (where you type
and click Run to see output quickly).

Script Mode

In this mode, you write the whole program in a file, save it, and then run it. The entire program is
executed together after compilation. Example: Running a C program using gcc on your computer.

2. Example of Interactive Mode (Python)


>>> a = 5
>>> b = 3
>>> sum = a + b
>>> print("Sum =", sum)
Sum = 8

Explanation: Each line is typed and executed immediately. You can see the output right after entering
the command.

3. Example of Interactive Mode (Online C Compiler)


In an online C compiler (like OnlineGDB or Programiz), you type the code below, click Run, and instantly
get the output — you don’t need to type any compile commands.
1 # include < stdio .h >
2 int main () {
3 int a = 5 , b = 3;
4 printf ( " Sum ␣ =% d \ n " , a + b ) ;
5 return 0;
6 }

Output:
Sum = 8

Explanation: Even though C is a compiled language, online compilers make it feel interactive because
they automatically compile and run the program when you click Run.

4. Example of Script Mode (C on Computer)

1 # include < stdio .h >


2 int main () {
3 int a = 5 , b = 3 , sum ;
4 sum = a + b ;
5 printf ( " Sum ␣ = ␣ % d \ n " , sum ) ;
6 return 0;
7 }

7
C Programming

Steps to Run in Script Mode:


1. Save file as sum.c
2. Compile: gcc sum.c -o sum
3. Run: ./sum
Output: Sum = 8

5. Difference Between Interactive and Script Mode


Feature Interactive Mode Script Mode
Execution Line by line Whole program at once
Output Shown immediately After compilation
File Required Not needed Program saved in file
Example Tools Python, Online C Compiler GCC, Code::Blocks

7 Comments, Indentation, and Error Messages


7.1 Comments
Comments

Definition/Purpose: Comments are notes you write in your code to explain what it does. They
are ignored by the compiler or interpreter, so they do not affect how the program runs.
Why use them:

✰ Help you and others understand the code later.


✰ Make debugging easier.
✰ Useful for documenting logic, especially in complex programs.
Example:

// - single line comment


/* */ - Multi line comments

7.2 Indentation
Indentation

Definition/Purpose: Indentation is adding spaces or tabs at the beginning of a line to show its
structure. Some languages (like Python) require it, others (like C/C++) use it for readability.
Why use it:
✱ Makes code easier to read.
✱ Shows which lines belong together in blocks (like inside if, for, while).

✱ Helps prevent logical errors.

Example: Comments and Indentation in Code


Program: Calculate Price of Gold

// Input the weight of gold and calculate total price


#include <stdio.h>

8
C Programming

int main() {
// Declare variables
float weight, price_per_gram, total_price;

// Assign price per gram


price_per_gram = 12000; // As of 10.10.2025

// Ask user to input weight


printf("Enter weight of gold in grams: ");
scanf("%f", &weight);

// Calculate total price


total_price = weight * price_per_gram;

// Display the result


printf("Total price of gold: %.2f\n", total_price);

return 0;
}

8 Error Messages (Bugs)


Definition/Purpose: Errors, or bugs, are problems in code that prevent it from running correctly.

8.1 Syntax Error


Syntax Error

Definition: A mistake in the rules of the programming language. The program cannot compile or
run.
Example:
int x = 10 // Missing semicolon

Error Message: The compiler may say: “expected ’;’ before ’’“

8.2 2. Runtime Error


Runtime Error
Definition: The program compiles but fails during execution.
Example:

int a = 10, b = 0;
int c = a / b; // Division by zero
Error Message: Division by zero or program crash.

9
C Programming

8.3 3. Logical Error


Logical Error

Definition: The program runs but produces incorrect results.


Example:
float area = radius * radius; // Forgot to multiply by 3.14

Error Message: Usually none, output is wrong.

9 Data Types, Constants, Variables, Keywords


9.1 C Tokens
A token is the smallest individual unit in a C program, including Keywords, Identifiers, Constants, Strings,
Special Symbols, and Operators.

9.2 Keywords
Keywords are reserved words (32 in C) with predefined meanings, not usable as variable names.

All 32 Keywords in C

The 32 keywords in ANSI C are: 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.

➊ Example: int, char, float, if, else, return, void.

9.3 Data Types


A data type defines the type of value a variable can hold and its memory allocation.

Data Type Description Size Format Specifier


(bytes)
char Single character. 1 %c
int Whole numbers. 2 or 4 %d or %i
float Decimal numbers (6-digit 4 %f
precision).
double Double-precision decimal 8 %lf
numbers.

9.4 Variables
A variable is a named memory location whose value can change during execution.

• Declaration Format: datatype v1, v2, ...;

• Example:
1 int sum ; // Declaration
2 float pi = 3.14; // Initialization

10
C Programming

9.5 Constants
A constant is a fixed value that cannot change during execution.

■ Numeric Constants: Integers (e.g., 123) or Reals (e.g., 29.85, 1.2e+10).


■ Character Constants:
– Single Character: Enclosed in single quotes (e.g., ’A’, ’3’).
– String: Enclosed in double quotes, ends with \0 (e.g., "Hello").
■ Symbolic Constant: Defined using #define (e.g., #define PI 3.14).

10 Operators in C
Definition
Operators and Operands

Operator: A symbol that instructs the compiler to perform a specific operation.


Operand: The data on which the operator acts.

Need for Operators


Operators allow computation, comparison, logical, and bit-level manipulation in programs.

10.1 Operator Table with Types


Operators Table (with Types)

Symbol Type Name Example


+ Arithmetic Addition a+b
- Arithmetic Subtraction / Unary Minus a - b, -x
* Arithmetic Multiplication a*b
/ Arithmetic Division a/b
% Arithmetic Modulus a%b
++ unary Increment ++i, i++
– unary Decrement –i, i–
= Assignment Simple Assignment x=5
+= Assignment Compound Addition x += 3
-= Assignment Compound Subtraction x -= 2
*= Assignment Compound Multiplication x *= 4
/= Assignment Compound Division x /= 2
%= Assignment Compound Modulus x %= 3
== Relational Equal to a == b
!= Relational Not equal to a != b
! Logical Logical NOT !flag
& Bitwise / Address Bitwise AND / Address-of a & b, &var
— Bitwise Bitwise OR a—b
ˆ Bitwise Bitwise XOR aˆb
˜ Bitwise Bitwise NOT ˜x
« Bitwise Left Shift x«2

11
C Programming

» Bitwise Right Shift x»1


?: Conditional Ternary x? y: z

10.2 Unary Operators


Unary Operators

Unary operators operate on a single operand. Common unary operators include:

• Unary Minus (-): Negates the value. Example: int x = -5;

Unary operators have high precedence and are right-associative.

10.3 Increment and Decrement Operators


Increment and Decrement Operators

Increment (++) and decrement (--) operators add or subtract 1. They can be:

• Prefix (++x / –x): Increments/decrements first, then uses the new value. Example: int
x=5; int y=++x; → y=6, x=6
• Postfix (x++ / x–): Uses current value, then increments/decrements. Example: int x=5;
int y=x++; → y=5, x=6

Commonly used in loops and counters. Precedence is higher than arithmetic operators.

10.4 Bitwise Operators


Bitwise Operators

Bitwise operators perform operations on individual bits:

• AND (&): 1 if both bits 1. Example: 5 & 3 = 1


• OR (—): 1 if any bit 1. Example: 5 | 3 = 7

• XOR (ˆ): 1 if bits differ. Example: 5 ˆ 3 = 6

• NOT (˜
): Inverts bits. Example: ˜5 = -6
• Left Shift («): Shifts bits left. Example: 5 << 1 = 10
• Right Shift (»): Shifts bits right. Example: 5 >> 1 = 2

Used in low-level programming, flags, and optimization.

12
C Programming

10.5 Assignment Operators


Assignment Operators

Assign values to variables. Simple: =, Compound: arithmetic/bitwise.

• Simple Assignment (=): x = 5;


• Compound Assignments:
– += → add assign (x += 3;)
– -= → subtract assign (x -= 2;)
– *= → multiply assign (x *= 4;)
– /= → divide assign (x /= 2;)
– %= → modulus assign (x %= 3;)
– Bitwise: &=, |=, ˆ=, <<=, >>= Example: x &= 1;

Assignment is right-associative and has low precedence.

Sample Program Demonstrating Operators

1 # include < stdio .h >


2

3 int main ( void ) {


4 int a = 10 , b = 3;
5 int add = a + b ;
6 int sub = a - b ;
7 int mul = a * b ;
8 int divv = a / b ;
9 int mod = a % b ;
10

11 a ++; ++ b ;
12 int eq = ( a == b ) ;
13 int gt = ( a > b ) ;
14 int logical = ( a > 0 && b > 0) ;
15 int bit_and = a & b ;
16 int left = a << 2;
17 int ternary = ( a > b ) ? a : b ;
18

19 printf ( " add =% d ␣ sub =% d ␣ mul =% d ␣ div =% d ␣ mod =% d \ n " , add , sub , mul , divv , mod ) ;
20 printf ( " eq =% d ␣ gt =% d ␣ logical =% d ␣ bit_and =% d ␣ left =% d ␣ ternary =% d \ n " ,
21 eq , gt , logical , bit_and , left , ternary ) ;
22 return 0;
23 }

11 Input/Output Functions
C I/O operations use function calls from the standard I/O library (<stdio.h>).

13
C Programming

Type Function Description Example


Unformatted getchar(), Reads single character or string. char ch =
Input gets() getchar();
Unformatted putchar(), Displays single character or putchar(ch);
Output puts() string.
Formatted Input scanf() Reads data with format scanf("%d",
specifiers (requires &). &num);
Formatted printf() Displays formatted data. printf("Value:
Output %d", num);

12 Built-in Functions
Built-in functions are predefined in header files and perform specific tasks.

• Usage: Include the appropriate header file (e.g., #include <math.h>).

Header File Category Example Function


<stdio.h> Standard I/O printf(), scanf()
<math.h> Mathematical sqrt(d), pow(d1, d2)
<ctype.h> Character tolower(c)
<string.h> String strlen(s)

Example

Example (Math Function):


1 # include < math .h >
2 int main () {
3 float num = 12.00 , root ;
4 root = sqrt ( num ) ; // Built - in function
5 printf ( " Square ␣ root ␣ of ␣ %.2 f ␣ = ␣ %.2 f \ n " , num , root ) ;
6 return 0;
7 }

13 Compiler vs Assembler
1. Definitions
Compiler

A compiler translates a program written in a high-level language (like C) into a machine-


understandable form.

Assembler

An assembler converts assembly language instructions into machine code (binary).In modern
compilers (like gcc), this step happens automatically inside the compilation process.

2. Simple Example
C Source Code:

14
C Programming

1 # include < stdio .h >


2

3 int main () {
4 int a = 5 , b = 3 , c ;
5 c = a + b;
6 printf (" Sum = % d \ n " , c ) ;
7 return 0;
8 }

When you compile this using gcc prog.c -o prog, the compiler performs several steps automatically.

3. What Happens Internally


1. Preprocessing: The preprocessor expands header files (like stdio.h) and macros. Output: tempo-
rary expanded source file.

2. Compilation: The compiler converts the preprocessed C code into assembly language. Output:
temporary assembly file (e.g., prog.s).
3. Assembly: The assembler converts assembly code into object code (machine code). Output: prog.o
file.

4. Linking: The linker combines the object file with library files (like stdio) to create the final exe-
cutable file. Output: [Link] or the name you specify with -o.

4. Example Commands and File Outputs


# Compile a C program (all steps done automatically)
gcc prog.c -o prog

# Internal process (performed by gcc):


prog.c --> (C source)
prog.s --> (assembly - temporary)
prog.o --> (object code)
prog --> (final executable)

6. Summary Table
Stage Language / Content Example File
1. Source Code Human-readable (C language) prog.c
2. Assembly Code CPU instructions (text form) prog.s (temporary)
3. Object Code Machine instructions (binary) prog.o
4. Executable File Ready-to-run program prog / [Link]

7. Visual Representation
C Source Code (.c)
|
| gcc compiler (includes assembler internally)
v
Object Code (.o)
|
| Linking
v
Executable File (.exe / [Link])

15
C Programming

8. In Simple Words
➢ Compiler: Converts C code to machine code (automatically calls assembler internally).
➢ Assembler: Converts assembly to machine code (used inside the compiler process).
➢ When we use gcc, we don’t have to run the assembler manually.

16

You might also like