TCET Programming in C Module 2
Module 2
Fundamental of C Programming
Structure of C program
Character Set, Identifiers and keywords, Data types, Constants, Variables.
Operators-Arithmetic, Relational, Logical, Assignment, Compound assignment, Bitwise, Unary and Conditional.
Operator precedence
Data Input and Output – printf( ), scanf( ), putchar( ), getchar( ), puts( ), gets( ).
What is C?
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972 by Dennis Ritchie. C became
popular because it is simple and easy to use.
C language combines the power of a low-level language and a high-level language. The low-level languages are
used for system programming, while the high-level languages are used for application programming. It is because
such languages are flexible and easy to use. Hence, C language is a widely used computer language.
It supports various operators, constructors, data structures, and loop constructs. The features of C programming
make it possible to use the language for system programming, development of interpreters, compilers, operating
systems, graphics, general utilities, etc. C is also used to write other applications, such as databases, compilers,
word processors, and spreadsheets.
Getting Started with C
There is a close analogy between learning English language and learning C language.
As with English, C language too has a set of rules that one must follow while writing programs in it.
The valid alphabets, numbers and special symbols allowed in C.
Constants, Variables and Keywords The alphabets, digits and special symbols when properly combined form
constants, variables and keywords. A constant is an entity that doesn’t change, whereas, a variable is an entity that
may change. A keyword is a word that carries special meaning. In programming languages, constants are often
called literals, whereas variables are called identifiers.
C Keywords Keywords are the words whose meaning has already been explained to the C compiler (or in a broad
sense to the computer). There are only 32 keywords available in C.
1
TCET Programming in C Module 2
Structure of C program
Program 2: Calculate Age
// Program to calculate current age based on birth year
#include <stdio.h> // Preprocessor directive
#define CURRENT_YEAR 2024 // Defining the current year
int calculateAge(int birthYear); // Function declaration
int main() {
int birthYear, age; // Variable declaration
printf("Enter your birth year: ");
scanf("%d", &birthYear); // Input from the user
age = calculateAge(birthYear); // Calculate the age through function call
printf("Your age is %d\n", age); // Output the age
return 0; // End of program & Return statement
}
// Function to calculate age
int calculateAge(int birthYear) {
return CURRENT_YEAR - birthYear; // Return the age
}
Explanation:
• Documentation: Describes the program's purpose.
• Preprocessor Directive: Includes standard input-output library with #include <stdio.h>.
• Definition Section: #define CURRENT_YEAR 2024 defines the current year.
• Function Declaration: Declares the calculateAge function.
• Variable Declaration: Declares birthYear and age variables.
• Statements and Expressions: Takes the user's birth year, calculates the age, and prints the result.
2
TCET Programming in C Module 2
• Sub Program: calculateAge computes the age using the birth year.
• Return Statement: return 0; signals successful execution.
1. Character Set in C
The character set in C refers to all the characters that can be used in a C program. It includes:
• Alphabetic characters: Lowercase a-z and uppercase A-Z.
• Digits: 0-9.
• Special characters: Such as +, -, *, /, %, =, {, }, ;, etc.
• Whitespace characters: Space, tab, and newline.
• Escape sequences: Like \n (newline), \t (tab), \\ (backslash), etc.
2. Identifiers and Keywords
Identifiers:
• Identifiers are names used to identify variables, functions, arrays, etc.
• Rules for valid identifiers:
o It must begin with a letter (A-Z or a-z) or an underscore (_).
o Subsequent characters can be letters, digits (0-9), or underscores.
o They cannot be the same as reserved keywords in C.
Example: int age;, float salary;, char name[];
Keywords:
• Keywords are reserved words that have special meaning in C and cannot be used as identifiers.
• Examples of keywords:
o int, float, char, return, if, else, while, for, break, continue, void, etc.
• Keywords are case-sensitive in C, meaning int and Int are different.
3. Data Types
In C, a data type defines the type of data that a variable can store. It specifies the size of the variable
and the operations that can be performed on it.
Basic Data Types:
• int: Used to store integer values (whole numbers).
o Example: int num = 5;
• float: Used to store single-precision floating-point numbers (decimal values).
o Example: float price = 4.99;
• double: Used to store double-precision floating-point numbers (more precision than float).
o Example: double distance = 3.14159265358979;
• char: Used to store a single character (enclosed in single quotes).
o Example: char letter = 'A';
Derived Data Types:
• Array: A collection of elements of the same type.
o Example: int arr[10];
• Pointer: A variable that stores the address of another variable.
o Example: int *ptr;
3
TCET Programming in C Module 2
• Structure: A user-defined data type that groups different types of data.
o Example: struct person { char name[50]; int age; };
Void Data Type:
• Represents an absence of value. It is used for functions that do not return any value.
o Example: void myFunction() { /* code */ }
4. Constants
Constants are fixed values that do not change during the execution of a program. In C, constants can be
of two types:
Literal Constants:
• These are values directly written in the program.
o Example: 5, 3.14, 'A'
Symbolic Constants:
• Constants can also be defined using the #define preprocessor directive.
o Example: #define PI 3.14
Constant Variables:
• These are variables whose values cannot be changed after initialization. They are declared using the const
keyword.
o Example: const int MAX_SIZE = 100;
5. Variables
A variable is a named storage location in memory where data can be stored and changed during the
program execution.
• Declaration: A variable must be declared before it is used.
o Syntax: <data_type> <variable_name>;
o Example: int age;
• Initialization: Variables can be initialized at the time of declaration.
o Example: int age = 25;
• Scope and Lifetime of Variables:
o Local Variables: Variables declared inside a function. Their scope is limited to the function, and they are
destroyed when the function exits.
o Global Variables: Variables declared outside of all functions. Their scope extends throughout the program.
o Static Variables: Variables declared with the static keyword. Their value persists across function calls.
Summary:
• Character Set in C consists of letters, digits, special characters, whitespace, and escape sequences.
• Identifiers are names used to identify variables or functions, while keywords are reserved words with special
meanings in the C language.
• Data Types in C specify the type and size of data, with basic types like int, float, double, and char, and
derived types like arrays, pointers, and structures.
• Constants are fixed values, and can be defined using #define or const keyword.
• Variables are named storage locations whose values can change during the program's execution.
4
TCET Programming in C Module 2
Operators in C Programming
Operators in C are symbols used to perform operations on variables or values. The main types
of operators in C are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Compound Assignment Operators
6. Bitwise Operators
7. Unary Operators
8. Conditional (Ternary) Operators
1. Arithmetic Operators
Arithmetic operators are used to perform basic arithmetic operations like addition,
subtraction, multiplication, etc.
Syntax:
<operand1> <operator> <operand2>
Operators:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulo, remainder)
5
TCET Programming in C Module 2
Example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("Addition: %d\n", a + b); // 15
printf("Subtraction: %d\n", a - b); // 5
printf("Multiplication: %d\n", a * b); // 50
printf("Division: %d\n", a / b); // 2
printf("Modulo: %d\n", a % b); // 0
return 0;
}
6
TCET Programming in C Module 2
2. Relational Operators
Relational operators are used to compare two values or expressions.
Syntax:
<operand1> <operator> <operand2>
Operators:
• == (Equal to)
• != (Not equal to)
• < (Less than)
• > (Greater than)
• <= (Less than or equal to)
• >= (Greater than or equal to)
7
TCET Programming in C Module 2
Example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("Equal: %d\n", a == b); // 0 (false)
printf("Not equal: %d\n", a != b); // 1 (true)
printf("Less than: %d\n", a < b); // 0 (false)
printf("Greater than: %d\n", a > b); // 1 (true)
return 0;
}
3. Logical Operators
Logical operators are used to perform logical operations, typically in conditions.
Syntax:
<operand1> <operator> <operand2>
Operators:
• && (Logical AND)
• || (Logical OR)
• ! (Logical NOT)
Example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
if (a > b && a != 0) {
printf("Logical AND: True\n");
}
if (a > b || b == 0) {
printf("Logical OR: True\n");
}
printf("Logical NOT: %d\n", !(a == b)); // 1 (True)
return 0;
}
8
TCET Programming in C Module 2
4. Assignment Operators
Assignment operators are used to assign values to variables.
Syntax:
<variable> <operator> <value>
Operators:
• = (Simple assignment)
• += (Add and assign)
• -= (Subtract and assign)
• *= (Multiply and assign)
• /= (Divide and assign)
• %= (Modulo and assign)
9
TCET Programming in C Module 2
Example:
#include <stdio.h>
int main() {
int a = 5;
a += 3; // a = a + 3; a = 8
printf("a += 3: %d\n", a);
a -= 2; // a = a - 2; a = 6
printf("a -= 2: %d\n", a);
a *= 2; // a = a * 2; a = 12
printf("a *= 2: %d\n", a);
a /= 4; // a = a / 4; a = 3
printf("a /= 4: %d\n", a);
return 0;
}
5. Compound Assignment Operators
These are shorthand operators for performing an operation and assigning the result to the
variable in one step.
Example:
#include <stdio.h>
int main() {
int a = 10;
a += 5; // Equivalent to: a = a + 5
printf("a += 5: %d\n", a);
a *= 2; // Equivalent to: a = a * 2
printf("a *= 2: %d\n", a);
return 0;
}
6. Bitwise Operators
Bitwise operators perform operations on individual bits of integers.
Syntax:
<operand1> <operator> <operand2>
Operators:
• & (Bitwise AND)
• | (Bitwise OR)
• ^ (Bitwise XOR)
• ~ (Bitwise NOT)
• << (Left shift)
• >> (Right shift)
10
TCET Programming in C Module 2
11
TCET Programming in C Module 2
Example:
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("a & b: %d\n", a & b); // Bitwise AND
printf("a | b: %d\n", a | b); // Bitwise OR
printf("a ^ b: %d\n", a ^ b); // Bitwise XOR
printf("~a: %d\n", ~a); // Bitwise NOT
printf("a << 1: %d\n", a << 1); // Left shift
printf("a >> 1: %d\n", a >> 1); // Right shift
return 0;
}
7. Unary Operators
Unary operators operate on a single operand. They are used for various purposes such as
incrementing, decrementing, and negating.
Operators:
• ++ (Increment)
• -- (Decrement)
• + (Unary plus)
• - (Unary minus)
• ! (Logical NOT)
• sizeof (Size of operand)
Example:
#include <stdio.h>
int main() {
int a = 5;
printf("++a: %d\n", ++a); // Pre-increment: 6
printf("a++: %d\n", a++); // Post-increment: 6, then a becomes 7
printf("a--: %d\n", a--); // Post-decrement: 7, then a becomes 6
printf("!a: %d\n", !a); // Logical NOT: 0 (false)
return 0;
}
8. Conditional (Ternary) Operator
The conditional operator is a shorthand for if-else statements. It evaluates a condition and
returns one of two values based on whether the condition is true or false.
Syntax:
<condition> ? <value_if_true> : <value_if_false>
Example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
int max = (a > b) ? a : b; // If a > b, max = a; else max = b
printf("Max value: %d\n", max);
return 0;
}
12
TCET Programming in C Module 2
Summary
• Arithmetic Operators: Perform basic math (+, -, *, /, %).
• Relational Operators: Compare two values (==, !=, <, >, <=, >=).
• Logical Operators: Combine conditions (&&, ||, !).
• Assignment Operators: Assign values to variables (=, +=, -=, *=, /=, %=).
• Compound Assignment Operators: Shortened forms of assignment (+=, -=, *=, etc.).
• Bitwise Operators: Perform operations on individual bits (&, |, ^, ~, <<, >>).
• Unary Operators: Operate on one operand (++, --, +, -, !, sizeof).
• Conditional Operator: A shorthand for if-else (<condition> ? <true_value> :
<false_value>).
Operator Precedence in C Programming
Operator precedence in C programming determines the order in which different operators in an expression
are evaluated. Understanding operator precedence is crucial to writing correct expressions, as it helps avoid
unintended behavior due to misinterpretation of the evaluation order.
1. What is Operator Precedence?
• Definition: Operator precedence is the set of rules that specifies the order in which operators
are evaluated in an expression.
• Goal: To determine the correct sequence in which operators are applied, ensuring that the
expression evaluates correctly.
• Evaluation: Operators with higher precedence are evaluated first. If operators have the same
precedence, their associativity (left-to-right or right-to-left) determines the order.
2. Operator Precedence in C
In C, operators are classified into several groups based on their precedence. Below is a detailed
explanation of common operators in C, arranged from highest to lowest precedence.
a) Parentheses ()
• Precedence: Highest
• Purpose: Parentheses are used to explicitly specify the order of operations in expressions.
• Example:
int result = (5 + 3) * 2; // Evaluates as (5 + 3) * 2 = 16
b) Unary Operators
Unary operators are evaluated before binary operators. They are used to perform operations on a single
operand.
• Operators:
o Unary plus +
o Unary minus -
o Logical NOT !
o Bitwise NOT ~
o Increment ++ (prefix)
o Decrement -- (prefix)
o Dereference * (pointer)
o Address & (address-of)
• Precedence: High
• Associativity: Right to left for ++, --, &, *, and others.
• Example:
int x = 5;
int y = ++x; // x is incremented first, then y = 6
c) Exponentiation (No direct exponentiation operator in C)
• C does not have an exponentiation operator like **. Exponentiation can be performed using
the pow() function from math.h.
13
TCET Programming in C Module 2
d) Multiplication, Division, and Modulus * / %
• Precedence: These operators have the same precedence and are evaluated from left to
right.
• Operators:
o Multiplication *
o Division /
o Modulus % (remainder after division)
• Example:
int result = 4 + 5 * 2; // Multiplication is done first, result = 14
e) Addition and Subtraction + -
• Precedence: Lower than multiplication and division.
• Associativity: Left to right.
• Example:
int result = 5 + 3 - 2; // Left to right: result = 6
f) Relational Operators < <= > >=
• Precedence: These operators compare two values and return a boolean result.
• Operators:
o Less than <
o Greater than >
o Less than or equal <=
o Greater than or equal >=
• Associativity: Left to right.
• Example:
int result = (5 > 3); // result = 1 (True)
g) Equality Operators == !=
• Precedence: Equality operators are used to compare values.
• Operators:
o Equal to ==
o Not equal to !=
• Associativity: Left to right.
• Example:
int result = (5 == 5); // result = 1 (True)
h) Bitwise AND &
• Precedence: Lower than relational operators.
• Associativity: Left to right.
• Example:
int result = 5 & 3; // Bitwise AND of 5 and 3
i) Logical AND &&
• Precedence: Lower than bitwise AND.
• Associativity: Left to right.
• Example:
int result = (5 > 3) && (2 < 8); // Evaluates to 1 (True)
j) Bitwise OR |
• Precedence: Lower than bitwise AND.
• Associativity: Left to right.
• Example:
int result = 5 | 3; // Bitwise OR of 5 and 3
k) Logical OR ||
• Precedence: Lower than logical AND.
• Associativity: Left to right.
• Example:
int result = (5 < 3) || (2 < 8); // Evaluates to 1 (True)
l) Conditional (Ternary) Operator ? :
• Precedence: Higher than logical OR and assignment.
14
TCET Programming in C Module 2
• Purpose: A shorthand for if-else expressions.
• Example:
int result = (a > b) ? a : b; // If a > b, result = a, else result = b
m) Assignment Operators = += -= *= /= %= &= |= ^= <<= >>=
• Precedence: Assignment operators have the lowest precedence among the operators in C.
• Associativity: Right to left.
• Example:
int x = 5;
x += 3; // x becomes 8
3. Operator Precedence Table for C
Here is the operator precedence table for C, ordered from the highest to lowest precedence:
4. Understanding Precedence in Expressions
Example 1:
int result = 5 + 3 * 2;
• Multiplication (*) has higher precedence than addition (+), so it is evaluated first.
• Evaluation: 5 + (3 * 2) → 5 + 6 → result = 11
Example 2:
int result = 10 + 5 * 2 / 4;
• Multiplication (*) and division (/) have the same precedence and are evaluated from left to
right.
• Evaluation: 10 + (5 * 2) / 4 → 10 + 10 / 4 → 10 + 2 → result = 12
Example 3:
int result = (5 + 3) * 2;
• Parentheses () override precedence, so the addition (5 + 3) is evaluated first.
• Evaluation: (5 + 3) * 2 → 8 * 2 → result = 16
5. Common Pitfalls
• Misunderstanding precedence: A common mistake is assuming that operators are evaluated
from left to right without considering precedence.
• Assignment operator confusion: Assignment operators (=, +=, -=, etc.) have the lowest
precedence, so they are evaluated after other operations in an expression.
15
TCET Programming in C Module 2
Example of a potential mistake:
int x = 5;
int result = x * 3 + 2;
• Correct: result = (x * 3) + 2 → result = 15 + 2 → result = 17
• Common mistake: Assuming that addition happens before multiplication, which would give
an incorrect result.
6. Conclusion
Operator precedence in C determines how expressions are evaluated. By understanding and properly using
operator precedence, developers can write more predictable and error-free code.
Data Input and Output in C Programming
In C programming, we use various functions to handle input and output operations. These functions allow
us to read data from the user or display information to the screen.
1. Output Functions
Output functions in C are used to display data to the user or on the screen.
a) printf()
• Purpose: Displays formatted output to the standard output (usually the screen).
• Syntax:
printf("format string", arguments);
• Common format specifiers:
o %d: For integer values
o %f: For floating-point numbers
o %c: For characters
o %s: For strings
o %lf: For double values
• Example:
int x = 10;
printf("The value of x is: %d\n", x); // Output: The value of x is: 10
b) putchar()
• Purpose: Used to display a single character.
• Syntax:
putchar(character);
• Example:
char ch = 'A';
putchar(ch); // Output: A
c) puts()
• Purpose: Used to print a string followed by a newline (\n).
• Syntax:
puts("string");
• Example:
puts("Hello, world!"); // Output: Hello, world!
2. Input Functions
Input functions in C are used to read data from the user or from external sources.
a) scanf()
• Purpose: Used to read formatted input from the user (from the keyboard).
• Syntax:
scanf("format string", &variable);
• Common format specifiers:
o %d: For reading integer values
o %f: For reading floating-point numbers
o %c: For reading characters
o %s: For reading strings (without spaces)
• Example:
16
TCET Programming in C Module 2
int age;
printf("Enter your age: ");
scanf("%d", &age); // User enters 25
printf("Your age is: %d\n", age); // Output: Your age is: 25
b) getchar()
• Purpose: Used to read a single character from the standard input (keyboard).
• Syntax:
char ch = getchar();
• Example:
char ch;
printf("Enter a character: ");
ch = getchar(); // User enters 'A'
printf("You entered: %c\n", ch); // Output: You entered: A
c) gets() (Deprecated)
• Purpose: Reads a line of text (string) from the standard input, including spaces. Note: This
function is deprecated in modern C and should be avoided because it can lead to buffer
overflow issues.
• Syntax:
gets(string);
• Example:
char name[50];
printf("Enter your name: ");
gets(name); // User enters "John Doe"
printf("Hello, %s!\n", name); // Output: Hello, John Doe!
3. Important Points
• Buffer Overflow in gets(): gets() does not check for the size of the input buffer, so it can
cause a buffer overflow if the user enters more characters than the array can hold. Use
fgets() instead for safer input.
• Newline Character: getchar() and scanf() often leave a newline character (\n) in the input
buffer after reading. This can affect subsequent input operations. To handle this, we might
need to use getchar() to read and discard the newline.
• Spaces in Strings: scanf() with the %s format specifier cannot read strings that contain
spaces. To read strings with spaces, use fgets() instead.
17
TCET Programming in C Module 2
18
TCET Programming in C Module 2
The first printf( ) outputs the message ‘Enter values of p, n, r’ on the screen. Here we have not used any
expression in printf( ) which means that using expressions in printf( ) is optional. Note the use of ampersand
(&) before the variables in the scanf( ) function is necessary. & is the ‘Address of’ operator. It gives the
location number (address) used by the variable in memory. When we say &a, we are telling scanf( ) at which
memory location should it store the value supplied by the user from the keyboard.
19
TCET Programming in C Module 2
Problem 1.2 The distance between two cities (in kilometers) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimeters.
Problem 1.3 If the marks obtained by a student in five different subjects are input through the keyboard,
write a program to find out the aggregate marks and percentage marks obtained by the student. Assume
that the maximum marks that can be obtained by a student in each subject is 100.
20
TCET Programming in C Module 2
2 Marks
What is the purpose of the printf() function in C?
Define an identifier in C programming.
What is the difference between a keyword and an identifier in C?
What is the use of the getchar() function?
What is an arithmetic operator? Give an example.
Name any two relational operators in C.
What is a constant in C? Give an example.
How do you declare a variable in C?
What is a bitwise operator? Give an example.
What does the puts() function do in C?
Define a variable in C.
What is the purpose of the scanf() function in C?
What is the precedence of the * (multiplication) operator compared to the + (addition)
operator in C?
What is a unary operator in C? Give an example.
(Any four can be ask)
21
TCET Programming in C Module 2
5 Marks
What are data types in C? Explain the difference between primary data types and derived data
types with examples.
Discuss the role of constants in C programming. What are the different types of constants in
C?
What are operators in C? Classify operators and explain any three categories with examples.
What is an assignment operator in C? Provide examples of different types of assignment
operators.
Explain the operator precedence in C with an example.
Discuss the role of logical operators in C with examples.
What is a conditional operator in C? Explain how it works with an example.
Discuss the structure of a C program in detail.
Write a C program to perform basic arithmetic operations (addition, subtraction,
multiplication, and division) using appropriate operators.
Write a C program that takes two numbers as input, compares them using relational
operators, and prints the result.
Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic
salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross
salary.
The distance between two cities (in kilometers) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimeters.
If the marks obtained by a student in five different subjects are input through the keyboard,
write a program to find out the aggregate marks and percentage marks obtained by the
student. Assume that the maximum marks that can be obtained by a student in each subject is
100.
Swaping of two numbers program.
If lengths of three sides of a triangle are input through the keyboard, write a program to find
the area of the triangle.
22
TCET Programming in C Module 2
10 Marks
The length and breadth of a rectangle and radius of a circle are input through the keyboard.
Write a program to calculate the area and perimeter of the rectangle, and the area and
circumference of the circle.
Explain the different types of constants in C. Provide examples of each type.
Explain all the categories of operators in C. Provide examples for each category.
Explain the difference between logical operators (&&, ||, !) and bitwise operators (&, |, ^).
Explain the difference between the ++ (increment) and -- (decrement) operators in C.
Discuss the different assignment operators in C with examples.
Write a program to construct the following terms in program.
printf( ), scanf( ), putchar( ), getchar( ), puts( ), gets( ).
Write a C program to evaluate the following expression using different types of operators.
Result = (a + b * c - d) / (e % f) + (g && h) - (i++ * j--)
23