Docsity

MODULE 1 C PROGRAMMING (2024 SCHEME KTU), Summaries of C programming

Toggle sidebar
bg1
INTRODUCTION TO C
C is one of the popular general purpose programming languages. C
language has been designed and developed by Dennies Ritchie at Bell
Laboratories, USA in 1972. C is widely used for "system programming",
including implementing operating systems and embedded system
applications (UNIX, Linux, Windows, iOS)
Steps in Learning C Language
Learning C programming is done step by step, starting from basic elements and moving
towards writing complete programs.
1. Alphabets, Digits, and Special Symbols
C language is made up of basic characters such as alphabets (Aโ€“Z, aโ€“z), digits (0โ€“9), and
special symbols like +, -, {, }, ;, etc. These are used to form words, expressions, and statements
in a program.
2. Constants, Variables, and Keywords
These are the basic building blocks of C programming.
Constants are ๏ฌxed values that do not change during program execution (e.g., 10, 3.5, 'A').
Variables are names given to memory locations used to store data, and their values can
change (e.g., int x = 5;).
Keywords are reserved words in C with special meanings, such as int, ๏ฌ‚oat, return, and if.
3. Instructions
Instructions are the statements written in a program to perform speci๏ฌc tasks. Each
instruction tells the computer what to do, such as calculations, input/output, or decision
making. Every instruction in C usually ends with a semicolon (;).
4. Program
A program is a complete set of instructions written to solve a problem. It includes all
elements like variables, constants, and instructions organized properly. Every C program
starts execution from the main() function.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download MODULE 1 C PROGRAMMING (2024 SCHEME KTU) and more Summaries C programming in PDF only on Docsity!

INTRODUCTION TO C

C is one of the popular general purpose programming languages. C

language has been designed and developed by Dennies Ritchie at Bell

Laboratories, USA in 1972. C is widely used for "system programming",

including implementing operating systems and embedded system

applications (UNIX, Linux, Windows, iOS)

Steps in Learning C Language

Learning C programming is done step by step, starting from basic elements and moving towards writing complete programs.

1. Alphabets, Digits, and Special Symbols

C language is made up of basic characters such as alphabets (Aโ€“Z, aโ€“z), digits (0โ€“9), and special symbols like +, -, {, }, ;, etc. These are used to form words, expressions, and statements in a program.

2. Constants, Variables, and Keywords

These are the basic building blocks of C programming.

Constants are fixed values that do not change during program execution (e.g., 10, 3.5, 'A'). Variables are names given to memory locations used to store data, and their values can change (e.g., int x = 5;). Keywords are reserved words in C with special meanings, such as int, float, return, and if.

3. Instructions

Instructions are the statements written in a program to perform specific tasks. Each instruction tells the computer what to do, such as calculations, input/output, or decision making. Every instruction in C usually ends with a semicolon (;).

4. Program

A program is a complete set of instructions written to solve a problem. It includes all elements like variables, constants, and instructions organized properly. Every C program starts execution from the main() function.

Character Set in C

A character is the smallest unit in a program and is used to form words, expressions, and statements. In C programming, a character can be a letter, digit, or special symbol. The combination of these characters is used to write programs.

The character set in C includes the following:

1. Alphabets

These include both lowercase and uppercase letters.

Lowercase alphabets: a to z Uppercase alphabets: A to Z

These are mainly used for naming variables, functions, and identifiers.

2. Digits

Digits are numbers from 0 to 9. They are used to represent numeric values in programs.

3. Special Characters

These are symbols used to perform operations or define the structure of a program. Examples include:

      • / % = < > ( ) { } [ ] ; : # @ _ ' " \

4. White Spaces and Escape Sequences

White spaces include blank space, tab, and newline. They improve readability of the program. Escape sequences are special characters used with a backslash () to perform specific tasks. Examples: \n โ†’ new line \t โ†’ tab space \b โ†’ backspace

Character Representation

In C programming, characters are represented using the ASCII (American Standard Code for Information Interchange) system. ASCII assigns a unique numeric value to each character so that computers can store and process text efficiently.

Identifiers and Keywords

In C programming, identifiers and keywords are important concepts used to write programs correctly.

Identifiers

Identifiers are user-defined names used to identify different elements in a program such as variables, functions, and arrays. They help in giving meaningful names to data and operations.

Rules for Naming Identifiers

Must begin with a letter or underscore (_) Can contain letters, digits, and underscore only Cannot use special characters like @, #, - Should not be a keyword Should not contain spaces They are case sensitive (e.g., sum and Sum are different)

Examples

Valid identifiers: length, area, total_sum, _index Invalid identifiers: 1stplace (starts with digit), total-sum (contains -), float (keyword)

Keywords

Keywords are reserved words in C that have fixed meanings. They are used by the compiler to perform specific functions and cannot be used as identifiers.

Characteristics of Keywords

Reserved words (cannot be used as variable names) Always written in lowercase Have fixed meaning in the program

Examples of Keywords

int, float, if, else, return, while, for, break, char, double, void, struct, etc.

Identifiers Keywords

User-defined names used in a

program

Reserved words in C

Used for variables, functions,

arrays, etc.

Used to define program structure

Can be created by the

programmer

Cannot be created by the

programmer

Must follow naming rules No need to follow naming rules

Cannot be a keyword Cannot be used as identifiers

Can contain letters, digits, and

underscore

Have fixed spelling and meaning

Can be in uppercase or lowercase Always written in lowercase

Case sensitive (sum โ‰  Sum) Not case variable (fixed form only)

Can be changed during program

writing

Cannot be changed

Example: total, num1, _index Example: int, float, if, return

Constants

Constants are values that do not change during the execution of a program. Once defined, their value remains fixed. They are also called literals.

Types of Constants in C

1. Integer Constants

Integer constants are whole numbers (no decimal point). They can be written in different number systems:

int (Integer) Used to store whole numbers without decimal points. Example: int a = 10; char (Character) Used to store a single character like a letter or symbol. Example: char ch = 'A'; (Stored internally using ASCII value) float (Floating Point) Used to store decimal numbers (single precision). Example: float x = 3.14; double Used to store larger and more accurate decimal numbers. Example: double y = 12.3456; void Represents no value. Mostly used in functions that do not return anything.

๐Ÿ‘‰ These are the most commonly used data types in C.

2. Derived Data Types

These are formed using basic data types and are used for handling more complex data.

Array Stores multiple values of the same type in a list. Example: storing marks of students Pointer Stores the memory address of another variable. Function A block of code that performs a specific task and can be reused.

3. User-Defined Data Types

These are created by the programmer according to need.

Structure (struct) Used to group different types of data together. Union Similar to structure but shares the same memory for all members. Enumeration (enum) Used to define a set of named constant values.

Type Casting in C

Type casting means changing one data type into another. It is used when we want to convert data from one type to a different type.

For example, converting an integer to a character or a float to an integer.

Types of Type Conversion in C

1. Implicit Type Conversion (Automatic)

This conversion is done automatically by the compiler. The programmer does not need to do anything.

It usually happens when different data types are used in an expression.

Example:

int x; for(x = 97; x <= 122; x++) { printf("%c", x); }

Here, the integer value of x is automatically converted to a character when printing.

2. Explicit Type Conversion (Type Casting)

This conversion is done manually by the programmer using a cast operator.

Syntax:

(data_type) expression;

Example:

int x; for(x = 97; x <= 122; x++) { printf("%c", (char)x); }

Here, (char)x explicitly converts the integer value of x into a character.

Operators and Their

Precedence in C

Operators are symbols used to perform operations on data (operands). Operands are the values or variables on which the operations are applied.

Types of Operators

1. Unary Operators (one operand)

These operators work on a single value. Examples: ++, --, !, sizeof Example: ++a increases the value of a by 1

2. Binary Operators (two operands)

These operators need two values.

Arithmetic Operators (+ - * / %) Used for calculations like addition and multiplication Example: a + b Relational Operators (< > <= >= == !=) Used to compare two values and give result TRUE or FALSE Example: a > b Logical Operators (&& || !) Used to combine conditions Example: (a > b && b > c) Assignment Operators (= += -= *= /=) Used to assign values to variables Example: a = 10 Bitwise Operators (& | ^ ~ << >>) Work on binary (bit-level) data

3. Ternary Operator (three operands)

Used for decision making in a single line

Syntax:

condition? value1 : value2;

Example:

result = (marks >= 50)? 1 : 0;

Increment and Decrement Operators

++ increases value by 1 -- decreases value by 1

Prefix: ++a โ†’ change first, then use Postfix: a++ โ†’ use first, then change

Operator Precedence

Operator precedence tells us the order in which operations are performed in an expression. When an expression has multiple operators, precedence decides which operator is evaluated first.

Why is it important?

If precedence is not followed, the result of an expression can be wrong. The compiler uses precedence rules to evaluate expressions correctly.

Basic Order of Precedence (High to Low)

  1. Unary operators โ†’ ++ --! sizeof
  2. Multiplication / Division / Modulus โ†’ * / %
  3. Addition / Subtraction โ†’ + -
  4. Relational operators โ†’ < > <= >=
  5. Equality operators โ†’ == !=
  6. Logical AND โ†’ &&
  7. Logical OR โ†’ ||
  8. Assignment โ†’ = += -= *= /=

Example 1

x = 10 + 2 * 7;

Step 1: 2 * 7 = 14 (higher precedence) Step 2: 10 + 14 = 24

Final result: x = 24

Trick: โ€œUnary โ†’ Multiply โ†’ Add โ†’ Compare โ†’ Logic โ†’ Assignโ€

Think of it step by step:

  1. Unary โ†’ ++ --!
  2. Multiply group โ†’ * / %
  3. Add group โ†’ + -

5. User-Defined Functions

Functions created by the programmer to perform specific tasks. They help in making programs modular and reusable.

Example Program

// Program to print Hello World #include

int main() { printf("Hello, World"); return 0; }

Input and Output Functions

Used to take input from user and display output.

getchar() / putchar() โ†’ for single character gets() / puts() โ†’ for strings scanf() โ†’ for input printf() โ†’ for output

Common Format Specifiers

%d โ†’ integer %c โ†’ character %f โ†’ float %s โ†’ string

Control Flow Statements

Control flow statements are used to control the order in which statements are executed in a program. In real programs, decisions need to be made and some tasks need to be repeated.

1. Branching (Decision Making)

Branching is used when a program needs to choose between different actions based on a condition.

If the condition is true, one set of statements is executed; otherwise, another set is executed.

Examples:

if if-else switch

2. Selection

Selection is a type of branching where one option is selected from many choices.

Example:

switch statement (selects one case from multiple options)

3. Looping (Repetition)

Looping is used when a set of statements needs to be repeated multiple times until a condition is satisfied.

Examples:

for loop while loop do-while loop

Conditional Statements in C

Conditional statements are used to make decisions in a program. They control the flow of execution based on whether a condition is true or false.

Types of Conditional Statements

1. Simple if Statement

Used to check a condition. If it is true, the statement is executed.

Syntax:

if(condition) { statement; }

Example:

if(a < 10) { printf("Number is less than 10"); }

Example Idea: Check whether input is uppercase, lowercase, digit, or special character.

4. Nested if Statement

An if statement inside another if.

Example Idea:

if(a > 0) { if(a < 10) { printf("Between 1 and 9"); } }

5. Conditional Operator (?:)

Short form of if-else.

Syntax:

condition? value1 : value2;

Example:

big = (a > b)? a : b;

6. switch Statement

Used when there are many choices based on one variable.

Syntax:

switch(expression) { case value1: statement; break; case value2: statement; break; default: statement; }

Example Idea: Print day name based on number.

1. Simple if Statement

Program: Check if number is less than 10

#include int main() { int a; printf("Enter a number: "); scanf("%d", &a);

if(a < 10) { printf("Number is less than 10"); }

return 0; }

2. if-else Statement

Program: Find largest of two numbers

#include int main() { int a, b;

printf("Enter two numbers: "); scanf("%d%d", &a, &b);

if(a > b) printf("Largest number is %d", a); else printf("Largest number is %d", b);

return 0; }

3. if-else if Ladder

5. Conditional Operator (?:)

Program: Find largest using ternary operator

#include int main() { int a, b, big;

printf("Enter two numbers: "); scanf("%d%d", &a, &b);

big = (a > b)? a : b;

printf("Largest number is %d", big);

return 0; }

6. switch Statement

Program: Print day name

#include int main() { int day;

printf("Enter day number (1-7): "); scanf("%d", &day);

switch(day) { case 1: printf("Sunday"); break; case 2: printf("Monday"); break; case 3: printf("Tuesday"); break; case 4: printf("Wednesday"); break; case 5: printf("Thursday"); break; case 6: printf("Friday"); break; case 7: printf("Saturday"); break; default: printf("Invalid day"); }

return 0; }

Iteration Statements (Loops)

Iteration statements are used to repeat a set of instructions until a condition becomes false. These are also called loops.

Basic Parts of a Loop

Initialization โ†’ starting value Condition โ†’ checks whether to continue Update โ†’ changes value each time Body โ†’ statements to execute repeatedly

Types of Loops

1. for Loop

Used when number of iterations is known All parts (initialization, condition, update) are in one line

Syntax:

for(initialization; condition; update) { // body }

2. while Loop

Used when number of iterations is not known Condition is checked before execution

Syntax:

while(condition) { // body }

3. do-while Loop

Condition is checked after execution Loop runs at least once

Syntax: