0% found this document useful (0 votes)
8 views31 pages

BCA C Programming Unit 2 Introduction To C Language

This document serves as a self-learning material for the C programming language, covering its history, structure, and fundamental concepts. It emphasizes the importance of functions as building blocks in C programming and provides insights into various data types and program organization. The document also includes learning objectives, case studies, terminal questions, and assignments to enhance understanding of C language.

Uploaded by

sherylswami378
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)
8 views31 pages

BCA C Programming Unit 2 Introduction To C Language

This document serves as a self-learning material for the C programming language, covering its history, structure, and fundamental concepts. It emphasizes the importance of functions as building blocks in C programming and provides insights into various data types and program organization. The document also includes learning objectives, case studies, terminal questions, and assignments to enhance understanding of C language.

Uploaded by

sherylswami378
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
You are on page 1/ 31

C Programming

Introduction to
C Language
SELF LEARNING MATERIAL

SEM - I (102)

BCA
UNIT-2 INTRODUCTION TO C LANGUAGE
TABLE OF CONTENTS

21 Introduction
2.2 History of C Language
2.3 Structure of C Programming
2.4 Functions as Building Blocks
2.5 Tokens
2.6 Data Types
2.7 Summary
2.8 Case Study
2.9 Terminal Questions
2.10 Answers
2.11 Assignment
2.12 References

Learning Objectives
• To explore the structure of C language
• To understand the fundamentals of C language
• To discuss various data types used in C language
NOTES

2.1
Introduction
Dennis Ritchie at Bell Labs created the general-purpose computer language
C in the early 1970s. Operating systems, compilers, and embedded systems
are just a few of the many applications that use this powerful language.

The Unix operating system originally required the system programming


language C. It was designed to be a straightforward, effective, and portable
low-level programming language. One of the most extensively used
programming languages in the world today is C.

C is an immensely popular, versatile, and user-friendly programming


language that serves as a foundation for various applications and operating
systems, such as Windows. It is also extensively utilized in the development
of complex applications like the Oracle database, Git, and the Python
interpreter. Often regarded as a divine language in programming, C’s
significance lies in its ability to act as a fundamental building block for other
languages that incorporate its concepts.

Functions play a crucial role in organizing and reusing code, allowing for
modular and efficient programming. A C program is a collection of functions.
Each function performs a specific task. Functions are called by other
functions to perform the tasks that are required by the program.

01
NOTES 2.2
History of C Language

The early 1970s marked the beginning of an interesting journey in the history of the
C programming language. Together with his colleagues at Bell Labs, Dennis Ritchie
developed it with the main goal of creating a powerful and adaptable programming
language for the Unix operating system. The roots of C can be traced back to an
earlier language called B, which was developed by Ken Thompson. B was itself
derived from the BCPL (Basic Combined Programming Language) language. As B
evolved, Dennis Ritchie saw the need for additional features and improvements,
leading to the development of the C language.

Assembly language was used to implement the first version of C on a DEC PDP-
11 machine. Its portability, strength, and simplicity helped the language become
more widely used. One of the key advantages of C was its ability to write low-
level code and directly access computer hardware while still providing high-level
programming constructs.

The first version of Brian Kernighan and Dennis Ritchie’s book “The C Programming
Language” was released in 1978. This book became immensely popular and served
as the definitive reference for learning C. It provided clear explanations, examples,
and exercises, making it accessible to a wide audience. As Unix gained prominence
in the computing world, the usage of C expanded rapidly. The language became
the de facto standard for developing system software and operating systems.
Its portability allowed Unix to be easily adapted to different hardware platforms,
solidifying C’s position as a versatile language.

In the 1980s, with the emergence of personal computers, the demand for C grew
even further. Compiler implementations for different platforms became available,
making it accessible to a wider range of developers. Early high-level programming
languages like C++ and Objective-C, which expanded on the C language and built
upon it, contributed to C’s popularity as well.

Over the years, C continued to evolve. In 1989, the American National Standards
Institute (ANSI) published the first standardized version of C, known as “ANSI C”
or “C89.” This standardization ensured consistency and portability across different
implementations.

Subsequent revisions of the C standard were published, including “C99” in


1999 and “C11” in 2011, which introduced new features and improvements to
the language. These standards provided guidelines for compiler developers and
ensured compatibility among different C implementations.

C is still a frequently used programming language today and is renowned for its
effectiveness, ease of use, and low-level control. It continues to be the language of
choice for system programming, embedded systems, and various other applications
where performance and direct hardware access are crucial.
02
Aspiring programmers, including students, often begin their journey by learning
the C language. Its rich history, wide usage, and strong foundations make it an
NOTES
essential language for understanding programming concepts and building a solid
programming skillset.

CHECK YOUR PROGRESS


1. The C programming language was created by Dennis Ritchie at ________
Labs.
2. The first standardized version of C, known as “ANSI C” or “C89,” was
published by the ________.
3. The C language was derived from the BCPL language. [True/False]
4. The book “The C Programming Language” was published before the
development of Unix. (True/False)

Activity
Explore and identify the various real-world applications and domains where the C
programming is being used extensively. You can choose domains like Operating
systems, embedded systems, compilers and interpreters, networking, etc.

2.3
Structure of C Programming

A C program’s structure refers to the way the code is arranged in a particular way.
It is important to have a well-defined structure for a C program, as this makes
it easier to understand and debug. A good structure also makes the code more
modular, which makes it easier to reuse and maintain.

A C program is typically divided into different sections, each serving a specific


purpose.

Preprocessor Directives:
STUDY NOTE
The preprocessor is a separate program that
performs source code processing prior to The main() function is
compilation. The preprocessor directives are the entry point of a C
instructions to the preprocessor. These directives program and is required
begin with the ‘#’ symbol. They include tasks in every C program.
such as including header files, defining macros,
and conditional compilation using directives like ‘#include’, ‘#define’, ‘#ifdef’, etc.

03
NOTES Header Files:
Header files contain function prototypes, definitions, and declarations necessary
for program execution. They provide information about functions and libraries that
are used in the program. Commonly used header files include ‘stdio.h’ for input/
output operations, ‘stdlib.h’ for memory allocation, ‘math.h’ for mathematical
operations, and ‘string.h’ for string handling.

Global Declarations:
In this section, global variables and constants are declared. Every function in the
program has access to global variables. Constants are values that remain constant
throughout the program’s execution.

Function Declarations:
Function declarations specify the names, return types, and parameters of functions
used in the program. Function declarations are necessary when functions are
defined after the main function.

Main Function:
The program’s primary function acts as its starting point. It is the point at which
the program execution starts, and it usually contains the program’s main logic. A
main function is a requirement for all C programs. It can accept parameters from
the command line and has a “int” return type.

Function Definitions:
User-defined functions are defined in this section. A specified set of operations are
contained in functions, which can be called from other areas of the program. They
aid in code organization, encourage reuse, and improve readability. The function
name, return type, parameter list, and function body—which contains the actual
code—are all included in the definition of a function.

Additional Functions:
There may be more functions in the application in addition to the primary function
and user-defined functions. These functions carry out particular responsibilities and
are called by other functions.

Commented Code:
Comments are used to provide explanatory notes within the source code. They are
not executed by the compiler and serve as documentation for the programmer and
other readers. Commented code helps in understanding the code’s logic, purpose,
and any important details.

CHECK YOUR PROGRESS


5. Header files in C contain function prototypes, definitions, and declarations
necessary for program execution.(True/False)
6. Global variables and constants are declared in the Global Declarations section
of a C program and are accessible throughout the program. [True/False]

04
2.4 NOTES
Functions as Building Blocks

Because C uses a procedural programming paradigm, programs are made up


of a series of procedures or functions. In C, functions play a crucial role in
organizing and executing program logic efficiently. Procedural programming
focuses on creating procedures or functions that perform specific tasks. These
functions are designed to receive inputs, process them, and produce outputs. The
main program structure consists of a series of function calls that are executed
sequentially. This approach allows for a modular and structured development of
programs.

The main building blocks of C programs are functions. They contain a group of
statements that carry out a certain function and can be used anywhere in a program.
They enhance code organization, reusability, and maintainability. By breaking down
a program into functions, complex problems can be solved by dividing them into
smaller, manageable tasks.

In C, functions are declared using the function_name(parameter_list)syntax.


The function_name is the name of the function, and the parameter_list is a
list of variables that are passed to the function. The function body is enclosed in
curly braces {}.

In the C programming language, the main() function holds significant importance.


It serves as the entry point of a C program and acts as the starting point for program
execution. When a C program is executed, the operating system starts executing
the program from the main()function.

Function Aspects
● Function Declaration:
Before using a function, it needs to be declared to inform the compiler about
its name, return type, and parameters (if any). To provide information to the
compiler regarding the function name, function parameters, and return type,
the declaration is normally either in the global scope or within a header file.
Syntax:
return_type function_name (argument list);
● Function Definition:
The actual code used to implement the declared function is contained in the
function declaration. It includes the function header (return type, function name,
parameters), followed by the function body enclosed within curly braces. The
body contains the instructions that are executed when the function is called.
Syntax:
return_type function_name (argument list) {function body;}

05
NOTES ● Function Calling:
To execute a function, it needs to be called or invoked. Function calling involves
specifying the function name along with any required arguments (if the
function has parameters). The function call transfers the program’s control to
the function, executes its code, and returns back to the caller.
Syntax:
function_name (argument_list)
● Function Parameters:
Function parameters are placeholders that receive values when the function is
called. They allow passing data from the calling code to the function. Parameters
can be of various data types such as int, float, char, etc. Functions can have
multiple parameters, separated by commas.
Syntax:
data_type parameter_name;
● Return Values:
The calling code may receive a value from a function as well. The kind of value
a function returns depends on the return type, which is set during function
definition. To supply the return value, use the ‘return’ statement. The calling
code can utilize the returned value as needed.
Syntax:
return expression;
● void Functions:
Not all functions need to return a value. Void functions do not have a return type
or a return statement. Void functions are declared using the keywordvoid. They
are used when the function’s purpose is to perform a task or modify variables
without returning a specific value.
Syntax:
void function();

Syntax of the main() Function:


The main()function has a specific syntax in C.
int main() {
// Statements
// ...
return 0;
}

int: The main() function’s return type is given as int, indicating that it returns an
integer value. According to convention, a return value of 0 denotes the successful
completion of the program, whereas a value other than zero denotes an error or
unusual termination.

main():main is the name of the function and is reserved in C. It serves as the entry
point of the program. The parentheses following the function name are mandatory.

06
void: In some cases, voidis used instead of int as the return type of main().This
shows that the main() function doesn’t return value. However, using int is more
NOTES
common because it enables you to describe the program’s success or failure.

Statements: There are several statements contained within curly brackets that
make up the main() function’s body. These statements outline the procedures and
tasks that the program will carry out. The statements may also contain additional
C language features such as loops, if-else statements, variable declarations, and
function calls.

return 0;: At the end of the main() function, a return statement is typically used
to exit the function and return a value. Returning 0 signifies successful program
execution to the operating system. Other non-zero return values can be used to
indicate errors or specific conditions.

Example of the main() Function:


#include <stdio.h>
int main() {
printf(“Hello, World!\n”);
return 0;
}

In this example, the main() function is defined to print the message “Hello,
World!” to the console using the printf() function. After executing the printf()
statement, the return 0; statement is encountered, indicating successful
program completion.

When a C program is run, the operating system looks for the binary file that
was previously compiled and launches it from the main() function. It begins by
sequentially executing each statement included within the main() function until it
reaches the function’s end or comes across a return statement. The program ends
when the main() function is finished, and the operating system gains control.

Types of Functions
In C, there are two types of functions:

User-defined functions:
The programmer develops user-defined functions to carry out particular operations
in accordance with program requirements. The programmer defines and declares
these functions in the program. The return type, function name, optional parameters,
and function body are all components of user-defined functions. The function body
is enclosed in curly braces {}.

Syntax:
return_type function_name(parameter1, parameter2, ...) {
// Function body
return value;
}

07
NOTES Example:
int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
int result = addNumbers(5, 7);
printf(“Sum: %d\n”, result);
return 0;
}

The program outputs:


Sum: 12

Standard Library Functions:


Library functions are pre-defined functions provided by C libraries. They offer a
wide range of functionality and can be directly used in programs without the need
for explicit declaration or definition. Library functions are declared in header files
and provide solutions to common programming tasks. Examples include printf(),
scanf(), strlen(), etc.

Syntax:
#include <header_file.h>
int main() {
// Function call
return 0;
}

Example:
#include <stdio.h>
int main() {
printf(“Hello, world!\n”);
return 0;
}

In the above example, theprintf() function is a library function from the stdio.h
header file. It is used to print the message “Hello, world!” to the console. The
#include <stdio.h>directive includes the necessary header file for using the
printf() function. The function call printf(“Hello, world!\n”);is executed
within the main() function.

Additional Examples of Library Functions:


● The scanf()function from stdio.his used to read input from the user.
#include <stdio.h>
int main() {
int age;

08
printf(“Enter your age: “);
scanf(“%d”, &age);
NOTES
printf(“Your age is: %d\n”, age);
return 0;
}
Output:
Enter your age: 25
Your age is: 25
● The strlen()function from string.h is used to determine the length of a string.
#include <stdio.h>
#include <string.h>
int main() {
char name[] = “John”;
int length = strlen(name);
printf(“Length of name: %d\n”, length);
return 0;
}
Output:
Length of name: 4
● The rand()function from stdlib.his used to generate random numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0)); // Seed the random number generator
int randomNum = rand() % 100; // Generate a random
number between 0 and 99
printf(“Random Number: %d\n”, randomNum);
return 0;
}
Output:
Random Number: 67

CHECK YOUR PROGRESS


7. Library functions in C are pre-defined functions provided by C libraries,
and their declarations need to be explicitly mentioned in the program.
[True/False]
8. The header file for input/output operations in C is _______.
9. The _______ function from string.h is used to determine the length of a
string.
10. What category of functions provides a wide range of functionality and can
be directly used in programs without explicit declaration or definition?

09
NOTES Activity
Use any IDE or online compiler for C Language and practice compiling and
running the codes provided in this section. Gain hands-on experience with the
basic workflow of C programs. Try changing the syntax of the code and analyse
the errors that are encountered.

2.5
Tokens

A character set refers to the collection of characters that can be used in the
program. It defines the set of valid characters, such as letters, digits, symbols, and
control characters, that can be represented and manipulated in C programs.

C uses the ASCII (American Standard Code for Information Interchange) character
set as the default. ASCII represents characters using 7 bits, allowing a total of
128 unique characters. These characters include uppercase and lowercase letters,
digits, punctuation marks, special symbols, and control characters.

1. Letters:
● Uppercase: A, B, C, ..., Z
● Lowercase: a, b, c, ..., z
2. Digits: 0, 1, 2, ..., 9
3. Punctuation marks: !, ?, ., ,, ;, :, etc.
4. Special symbols: @, #, $, %, &, *, etc.
5. Control characters: ‘\n’ (newline), ‘\t’ (tab), ‘\b’ (backspace), etc.

In C programming, characters are represented using single quotes (‘ ‘).

Example:
char ch = ‘A’;

In the above example, the character variable ch is assigned the value ‘A’.

Characters can also be used in C string literals, enclosed in double quotes (“ “).

Example:
char str[] = “Hello”;

In the above example, the character array str stores the string “Hello” where
each character is represented individually.

10
ASCII Standard: The ASCII standard consists of 128 characters, including digits,
punctuation marks, uppercase and lowercase letters, control characters, and
NOTES
special symbols.

Extended ASCII: Extended ASCII extends the standard ASCII character set to
include additional characters, allowing for greater language and symbol support.
Escape Sequences: C provides escape sequences, such as ‘\n’ for a new line and
‘\t’ for a tab, to represent non-printable characters in a program.
Character Constants: In C, character constants are enclosed in single quotes (‘’).
For example, ‘A’ represents the character ‘A’, and ‘5’ represents the character ‘5’.
Character Data Type: The char data type in C is used to store individual characters.
It is typically represented as a single byte in memory.
String: A string in C is a sequence of characters
enclosed in double quotes (“”), such as “Hello, STUDY NOTE
World!”. The null character (‘\0’) marks the end of Studies have shown
a string. that the total number
Tokens are the building blocks of a C program. of tokens in C program
They are the smallest units of code that the has a direct impact
compiler can understand. Tokens are used to on compilation time.
construct statements, which are the basic units As the number of
of execution in a C program. Statements are tokens increases,
made up of one or more tokens, and they are the compilation time
used to perform actions, such as assigning values tends to increase
to variables, calling functions, and printing output. exponentially.

Tokens can be classified into the following categories:

Keywords

Identifiers

Operators

Constants

Special Symbols

Fig 1: Tokens in C Language

Keywords:
Keywords are reserved words in C that have special meaning to the compiler. These
keywords serve specific purposes and play a crucial role in the language’s syntax
and structure.They cannot be used as identifiers, which are names for variables,
functions, and other objects.
11
NOTES auto
default
break
long
float
for
register
signed
typedef
union
case double do sizeof unsigned
char else goto static void
const enum int struct volatile
continue if extern switch

int: The ‘int’ keyword is used to declare variables of type integer.


Syntax: int variableName;
Example: int age;
float: The ‘float’ keyword declares variables of STUDY NOTE
type floating-point (decimal) numbers.
Keywords in C language
Syntax: float variableName; are case-sensitive, so
Example: float height; int is different from INT.
char: The ‘char’ keyword declares variables of
type character.
Syntax: char variableName;
Example: char grade;
if: The ‘if’ keyword is used for conditional statements. It evaluates a condition and
executes a code block if the condition is true.
Syntax:
if (condition) {
// code to be executed if the condition is true
}

Example:
if (age >= 18) {
printf(“You are eligible to vote.”);
}

else: The ‘else’ keyword is used in conjunction with ‘if’ to specify an alternative
code block to execute if the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

Example:
if (score >= 60) {
printf(“You passed the exam.”);
} else {
printf(“You failed the exam.”);
}
12
for: The ‘for’ keyword is used to construct a loop that repeatedly runs a piece of
code a certain number of times.
NOTES
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
for (int i = 0; i < 10; i++) {
printf(“%d\n”, i);
}

while: The “while” keyword is used to create a loop that repeatedly runs a block of
code as long as a given condition is true.
Syntax:
while (condition) {
// code to be executed
}
Example:
while (count > 0) {
printf(“Countdown: %d\n”, count);
count--;
}

Identifiers:
Identifiers in C programming are names used to identify variables, functions, arrays,
structures, and other user-defined entities. An identifier provides a unique name
that can be referenced and used within the program.

An identifier in C follows following rules:


● A letter (a-z, A-Z) or an underscore (_) must be used as the first character.
● A letter, a number (0–9), or an underscore may come after it.
● No reserved keywords should be used.
● Uppercase and lowercase letters are different because of the case-sensitivity.

Examples of valid identifiers:


● count
● studentName
● _result
● MAX_SIZE
● myFunction

Examples of invalid identifiers:


● 123var (starts with a digit)
● break (a reserved keyword)
● my-variable (contains a hyphen)
13
NOTES Guidelines for naming identifiers:
● Use meaningful names that reflect the purpose or meaning of the entity.
● Conventionally, camelCase (e.g., myVariableName) or underscores (e.g., my_
variable_name) are used for multi-word identifiers.
● Identifiers starting with an underscore have special meanings in C and should
be avoided in general.
● It is common to follow specific naming conventions based on the programming
style or guidelines of the organization or community you are programming for.

Constants:
Constants are fixed values that don’t change while a program is running. They serve
as a representation for program-required fixed or immutable data. Various types of
constants are possible, including integers, floating-point values, characters, and
strings.

In C, constants are defined using specific syntax rules based on their data types:

Integer Constants: Whole numbers without a decimal point are known as integer
constants.They can be expressed as decimals, octal numbers with a leading zero,
or hexadecimal numbers with a leading 0x or 0X.

Example:
Decimal: 25
Octal: 031 (equals decimal 25)
Hexadecimal: 0x19 (equals decimal 25)
Floating-Point Constants: Floating-point constants represent numbers with decimal
points. They can be written in decimal notation or scientific notation (using ‘e’ or ‘E’
for exponent).

Example:
Decimal: 3.14
Scientific: 2.5e-3 (equals 0.0025)
Character Constants: Character constants represent individual characters enclosed
in single quotes (‘’).They can be any printable ASCII character or an escape
sequence.

Example:
Character: ‘A’
Escape sequence: ‘\n’ (newline)
String Constants: These are a sequence of characters enclosed in double quotes
(“”).
They can contain multiple characters, including letters, digits, symbols, and escape
sequences.

Example: “Hello, World!”

Example of constant usage in C:

14
#include <stdio.h>
int main() {
NOTES
const int MAX_VALUE = 100; // Integer constant
const float PI = 3.14159; // Floating-point constant
const char GRADE = ‘A’; // Character constant
const char NAME[] = “John”; // String constant
printf(“The maximum value is: %d\n”, MAX_VALUE);
printf(“The value of PI is: %.2f\n”, PI);
printf(“The grade is: %c\n”, GRADE);
printf(“The name is: %s\n”, NAME);
return 0;
}

The program outputs:


The maximum value is: 100
The value of PI is: 3.14
The grade is: A
The name is: John

Operators:
Symbols or special characters known as operators in C programming are used to
conduct operations on operands (variables, constants, or expressions) to create
results. Operands are the data items on which we apply operators. Operators
are applied between operands. Based on the number of operands, operators are
classified into three types:

Unary Operators: Unary operators work with a single operand.

Examples:
● Unary minus (-): Negates the operand’s value. Like: -x
● Unary plus (+): Represents the operand’s value. Like: +x
● Increment (++) and Decrement (--): Increase or decrease the operand’s value
by 1. Like: ++x, --x
● Logical NOT (!): Returns the logical inverse of the operand. Like: !x
● Bitwise complement (~): Flips the bits of the operand. Like: ~x

Binary Operators: Binary operators work with two operands.

Examples:
● Arithmetic operators: Addition (+), Multiplication (*), Division (/), Subtraction
(-), Modulus (%)
● Relational operators: Equal to (==), Greater than (>), Less than (<), Not equal
to (!=), Greater than or equal to (>=), Less than or equal to (<=)
● Logical operators: Logical AND (&&), Logical OR (||)
● Assignment operators: Assignment (=), Compound assignment operators
(+=, -=, *=, /=, %=)

15
NOTES ● Bitwise operators: Bitwise AND (&), Bitwise XOR (^), Bitwise OR (|), Left shift
(<<), Right shift (>>)

Ternary Operator: The ternary operator (?:) is the only ternary operator in C. It takes
three operands and works as a conditional expression.

Syntax:

condition ? expression1 : expression2

If the condition is true, expression1 is evaluated; otherwise, expression2 is


evaluated.

Example: max = (a > b) ? a : b;

Special symbols:
Special symbols are characters that have a specific meaning and purpose within
the language. These symbols are used for various tasks, such as indicating the
beginning or end of a statement, defining data types, performing arithmetic
operations, and more.
● Parentheses (): Used to group expressions, specify function arguments, and
control the order of evaluation.
● Curly Braces {}: Used to define blocks of code and enclose the body of
functions, loops, and conditional statements.
● Square Brackets []: Used for array indexing and declaration.
● Semicolon (;): Used to terminate a statement in C. It indicates the end of an
expression or a command.
● Comma (,): Used to separate multiple expressions or function arguments.
● Ampersand (&): Used for the address-of operator and bitwise AND operation.
● Asterisk (*): Used for the multiplication operator, pointer declaration, and
dereferencing a pointer.
● Hash (#): Used to preprocess directives in C, such as include statements and
macro definitions.
● Double Quotes (“ “): Used for enclosing string literals.
● Single Quotes (‘ ‘): Used for enclosing character literals.
● Period (dot) (.) and Arrow (->): Used for accessing members of structures and
unions.
● Backslash (): Used as an escape character to represent special characters or
sequences in strings or characters.

Variables
In C, variables are used to store and control data while a program is running. A
named place in the computer’s memory where values can be stored and retrieved
is known as a variable.

In C, variables are declared using the following syntax:


data_type variable_name;

16
data_type represents the type of data the variable can hold, such as int, float,
char, etc.variable_name is the identifier given to the variable, which can be any
NOTES
valid name conforming to certain rules.

Examples:
● Integer Variable:
int age; // Declaration of an integer variable named “age”
● Floating-Point Variable:
float pi; // Declaration of a floating-point variable named “pi”
● Character Variable:
char grade; // Declaration of a character variable named “grade”
● String Variable:
char name[20]; // Declaration of a character array variable named “name” to
store a string of maximum 20 characters

Assigning Values to Variables:


After declaring a variable, a value is assigned to it using the assignment operator
‘=’.
age = 25; // Assigning a value of 25 to the variable “age”
pi = 3.14; // Assigning a value of 3.14 to the variable “pi”
grade = ‘A’; // Assigning the character ‘A’ to the variable
“grade”
strcpy(name, “John”); // Assigning the string “John” to the
variable “name”
Accessing Variable Values:
Variable’s value is accessed by simply using its name in expressions or statements:
int x = 10;
int y = 5;
int sum = x + y; // Accessing the values of variables “x” and
“y” and storing their sum in “sum”

CHECK YOUR PROGRESS


11. The _____ character marks the end of a string in C.
12. Constants in C are used to represent fixed or immutable data that remains
_____ during program execution.
13. Escape sequences in C are used to represent printable characters.
(True/False)
14. Alex is using an escape sequence to represent a new line in his C program.
Which escape sequence should he use?
15. What is the term used to describe specific words with predefined meanings
in the C language?
16. What is the name given to the named storage location in the computer’s
memory used for storing data in C?
17. Identifiers in C can start with a digit. [True/False]

17
NOTES Activity
Use online resources to get list of programs or codes written in C Language.
Analyse the code snippets and identify the different types of tokens present,
such as keywords, identifiers, operators, and constants.

2.6
Data Types

Each variable in C has a corresponding data type. The type of data that can be
stored in the variable is determined by its data type. For instance, a floating-point
variable can store numbers with decimal points but an integer variable can only
hold integers. The amount of RAM allocated for the variable is also based on its
data type.

There are a number of operations that can be carried out on each data type. A
collection of data with fixed values, meanings, and features is referred to as a data
type. An essential component of C programming is the data type. The type of data
that can be kept in a variable and the operations that can be carried out on it can
both be specified by the programmer. As a result, the code is easier to comprehend
and more effective.
● int:
Size: 4 bytes (32 bits) on most systems
Information: Stores whole numbers (integers)
Format Specifier: %d for signed integers, %u for unsigned integers
● char:
Size: 1 byte (8 bits)
Information: Stores single characters or small integers
Format Specifier: %c for characters, %d for integer representation
● float:
Size: 4 bytes (32 bits)
Information: Stores single-precision floating-point numbers
Format Specifier: %f for normal display, %e for scientific notation
● double:
Size: 8 bytes (64 bits) on most systems
Information: Stores double-precision floating-point number
Format Specifier: %lf for normal display, %le for scientific notation

18
● short:
NOTES
Size: 2 bytes (16 bits) on most systems.
Information: Stores smaller integers than int.
Format Specifier: %hd for signed short integers, %hu for unsigned short
integers.
● long:
Size: 4 bytes (32 bits) on most systems
Information: Stores larger integers than int
Format Specifier: %ld for signed long integers, %lu for unsigned long integers
● unsigned:
Size: Same as the corresponding signed type
Information: Stores only non-negative integers
Format Specifier: %u for unsigned integers

Comments
Comments in C are lines of code that are ignored by the compiler during the
compilation process. They are used to add explanatory or descriptive text within
the program for better understanding and documentation purposes. Code
readability and other programmers’ ability to grasp the code are greatly enhanced
by comments.

There are two types of comments in C:

Single-Line Comments:
Single-line comments start with // and continue until the end of the line. They are
typically used for short comments or to comment out a single line of code.

Syntax:
// This is a single-line comment

Multi-Line Comments:
Multi-line comments start with /* and end with */. They can span multiple lines
and are often used for longer comments, including explanations of functions,
algorithms, or code sections.

Syntax:
/*
This is a multi-line comment
It can span across multiple lines
*/

CHECK YOUR PROGRESS


18. The ________ data type stores double-precision floating-point numbers.
19. Comments in C are ignored by the compiler during the compilation process.
(True/False)

19
NOTES 2.7
Summary
● The first standardized version of C, known as “ANSI C” or “C89,” was published
by the American National Standards Institute.
● C is known for its efficiency, as it allows low-level programming and direct
access to computer hardware.
● C tokens are the smallest individual units in a C program, including keywords,
identifiers, and constants.
● Keywords in C are reserved words with predefined meanings and cannot be
used as identifiers.
● Identifiers are user-defined names used for variables, functions, and other
elements in a C program.
● Variables in C are named storage locations used to store data during program
execution.
● Constants in C are values that remain unchanged throughout program execution.
● Data types supported by C include arrays, characters, floating-point numbers,
and integers.
● Data types define the size and type of information that can be stored in variables.
● Comments in C are used for code documentation, explanations, and improving
code readability.
● Understanding C tokens and their types is crucial for effective programming
and code comprehension.
● Choosing appropriate identifiers and following naming conventions enhances
code readability and maintainability.
● Variables allow us to store and manipulate data, making programs dynamic and
responsive.
● Constants provide fixed values that remain constant during program execution.
● Data types help in defining the range and precision of values that variables can
hold.
● Comments play a vital role in documenting code logic, providing insights, and
making the code easier to understand and maintain.

20
2.8 NOTES
Case Study
Tally Solutions Pvt. Ltd. and Tally Software Development
Tally Solutions Pvt. Ltd. is an Indian multinational company that specializes in
developing business accounting and inventory management software. The company
was founded in 1986 and is headquartered in Bengaluru, India. Tally Solutions is
widely recognized for its flagship product, Tally.ERP 9, which is a comprehensive
business management software solution used by businesses of all sizes across
various industries.
The development of Tally software heavily relies on the use of the C programming
language. C is known for its efficiency, portability, and low-level control, making it
a suitable choice for system-level programming tasks. Tally software incorporates
complex algorithms and data structures to handle financial accounting, inventory
management, taxation, payroll processing, and more.

Key Features and Functionality:


1. Data Management: Tally software utilizes C language to manage and manipulate
large volumes of financial and business data efficiently. This includes storing
and retrieving data, performing calculations, and generating reports.
2. Performance Optimization: The C language allows developers at Tally
Solutions to optimize the performance of the software. By leveraging C’s low-
level control and memory management capabilities, they can fine-tune critical
sections of the code to enhance speed and responsiveness.
3. Platform Compatibility: The platform independence of C, which enables
Tally applications to operate on many operating platforms including Windows,
Linux, and macOS. This flexibility enables businesses to choose their preferred
operating system while using Tally for their accounting needs.
4. Integration with External Systems: Tally software integrates with external
systems such as banks, payment gateways, and other software applications.
The use of C language facilitates seamless communication and data exchange
between different systems, ensuring smooth integration and interoperability.
Tally Solutions’ innovative use of the C language in developing Tally software has
contributed to its widespread adoption and success. The software has become
a leading choice for businesses across India and globally, streamlining their
accounting processes and improving overall financial management.

QUESTIONS:
1. Considering the case study of Tally Solutions Pvt. Ltd. and the development of
Tally software using the C language, discuss the advantages and disadvantages
of using C for such a complex software application. How does the choice of
C language impact the performance, portability, and maintenance of Tally
software? Provide examples and insights to support your analysis.
21
NOTES 2. In the case of Tally Solutions Pvt. Ltd., the C language played a crucial role
in the development of Tally software, enabling efficient data management,
performance optimization, and platform compatibility. However, technology
evolves rapidly, and new programming languages and frameworks emerge.
Considering this, discuss the potential challenges and opportunities Tally
Solutions might face in the future regarding the continued use of C language
for Tally software development. Analyze the feasibility of adopting newer
programming languages or frameworks and assess the potential impact on
Tally software’s competitiveness, scalability, and future growth in the evolving
business software market.

2.9
Terminal Questions
SHORT ANSWER QUESTIONS
1. What is the purpose of using header files in a C program?
2. Explain the significance of a well-structured C program. How does a proper
program structure enhance code readability, maintainability, and reusability?
3. Explain the impact of data types on memory utilization and program execution.

LONG ANSWER QUESTIONS


1. Evaluate the characteristics and advantages of C as a procedural programming
language, highlighting its suitability for various applications and development
environments.
2. Discuss the role and significance of preprocessor directives as tokens in the
C programming language. Explain how preprocessor directives contribute to
program functionality, code organization, and compilation process.

MULTIPLE CHOICE QUESTIONS


1. What year was the first standardized version of C, known as “ANSI C” or “C89,”
published?
a) 1972 b) 1989
c) 1995 d) 2003
2. Which programming language was the predecessor to C?
a) Assembly language
b) B language c) BCPL language
d) Basic language3. Which of the following is NOT a section of
a C program?
a) Preprocessor directives b) Function definitions
c) Main function d) Local variables
22
4. In C programming, what is the purpose of the main function?
NOTES
a) It is the first function to be executed in a program.
b) It is responsible for defining global variables.
c) It is used for including header files.
d) It is a user-defined function.
5. Which of the following is an example of a user-defined function?
a) printf() b) scanf()
c) main() d) calculateAverage()
6. Which of the following is NOT a basic data type in C?
a) int b) float
c) char d) boolean
7. What is the size of the int data type in C?
a) 4 bytes b) 2 bytes
c) 8 bytes d) It varies depending on the system
8. Which of the following is a valid way to define a constant in C?
a) const constant_name; b) #define constant_name;
c) constant constant_name; d) constant_name = value;
9. Which of the following is a valid C token?
a) 123.45 b) for
c) “Hello, World!” d) main()
10. What is the purpose of comments in C programming?
a) To execute a specific block of code
b) To provide documentation and explanations within the code
c) To define keywords and identifiers
d) To declare variables
11. Which keyword is used to declare a variable in C?
a) int b) variable
c) define d) allocate
12. Which of the following is a valid identifier in C?
a) 123abc b) _variable
c) constant-name d) while
13. How many characters can be used as an identifier in C at most?
a) 10 b) 20
c) 30 d) There is no maximum limit
14. Which of the following is a valid variable declaration in C?
a) variable = 10; b) int variable;
c) variable int; d) declare variable;

23
NOTES 15. Which data type is used to store single characters in C?
a) char b) int
c) float d) double

2.10
Answers

CHECK YOUR PROGRESS


1. Bell 10. To be solved by student
2. American National Standards 11. Null
Institute (ANSI) 12. Unchanged
3. True 13. False
4. False 14. To be solved by student
5. True 15. To be solved by student
6. True 16. To be solved by student
7. False 17. False
8. stdio.h 18. Double
9. strlen() 19. True

SHORT ANSWER QUESTIONS


1. Header files in C contain function prototypes, definitions, and declarations
necessary for program execution. They provide information about functions and
libraries used in the program, enabling proper compilation and linking of the
program.
2. 2. A well-structured C program follows a clear hierarchy, which enhances
the readability and comprehension of the code. By dividing the code into
logical sections and functions, it becomes simpler to maintain and debug.
Code modularity is encouraged by a sound program structure, which enables
developers to reuse modules and functions across various program components
or in other programs. It also enhances collaboration among team members by
providing a clear framework for code organization. Additionally, a well-structured
program adheres to coding standards, leading to consistent and maintainable
codebases.
3. Data types affect memory utilization and program execution. Smaller types
use less memory and can be faster due to better cache use. Type conversions
and memory allocation impact speed. Choose types carefully to optimize both
memory and execution efficiency.

24
LONG ANSWER QUESTIONS
NOTES
1. C is widely recognized as a procedural programming language and has been
extensively used in various domains due to its distinctive characteristics and
advantages. Procedural programming follows a top-down approach, where
the program is divided into smaller modules or functions that perform specific
tasks. Here, we will evaluate the key characteristics and advantages of C as a
procedural language.
● Modular Approach: Modular programming in C makes it possible to
separate complicated programs into more manageable modules or
functions. The specified tasks carried out by each function encourage the
reuse and maintainability of the code. The overall quality of the code is
improved through modular programming, which improves code organization
and makes it simpler to find and fix errors.
● Efficiency and Performance: C is known for its efficiency and performance.
It provides direct access to memory, allowing low-level manipulation and
fine-grained control over hardware resources. C programs can be optimized
for speed and memory usage, making it suitable for developing applications
that require efficient algorithms, system-level programming, and real-time
processing.
● Portability: C is a highly portable language, allowing programs written in C
to be compiled and run on different platforms and operating systems. This
portability is due to the availability of C compilers for various architectures.
As a result, C programs can be easily migrated across different hardware
and software environments, making it a versatile choice for cross-platform
development.
● Extensive Standard Library: C provides an extensive standard library that
includes a wide range of functions for common tasks, such as input/output
operations, string manipulation, memory allocation, and mathematical
operations. This library simplifies development by providing pre-built
functionality, reducing the need for developers to reinvent the wheel.
● Proximity to Hardware: C allows direct access to hardware resources,
such as memory locations, peripherals, and registers. This proximity makes
it suitable for developing device drivers, embedded systems, and low-
level programming. C’s ability to interface with assembly language further
enhances its capability to interact with hardware at a low level.
● Large Community and Support: C has a large and active community
of developers, which means ample support and resources are available.
Numerous books, online forums, tutorials, and code examples exist, making
it easier for developers to learn, share knowledge, and seek assistance
when needed.
● Integration with Other Languages: C can easily interface with other
languages like C++, Java, and Python. This feature enables developers
to combine the efficiency and low-level control of C with the high-level
functionalities of other languages. C’s compatibility and ability to integrate
with different programming languages make it a preferred choice for building
software systems that require diverse language support.
25
NOTES 2. Preprocessor directives are an essential component of the C programming
language and serve as tokens that play a vital role in program functionality,
code organization, and the compilation process. Understanding the role and
significance of preprocessor directives is crucial for developing efficient and
well-structured C programs.
● Functionality: Preprocessor directives enable conditional compilation,
macro expansion, and file inclusion in a C program. They provide a means
to include or exclude specific blocks of code based on defined conditions.
For example, the #ifdef and #endif directives allow conditional compilation,
where a particular section of code is compiled only if a specific condition
is met. This feature enhances program flexibility and allows developers to
tailor program behavior based on different scenarios.
● Code Organization: Preprocessor directives contribute to code organization
by allowing the inclusion of header files using the #include directive.
Header files contain function prototypes, macro definitions, and other
necessary declarations. By including relevant header files, code modularity
and reusability are enhanced, as common code segments can be stored in
separate files and included wherever needed. This practice promotes code
readability, reduces redundancy, and simplifies maintenance.
3. Compilation Process: Preprocessor directives are evaluated by the
preprocessor, which operates before the actual compilation of the C program.
The directives guide the preprocessor in performing specific tasks such as file
inclusion, macro substitution, and conditional compilation. They help in resolving
dependencies, checking for library dependencies, and ensuring the correct
inclusion of required files. The preprocessor directives ensure that the code
is prepared for compilation with proper dependencies resolved and necessary
definitions in place.

MULTI CHOICE QUESTIONS


1. b) 1989
2. b) B language
3. d) Local variables
4. a) It is the first function to be executed in a program.
5. d) calculateAverage()
6. d) boolean
7. d) It varies depending on the system
8. b) #define constant_name;
9. d) main()
10. b) To provide documentation and explanations within the code
11. a) int
12. b) _variable
13. d) There is no maximum limit
14. b) int variable;
15. a) char
26
2.11 NOTES
Assignment

MULTIPLE CHOICE QUESTIONS


1. What is the purpose of the “const” keyword in C?
a) To define a constant variable
b) To declare a variable with a constant value
c) To allocate memory for a variable
d) To convert data types
2. Which of the following is NOT a valid format specifier in C?
a) %d b) %f
c) %c d) %x
3. Which of the following is a valid example of a single-line comment in C?
a) /* This is a comment */ b) # This is a comment
c) // This is a comment d) ** This is a comment **
4. Which of the following is a valid example of a multi-line comment in C?
a) /* This is a comment */ b) # This is a comment
c) // This is a comment d) ** This is a comment **
5. Which of the following is NOT a valid preprocessor directive in C?
a) #include b) #define
c) #function d) #ifdef

QUESTIONS
1. Explain the importance of modular programming and its impact on the structure
of a C program. Provide examples to illustrate how modular programming
enhances code organization, reusability, and maintainability.
2. Describe constants in C programming and their role in representing fixed
values. Differentiate between numeric constants, character constants, and
string literals.
3. You are developing a weather monitoring system using C. You need to store
temperature readings, rainfall amounts, wind speeds, and humidity levels.
Determine the appropriate data types for each variable based on their
characteristics and requirements.
4. Describe the difference between a signed and an unsigned data type in C
programming? Give an example of each.
5. Why is the selection of appropriate data types crucial in C programming?
Discuss the impact of choosing an incorrect data type for a variable.

27
NOTES 2.12
References

Books:
● “C Programming Language” by Brian W. Kernighan and Dennis M. Ritchie
● “C Programming Absolute Beginner’s Guide” by Greg Perry and Dean Miller

Web References:
● https://www.programiz.com/c-programming
● https://www.geeksforgeeks.org/tokens-in-c/
● http://www.btechsmartclass.com/c_programming/C-Creating-and-Running-C-
Program.html
● https://www.studytonight.com/c/identifiers-in-c.php

28

You might also like