0% found this document useful (0 votes)
8 views

Unit 1-1

Uploaded by

josephusjohn009
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 1-1

Uploaded by

josephusjohn009
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

Established as per the Section 2(f) of the UGC Act, 1956

Approved by AICTE, COA and BCI, New Delhi

B24CI0109: Fundamentals of C
Programming

School of Computer Science and Engineering

D r. N e e l a m M a l y a d r i

AY: 2024-2025 (ODD)


B24CI0109: Fundamentals of C
Programming
1 s t S e m e s t e r. A c a d e m i c Ye a r : 2 0 2 4 -
2025.

Syllabus--
Introduction
SYLLABUS-- INTRODUCTION
SYLLABUS – INTRODUCTION -- OBJECTIVES
The objectives of this course are to:

1) Understand the basic structure and history of the C programming language, and set up
an environment to execute simple programs.

2) Write programs in modules using functions and recursive calls to achieve modularity

3) Understand and utilize concepts of arrays and pointers to write efficient programs.

4. Memory management: Effectively use the memory management system to achieve


minimal compilation and execution time.

5. Use algorithms and flowcharts as fundamental tools for problem-solving in C


programming.
SYLLABUS – INTRODUCTION -- COURSE
OUTCOMES(CO’S)
After the completion of the course, the student will be able to:

CO1-Understand the foundational concepts of the C language, including its history and basic
building blocks.

CO2-Utilize conditional and unconditional control flow statements to write efficient programs.
CO3-Understand strings and library functions on strings.

CO4-Apply functions and recursive function calls to achieve modularity.

CO5-Manipulate pointers to write efficient programs.

CO6-Explore command line functionalities to control programs from command prompt.


SYLLABUS – INTRODUCTION – IN BRIEF……………

1. INTRODUCTION TO C PROGRAMMING:

OVERVIEW OF C LANGUAGE, STRUCTURE OF A C PROGRAM,


COMPILATION AND EXECUTION, BASIC SYNTAX AND SEMANTICS,
VARIABLES AND DATA TYPES, CONSTANTS AND LITERALS AND INPUT
AND OUTPUT OPERATIONS

2. BUILDING BLOCKS OF C:
ARITHMETIC OPERATORS, RELATIONAL OPERATORS, LOGICAL
OPERATORS, BITWISE OPERATORS, ASSIGNMENT OPERATORS,
CONDITIONAL OPERATOR, PRECEDENCE AND ASSOCIATIVITY OF
OPERATORS AND TYPE CONVERSION
SYLLABUS – INTRODUCTION – IN BRIEF

3. CONTROL STATEMENTS:
DECISION MAKING WITH IF AND IF-ELSE, NESTED IF-ELSE
STATEMENTS, SWITCH CASE STATEMENTS,
LOOPING CONSTRUCTS: FOR, WHILE, AND DO-WHILE LOOPS,
NESTED LOOPS, BREAK AND CONTINUE STATEMENTS AND GOTO
STATEMENT AND LABELS

4.FUNCTIONS:
DEFINING AND CALLING FUNCTIONS, FUNCTION PROTOTYPES,
SCOPE AND LIFETIME OF VARIABLES, PASSING ARGUMENTS TO
FUNCTIONS, RETURN VALUES AND RECURSIVE FUNCTIONS
SYLLABUS – INTRODUCTION – IN BRIEF

5. ARRAYS & STRINGS: ONE-DIMENSIONAL ARRAYS,


MULTIDIMENSIONAL ARRAYS, ARRAY INITIALIZATION AND
MANIPULATION.
STRINGS AND STRING FUNCTIONS AND ARRAY OF STRINGS,
MATRIX OPERATIONS USING 2-DIMENSIONAL ARRAYS.

6. POINTERS: UNDERSTANDING POINTERS, POINTER


ARITHMETIC, POINTERS AND ARRAYS, POINTERS AND STRINGS,
POINTERS TO FUNCTIONS, POINTERS AND DYNAMIC MEMORY
ALLOCATION.
INTRODUCTION TO STRUCTURES AND UNIONS.
SYLLABUS INTRODUCTION – TEXT BOOKS:

1. HERBERT SCHILDT, “C: THE COMPLETE REFERENCE”, 4TH EDITION, TATA


MCGRAW HILL, 2000.

2. B.W. KERNIGHAN & D.M. RITCHIE, "C PROGRAMMING LANGUAGE", 2ND


EDITION, PRENTICE HALL SOFTWARE SERIES, 2005.

3. B.S. ANAMI, S.A. ANGADI AND S. S. MANVI, “COMPUTER CONCEPTS AND C


PROGRAMMING: A HOLISTIC APPROACH”, SECOND EDITION, PHI,2008.

4. YASHAVANT KANETKAR, “LET US C” , BPB , 19TH EDITION, 2022


Basic Concepts Before Moving in to
Programming With C Contents
Basic Concepts

Program

Software and its types

Algorithm

Flowcharts
PROGRAM - DEFINITION
A computer program is a
sequence or set of A computer program in
instructions in a its human-readable form
programming language for is called source code.
a computer to execute.

Source code needs another computer


program to execute because computers
can only execute their native machine
instructions.
PROGRAM – SOME OF THE EXAMPLES

Web Browsers Operating Systems Office Suite Programs

Video Games
SOFTWARE - DEFINITIONinstructions,
Software is a set of
data or
programs used to
operate computers and
execute specific tasks.
Software helps a
It is the opposite of
business organization
hardware, which
to cut costs by
describes the physical
automating routine
aspects of a
tasks.
computer.

SOFTWARE
Software not only makes
your computer hardware Software is a generic
perform important tasks, term used to refer to
but can also help your applications, scripts &
business work more programs that run on a
efficiently. device.
It can be thought of as
the variable part of a
computer, while
hardware is the
invariable part.
SOFTWARE – TYPES

Application software (App) is a kind of


software that performs specific functions for
the end user by interacting directly with it.
The sole purpose of application software is to
aid the user in doing specified tasks.
System software is a type of computer
program that is designed to run a computer's
hardware and application programs.
APPLICATION SOFTWARE & SYSTEM SOFTWARE– SOME OF THE
EXAMPLES
Algorithm
Importance of Algorithm
ALGORITHM - DEFINITION

Simple Definition of Algorithm


as follows:
Step by step solving the given
problem.
A Step by step solution for a
specific mathematical or
computer related problem
IMPORTANT CHARACTERISTICS OF AN
ALGORITHM

Language
Unambiguity Fineness Effectiveness
Independence
GENERAL STRUCTURE OF AN ALGORITHM

Typical Structure of An Algorithm


ADVANTAGES OF WRITING AN ALGORITHM

It is a step-wise representation of a solution to a given problem, which


makes it easy to understand.

An algorithm uses a definite procedure.

It is not dependent on any programming language, so it is easy to


understand for anyone even without programming knowledge.
ADVANTAGES OF WRITING AN ALGORITHM

Every step in an algorithm has its own logical sequence so it is


easy to debug.

By using algorithm, the problem is broken down into smaller


pieces or steps hence, it is easier for programmer to convert it
into an actual program.
EXAMPLES OF AN ALGORITHM
1. Write an algorithm to find the
FLOW CHART
Importance of Flowchart
FLOWCHART – AN INTRODUCTION
• Flowchart is a • The process of • Programmers
graphical drawing a flowchart often use it as a
for an algorithm is
representation of known as program-planning
an algorithm. “flowcharting”. tool to solve a
problem.

Flowchart Flowchart Flowchart

• It makes use of
symbols which are
connected among
them to indicate the
flow of information
and processing.

Flowchart
NOTATIONS USED TO DRAW A FLOW CHART

START / STOP DECISION / CONDITION

INPUT / OUTPUT CONNECTOR

PROCESS / COMPUTE PREDFINED PROCESS


ADVANTAGES OF DRAWING THE FLOWCHART
Communication: Flowcharts are better way of
communicating the logic of a system to all concerned or
involved.

Effective analysis: With the help of flowchart, problem can

ADVANTAGES OF
be analysed in more effective way therefore reducing cost
and wastage of time.

FLOWCHART
Proper documentation: Program flowcharts serve as a good
program documentation, which is needed for various
purposes, making things more efficient.

Efficient Coding: The flowcharts act as a guide or blueprint


during the systems analysis and program development phase.

Proper Debugging: The flowchart helps in debugging process.


EXAMPLE 1 : ADDITION OF TWO NUMBERS
EXAMPLE 2 : CALCULATE THE PROFIT AND LOSS
EXAMPLE 3 : FIND THE LARGEST AMONG 3 NUMBERS
EXAMPLE 4 : FIND THE ROOTS OF QUADRATIC EQUATION
Established as per the Section 2(f) of the UGC Act, 1956
Approved by AICTE, COA and BCI, New Delhi

Unit 1
INTRODUCTION TO C PROGRAMMING

School of Computer Science and Engineering

D r. N e e l a m M a l y a d r i

AY: 2024-2025 (ODD)


UNIT 1: SYLLABUS

1. Introduction to C Programming:
Overview of C language, Structure of a C program,
Compilation and execution, Basic syntax and semantics,
Variables and data types, Constants and literals and Input
and output operations
Overview of C language
PROGRAMMING LANGUAGES : AN INTRODUCTION
To write a program (tells what to do) for a computer, we must use a computer language.
Over the years computer languages have evolved from machine languages to natural languages.
The following is the summary of computer languages
PROGRAMMING LANGUAGES : AN INTRODUCTION
Machine Language

In the earliest days of The instructions in


Each computer has its
computers, the only machine language These are so named as
own machine
programming must be in streams of the machine can
language which is
languages available 0s and 1s. This is also directly understood
made of streams of 0s
were machine referred as binary the programs.
and 1s.
languages. digits.
PROGRAMMING LANGUAGES : AN INTRODUCTION
Advantages of Machine Language

High speed execution The computer can No translation is needed.


understand instruction
immediately
PROGRAMMING LANGUAGES : AN INTRODUCTION
Disadvantages of Machine Language

Machine dependent Programming is very


Difficult to write bug free programs
difficult
PROGRAMMING LANGUAGES : AN INTRODUCTION
Symbolic Languages (or) Assembly Language
These early programming
In the early 1950s, Admiral Grace
languages simply mirrored the
Hopper, a mathematician and
machine languages using symbols
naval officer, developed the
or mnemonics to represent the
concept of a special computer
various language instructions.
program that would convert
These languages were known as
programs into machine language.
symbolic languages.

A special program called an


Because a computer does not
Assembler translates symbolic
understand symbolic language it
code into the machine language.
must be translated into the
Hence they are called as
machine language.
Assembly language.
PROGRAMMING LANGUAGES : AN INTRODUCTION
PROGRAMMING LANGUAGES : AN INTRODUCTION
ADVANTAGES AND DISADVANTAGES OF ASSEMBLY OR SYMBOLIC LANGUAGE

Advantages Disadvantages

Easy to It requires the


understand, translator and
modify, and use more development
the code time required

High efficiency and Very difficult to


more control on learn and write the
code code
PROGRAMMING LANGUAGES : AN INTRODUCTION
High-Level Languages
The symbolic languages greatly improved
programming efficiency they still required
programmers to concentrate on the
hardware that they were using working with
symbolic languages was also very tedious
because each machine instruction had to be
individually coded.

The desire to improve programmer efficiency and to change the focus the
computer to the problems being solved led to the development of high-level
languages.

High-level languages are portable to many different computer allowing the programm
to concentrate on the application problem at hand rather than the intricacies of the
computer.
PROGRAMMING LANGUAGES : AN INTRODUCTION
Language Translators
These are the special programs which are used for converting the programs in one language into
machine language instructions, so that they can be executed by the computer.

Compiler: It is a program which is used to convert the high level language


programs into machine language

Assembler: It is a program which is used to convert the assembly level


language programs into machine language

Interpreter: It is a program, it takes one statement of a high level


language program, translates it into machine language instruction and
then immediately executes the resulting machine language instruction
and so on.
PROGRAMMING LANGUAGES : AN INTRODUCTION
Comparison between a Compiler and Interpreter
Introduction to C Programming
Language
C PROGRAMMING LANGUAGE : AN INTRODUCTION

1. C is a general-purpose high level language that was originally developed by


Dennis Ritchie for the Unix operating system.
2. It was first implemented on the Digital Equipment Corporation PDP-11
computer in 1972 at BELL Laboratories of AT&T Labs.
3. The Unix operating system and virtually all Unix applications are written in the
C language.
4. It is a very popular programming language, despite being old.
5. C is very fast, compared to other programming languages, like Java and Python.
6. C was originally developed for UNIX operating system to beat the issues of
previous languages such as B, BCPL, etc.
C PROGRAMMING LANGUAGE : AN INTRODUCTION
C has become a widely used professional language for the following various reasons.

C language is
very easy to
Learn

C language can
be compiled on Easy to write a
variety of program code
computers

Reasons for using


C language

C language can C is a
handle low- structured
level activities language

C produces the
efficient
programs
C PROGRAMMING LANGUAGE : AN INTRODUCTION
C PROGRAMMING LANGUAGE : AN INTRODUCTION
CREATING AND RUNNING PROGRAMS

The following are the four steps in this process:

1) Writing and Editing the program

2) Compiling the program

3) Linking the program with the required modules

4) Executing the program


C PROGRAMMING LANGUAGE : AN INTRODUCTION
BASIC STRUCTURE OF C PROGRAMMING
C PROGRAMMING LANGUAGE : AN INTRODUCTION
BASIC STRUCTURE OF C PROGRAMMING
Section Description

Documentation Consists of the description of the program, programmer's name, and creation date. These are
generally written in the form of comments.

Link All header files are included in this section which contains different functions from the
libraries. A copy of these header files is inserted into your code before compilation.

Definition Includes preprocessor directive, which contains symbolic constants. E.g.: #define allows us to
use constants in our code. It replaces all the constants with its value in the code.
Global Includes declaration of global variables, function declarations, static global variables, and
Declaration functions.

Main() Function For every C program, the execution starts from the main() function. It is mandatory to
include a main() function in every C program.

Includes all user-defined functions (functions the user provides). They can contain the inbuilt
Subprograms functions and the function definitions declared in the Global Declaration section. These are
called in the main() function.
C PROGRAMMING LANGUAGE : AN INTRODUCTION
BASIC STRUCTURE OF C PROGRAMMING

Preprocessor directives For example, #define is the directive


are lines in your program that that defines a macro. Whitespace is
also allowed before and after the #.
start with # . The # is followed For better readability, a
by an identifier that is the preprocessor directive should start
directive name. in the first column.

INTRODUCTION TO PREPROCESSOR DIRECTIVES


To execute a preprocessor program on a certain statement, some of the preprocessor directives types are:
#define: It substitutes a preprocessor using macro.
#include: It helps to insert a certain header from another file.
#error : It can be performed to stop compilation.
#warning : It is performed to continue compilation with messages in the console window.
C PROGRAMMING LANGUAGE : AN INTRODUCTION
BASIC STRUCTURE OF C PROGRAMMING
INTRODUCTION TO COMMENTS IN C PROGRAM

• In programming, Comments are hints


that a programmer can add to make Types of
their code easier to read and Comments
understand.
• Comments can be used to explain
code, and to make it more readable.
• It can also be used to prevent
Single Line Multi Line
execution when testing alternative Comment Comments
code. A single-line The Multi-line comment in C starts
comment in C starts with a forward slash and asterisk
( /* ) and ends with an asterisk and
with ( // ) double
forward slash ( */ ). Any text
forward slash. It between /* and */ is treated as a
extends till the end of comment and is ignored by the
the line and we don’t compiler. It can apply comments to
need to specify its end. multiple lines in the program.
C PROGRAMMING LANGUAGE : AN INTRODUCTION
BASIC STRUCTURE OF C PROGRAMMING - Example
/** //Documentation
* file: age.c
* author: you
* description: program to find our age.
*/
#include <stdio.h> //Link
#define BORN 2000 //Definition
int age(int current); //Global Declaration
int main(void) //Main() Function
{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}
int age(int current)
{ //Subprograms
return current - BORN;
C PROGRAMMING LANGUAGE : AN INTRODUCTION
PROCESS OF COMPILING AND RUNNING C PROGRAM

The steps involved in


Creating and Running
Programs are:
1. Writing and Editing
Programs
2. Compiling Programs
3. Linking Programs
4. Executing Programs
C TOKENS
TOKENS IN C LANGUAGE
Just like we can't create a meaningful sentence without using words, we can't imagine a human body without
living cells similarly, we can't develop or construct a C program without using tokens in C. Tokens in C
language are the smallest elements or the building blocks used to construct a C program.

C tokens are the


basic buildings Each and every
blocks in C smallest individual
language which unit in a C program
are constructed is known as C
together to write a tokens.
C Program.

C Tokens are the


C tokens are of six
basic component
types.
of C Program.
TOKENS IN C LANGUAGE
The following 6 types of tokens are
available:
1. Identifiers
2. Keywords
3. Constants
4. Operators
5. Special Characters
6. Strings
TOKENS IN C LANGUAGE – 1. IDENTIFIERS

1 2
Identifiers in C are short and informative Each program element in a C program is
called an identifier. An identifier is a variable
names that uniquely identify variables or
that holds a value and stores it in the
function names. memory.

Identifiers

These can be composed of lowercase


These are user-defined words used letters, uppercase letters, underscore
for naming of functions, variables, or digits, but the first character should
structures, unions, arrays etc. be either an underscore or an
alphabet.
3
4
TOKENS IN C LANGUAGE – 1. IDENTIFIERS
There are some defined rules in C language for declaring identifiers:

Identifiers shouldn't begin


with any numerical digit and
hence, the first character
must be either an
underscore or an alphabet.
TOKENS IN C LANGUAGE – 1. IDENTIFIERS

Some Valid Identifiers:


reva, _reva, ferrari123, ferrari_123, count1_, Double

Some invalid identifiers:

100reva //started with a numerical digit


_hello,morning //can't use comma operator
int //keyword
float //keyword
Delhi(100) //circular brackets can't be used
TOKENS IN C LANGUAGE – 2. KEYWORDS
Keywords are words Keywords in C Their meaning and

KEYWORDS

KEYWORDS

KEYWORDS
whose meaning has language are the functionality are
already been defined collection of pre- already known to the
by the computer – defined or reserved compiler. Each
they are pre-defined words. These are Keyword is meant to
words in the C case-sensitive and perform a specific
compiler. written in lower function in a C
cases. program.

We can't use these keywords as variable


names or function names because by
doing so, we are trying to assign a new
meaning to the keyword, which is not
allowed in C language.
TOKENS IN C LANGUAGE – 2. KEYWORDS
There are a total of 32 keywords supported by the C language:
TOKENS IN C LANGUAGE – 2. KEYWORDS
Example:
Here, we are using int, char and auto keywords. We can simply use auto keyword to
deduce the data type of any variable.
In this example, instead of using int and character array, we can just use auto keyword
which will automatically identify the data type for storage purposes.

int num = 10; //int keyword


char univ[10] = “REVA"; //char keyword

These two lines can be modified as: (without knowing the data-type)
auto num = 10; //auto keyword is used to deduce the data type of a variable
auto univ= “REVA";
TOKENS IN C LANGUAGE – 3. CONSTANTS

• Constant is basically a value of a variable that


does not change throughout a program.
CONSTANTS • The constants remain the same, and we cannot
change their value whatsoever.
• Constants are also known as literals.

• The nature of the constant is that the variables whose


values are fixed and can not be modified during the

CONSTANTS
execution of a program once they are defined.
• The constant variables in C can be initialized only
once and their default value is zero. If we try to re-
initialize or re-define any constant variable, then we
will get a compilation error.
TOKENS IN C LANGUAGE – 3. CONSTANTS
We can declare constants in C language in the following ways:
By using a const keyword
By using a #define pre-processor
1. Using const keyword
const keyword Here, we are using the const keyword to declare a variable and assigning a value to
it that can not be modified later.

2. Using #define preprocessor


#define pre-processor Here, we are using #define pre-processor and constant will be an alias-
name for long keyword.
TOKENS IN C LANGUAGE – 3. CONSTANTS
TYPES OF CONSTANTS IN C LANGUAGE
Constant Example

Integer constant 10, 20, 30 etc.

Floating-point constant 10.2, 20.5, 30.6 etc.

Octal constant 011, 022, 088 etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'x', 'y', 'z' etc.

String constant "Java", "C++", "Python" etc.


TOKENS IN C LANGUAGE – 3. CONSTANTS
Integer Constants Floating-point constants Character constants String Constants

• These are constants • These are constants • These are constants • These are constants
that represent integer that represent real that represent single that represent a
values. They can be numbers with a characters enclosed in sequence of
represented in fractional part. They single quotes. characters enclosed in
decimal, octal, or can be written in • For example, the double quotes.
hexadecimal notation. decimal or character constant 'A' • For example, the
• For example, the exponential notation. represents the string constant "Hello,
decimal integer • For example, the character A. world!" represents
constant 42 can be floating-point the sequence of
written as 42, the constant 3.14159 can characters Hello,
octal integer constant be written as 3.14159, world!.
42 can be written as and the floating-point
052, and the constant 1.23 x 10^4
hexadecimal integer can be written as
constant 42 can be 1.23e4.
written as 0x2A.
TOKENS IN C LANGUAGE – 3. CONSTANTS

#include <stdio.h>
int main() {
const int NUM = 10;
const float PI = 3.14159;
const char LETTER = 'A';
const char *MESSAGE = "Hello, world!"; OUTPUT
printf("Integer constant: %d\n", NUM);
printf("Floating-point constant: %f\n", PI);
printf("Character constant: %c\n", LETTER);
printf("String constant: %s\n", MESSAGE);
return 0;
}
TOKENS IN C LANGUAGE – 4. OPERATORS

Expressions
In programming, an expression is a combination of one or more
constants, variables, operators, and function calls that can be
evaluated to produce a single value. Expressions can be used in
various programming constructs, such as assignments, function calls,
conditional statements, and loops.

In C programming language, operators are symbols that are used to perform various
mathematical, logical and decision making operations on variables and constants. Operators in
C can be categorized into several different groups.
TOKENS IN C LANGUAGE – 4. OPERATORS
Types Description
Arithmetic Operators These operators are used to perform mathematical operations such as addition, subtraction,
multiplication, division, and modulus. The arithmetic operators in C are + (addition), - (subtraction),
* (multiplication), / (division), and % (modulus).

Relational Operators These operators are used to compare two values and return a boolean value (true or false)
depending on the result of the comparison. The relational operators in C are == (equal to), != (not
equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal
to).

Logical Operators These operators are used to perform logical operations such as AND, OR, and NOT. The logical
operators in C are && (AND), || (OR), and ! (NOT).

Assignment Operators These operators are used to assign values to variables. The assignment operators in C are = (simple
assignment), += (add and assign), -= (subtract and assign), *= (multiply and assign), /= (divide and
assign), and %= (modulus and assign).

Bitwise Operators These operators are used to perform bit-level operations such as bitwise AND, bitwise OR, and
bitwise NOT. The bitwise operators in C are & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~
(bitwise NOT), << (left shift), and >> (right shift).
Conditional Operator This is a ternary operator that is used to evaluate a condition and return one of two values based
on the result of the evaluation. The conditional operator in C is ? : (ternary conditional operator).
TOKENS IN C LANGUAGE – 4. OPERATORS
#include <stdio.h>
int main() { // Relational operators
int a = 5, b = 2; printf("a == b : %d\n", a == b);
float c = 7.5, d = 2.0; printf("a != b : %d\n", a != b);
// Arithmetic operators printf("c > d : %d\n", c > d);
printf("c < d : %d\n", c < d);
printf("a + b = %d\n", a + b);
printf("a >= b : %d\n", a >= b);
printf("a - b = %d\n", a - b); printf("a <= b : %d\n", a <= b);
printf("a * b = %d\n", a * b); // Logical operators
printf("a / b = %d\n", a / b); printf("(a == b) && (c > d) : %d\n", (a == b) && (c > d));
printf("c + d = %f\n", c + d); printf("(a != b) || (c < d) : %d\n", (a != b) || (c < d));
printf("c - d = %f\n", c - d); printf("!(a == b) : %d\n", !(a == b));
printf("c * d = %f\n", c * d); // Bitwise operators
printf("c / d = %f\n", c / d); printf("a & b : %d\n", a & b);
// Increment and decrement operators printf("a | b : %d\n", a | b);
printf("a ^ b : %d\n", a ^ b);
printf("a++ = %d\n", a++);
printf("~a : %d\n", ~a);
printf("a = %d\n", a); printf("a << 1 : %d\n", a << 1);
printf("++b = %d\n", ++b); printf("b >> 1 : %d\n", b >> 1);
printf("b = %d\n", b); return 0;
}
TOKENS IN C LANGUAGE – 5. SPECIAL CHARACTERS
In C programming, there are certain special characters that have special meanings and are used to represent control characters,
escape sequences, and other special characters in strings and character literals. These special characters are represented by
escape sequences, which are combinations of the backslash character ‘\’ followed by a special code.

Here are some of the commonly used special characters in C programming:


\n - newline character: This character is used to represent a new line in a string or character literal.
When this character is encountered, the cursor moves to the beginning of the next line.
\t - tab character: This character is used to represent a tab in a string or character literal. When this
character is encountered, the cursor moves to the next tab stop.
\\ - backslash character: This character is used to represent a backslash in a string or character literal.
\" - double quote character: This character is used to represent a double quote in a string or character
literal.
\' - single quote character: This character is used to represent a single quote in a character literal.
\a - alert or bell character: This character produces an audible or visible alert.
\b - backspace character: This character moves the cursor back one position.
\r - carriage return character: This character moves the cursor to the beginning of the current line.
\f - form feed character: This character moves the cursor to the next page or form.
\v - vertical tab character: This character moves the cursor to the next vertical tab stop.
TOKENS IN C LANGUAGE – 5. SPECIAL CHARACTERS
Here's an example of using special characters in C:
#include <stdio.h>
int main()
{
printf("Hello\nworld!\n"); // Output: Hello
// world!
printf("First\tSecond\tThird\n"); // Output: First Second Third
printf("Backslash: \\ \n"); // Output: Backslash: \
printf("Double quote: \" \n"); // Output: Double quote: "
printf("Single quote: \' \n"); // Output: Single quote: '
printf("Alert: \a \n"); // Produces an alert sound
printf("Backspace: ab\bcd\n"); // Output: acd
printf("Carriage return: 123\rXYZ\n"); // Output: XYZ23
printf("Form feed: 123\fXYZ\n"); // Output: 123
// XYZ
printf("Vertical tab: 123\vXYZ\n"); // Output: 123
// XYZ
return 0;
}
TOKENS IN C LANGUAGE – 6. STRINGS
In C programming language, a string is a sequence of characters stored in an array. The string is
terminated by a null character ('\0'), which indicates the end of the string.
Here's an example of how to declare and initialize a string in C:

#include <stdio.h>
int main() {
char str[] = "Hello, world!"; // declare and initialize a string
printf("%s\n", str); // print the string
return 0;
}

We can also
initialize a string
by assigning it a
sequence of
characters one by
DATATYPES IN C
DATATYPES IN C LANGUAGE
Data types in C programming language refer to the type of data that can be stored in a variable.
In C, each variable must have a specified data type, which determines the size of the memory
required to store the data and the operations that can be performed on that data.

The need for data types in C arises from the fact that C is a strongly-typed language, which means
that the type of data stored in a variable must be declared before it can be used. This allows the
compiler to perform type checking and ensure that operations are performed only on data types
that are compatible with each other.

Using data types in C ensures that the program works as intended, with the
correct data being used in each operation. It also helps in reducing the
memory usage of a program, as the compiler knows the size of each variable
and can allocate memory accordingly.
Note : The use of data types enables the programmer to write more efficient
and readable code by using the appropriate data type for each variable or
constant.
DATATYPES IN C LANGUAGE
DATATYPES IN C LANGUAGE
In C programming language, there are several data types available, which can
be categorized as follows:
BASIC DATATYPES DERIVED DATATYPES ENUMERATED DATATYPES
char: character type, used to store a single arrays: a collection of similar data items
character or a small integer value. stored in contiguous memory locations.
int: integer type, used to store integer pointers: variables that hold the memory
values. addresses of other variables.
enum: user-defined data type used to
float: floating-point type, used to store structures: user-defined data types that assign names to integral constants, making
floating-point values with a single precision. combine a group of variables of different the code more readable.
data types under a single name.
double: floating-point type, used to store unions: similar to structures, but the
floating-point values with double precision. memory allocated to a union is shared
between all of its members.

It is important to note that the size and range of each


data type can vary depending on the implementation,
but the above-listed data types are commonly used in
C programming.
DATATYPES IN C LANGUAGE
The main difference between signed and unsigned datatypes is in how they
represent the range of values they can hold.
Signed Datatypes Unsigned Datatypes

A signed datatype can represent both positive and An unsigned datatype can only represent non-negative
negative values. It uses one bit to represent the sign of values. It uses all the bits to represent the magnitude of
the value (positive or negative), and the remaining bits to the value.
represent the magnitude of the value. For example, an unsigned 8-bit integer can represent
For example, a signed 8-bit integer (or "char") can values from 0 to 255.
represent values from -128 to +127.

Another difference between signed and unsigned datatypes is in how they handle arithmetic operations. For example,
in a signed integer, adding a negative value can result in overflow or underflow, while in an unsigned integer, adding a
negative value will simply wrap around to the maximum value. In addition, in a signed integer, dividing by a negative
value can result in a different result than dividing by a positive value, while in an unsigned integer, dividing by a
negative value is not possible.
DATATYPES IN C LANGUAGE
In C programming language, there are four basic data types:
char int float double
A character is a An integer is a A floating-point A double-precision
single byte that can whole number that number is a floating-point
represent a can be positive, number with a number is a
character from the negative, or zero. An fractional part. number with a
ASCII character set, int variable can A float variable fractional part and
or an integer value store an integer can store a more precision than
from -128 to 127. value in the range of floating-point a float. A double
A char variable is -2147483648 to value with variable can store a
typically used to 2147483647, single precision, floating-point value
represent a single depending on the typically 4 bytes with double
character or a small compiler and precision, typically
in size.
integer value. platform. 8 bytes in size.
DATATYPES IN C LANGUAGE
In C programming language, there are several datatypes available, which are classified into two
categories:
Primitive datatypes: These are the basic data types that are provided by the C language. The
primitive datatypes are further classified into three categories:
a. Integer types: These are used to store integer values. The size of the integer type
depends on the system architecture. The following diagram shows the different integer types in C
with their size and range:
Integer Type Size Range
char 1 byte -128 to 127

short 2 bytes -32768 to 32767


int 4 bytes -2,147,483,648 to 2,147,483,647
Long 4 / 8 bytes -2,147,483,648 to 2,147,483,647 (4 bytes)
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (8 bytes)
unsigned char 1 byte 0 to 255
unsigned short 2 bytes 0 to 65535
unsigned int 4 bytes 0 to 4,294,967,295
unsigned long 4 / 8 bytes 0 to 4,294,967,295 (4 bytes)
0 to 18,446,744,073,709,551,615 (8 bytes)
DATATYPES IN C LANGUAGE
Floating-point types: These are used to store real numbers. The size of the floating-point types
depends on the system architecture. The following diagram shows the different floating-point
types in C with their size and range:
Floating Point Type Size Range
float 4 bytes 1.2E-38 to 3.4E+38
double 8 bytes 2.3E-308 to 1.7E+308
long double 12 / 16 bytes 3.4E-4932 to 1.1E+4932

Boolean type: This is used to store true/false or 0/1 values. The size of the
Boolean type is implementation-dependent, but it is usually represented as an
integer type with a size of 1 byte.
Note : In C programming language, the boolean datatype is not a built-in
datatype. However, it can be emulated using the integer datatype, where 0
represents false and any non-zero value represents true.
Boolean Type Size Range
bool 1 byte 1 – TRUE
0 - FALSE
DATATYPES IN C LANGUAGE
Derived data types

They are those The derived data A derived data


Derived Datatypes

Derived Datatypes

Derived Datatypes
whose variables types are type won’t
allow us to store basically derived typically create a
multiple values out of the new data type –
of same type. primitive data but would add
But they never types. They are various new
allows to store used to create a functionalities to
multiple values complex data the existing ones
of different structures. instead.
types.
DATATYPES IN C LANGUAGE
Derived data types

Array: An array is a collection of Pointer: A pointer is a variable that stores


elements of the same data type, stored the memory address of another variable.
in contiguous memory locations. The Pointers are often used to manipulate
elements can be accessed using their arrays and to dynamically allocate
indices. memory.

Example: Example:
int a[5] = {9,8,7,6,5}; int var = 20;
Int *p = &var; //declaration and initialization of pointer
DATATYPES IN C LANGUAGE
sizeof( ) operator
The sizeof operator in C is used to determine the size, in bytes, of a type or a variable.
It returns the size as an unsigned integer value.

can be either a type or an


sizeof(expression) expression representing a
variable, constant, or data
type.
operator returns the size of the expression
or type
The sizeof operator returns the size of the expression or type as an unsigned integer value of
type size_t, which represents the size in bytes. The size calculated by sizeof includes any padding
that might be added by the compiler to align the data in memory.
VARIABLES IN C
VARIABLES IN C
• Variables are a fundamental concept
in programming, including in C

Variables language.
• Variables are used to store the values
that are used by the program to
perform various tasks.

• In C, variables are declared with a


name, a data type, and an optional

Variables initial value.


• In C programming language, a variable
is a named location in memory that
stores a value of a certain data type.
• Variables are used to store and manipulate
data in a program.

Variables
• In C, variables must be declared before they
are used. This means that we need to
declare a variable before we can use its
value in an expression or assign a new value
to it.
VARIABLES IN C
Variables are useful in C programming for several reasons. Here are a few examples:

They allow values to be stored and used in calculations or


comparisons later on in the program.

They can be used to represent different types of data, such as


numbers, characters, or strings.

They allow data to be manipulated and transformed as


necessary, such as incrementing a counter or computing an
average.

They enable the programmer to use names that have meaning


in the context of the program, making the code more readable
and easier to understand.
VARIABLES IN C
Declaring a variable in C:
To declare a variable in C, we need to specify its name and its data type.
Syntax
Any Valid C Identifier

datatype variable_name;

Any C Basic Datatypes


For example:
VARIABLES IN C
Initializing a Variable
We can also initialize a variable when you declare it, by assigning a value to it. The diagram
Syntax below illustrates
the concept of a
datatype variable_name = value;
variable in C
programming:

Assignment Operator
Any Valid C Identifier
Any Valid C Datatype

Example
SIMPLE I/O (INPUT/OUTPUT) FUNCTIONS IN C
SIMPLE I/O FUNCTIONS IN C

• Input and Output statement are used to


I/O read and write the data in C
programming.
STATEMENTS • These are embedded in stdio.h
(standard Input/Output header file).

• Input means to provide the program


I/O with some data to be used in the
program
STATEMENTS • Output means to display data on screen
or write the data to a printer or a file.
SIMPLE I/O FUNCTIONS IN C

stdin: This file is used to receive the


input (usually is keyboard file, but can
also take input from the disk file).
stdout: This file is used to send or
direct the output (usually is a monitor
file, but can also send the output to a
disk file or any other device).
stderr: This file is used to display or
store error messages.
SIMPLE I/O FUNCTIONS IN C

SIMPLE I/O FUNCTIONS In C, there There are mainly These are

SIMPLE I/O FUNCTIONS

SIMPLE I/O FUNCTIONS


are several two of discussed as:
Input/Output
simple functions are used • Unformatted I/O
input/outpu for this purpose. functions
t (I/O) These functions can • Formatted I/O
functions be used to interact functions
available in with the user and
the display information
standard in a simple console-
based C program.
library for
performing
basic I/O
operations.
SIMPLE I/O FUNCTIONS IN C
Unformatted Input/Output functions in C
They allow us to read and write raw data without any specific
formatting.
Here are a few examples:
Unformatted Input Functions:
1. getchar(): Reads a single character from the standard input.
2. gets(): Reads a string of characters from the standard input.
Unformatted Output Functions:
putchar(): Writes a single character to the standard output.
puts(): Writes a string of characters to the standard output.
SIMPLE I/O FUNCTIONS IN C
#include <stdio.h>
int main() {
// Unformatted Input
char ch; In this example, the getchar() function is used to
printf("Enter a character: "); read a single character from the user, and putchar()
ch = getchar(); is used to display the entered character. The puts()
printf("You entered: "); function is used to write the string "Hello, World!" to
putchar(ch); the standard output.
// Unformatted Output
char str[] = "Hello, World!";
puts(str);
return 0;
}
SIMPLE I/O FUNCTIONS IN C

Formatted input/output functions in C


They allow us to read and write data with specific formatting.
Here are some commonly used formatted I/O functions:
Formatted Input Functions:
scanf(): Reads input from the standard input based on the specified format.
fscanf(): Reads input from a file based on the specified format.
sscanf(): Reads input from a string based on the specified format.

Formatted Output Functions:


printf(): Writes output to the standard output based on the specified format.
fprintf(): Writes output to a file based on the specified format.
sprintf(): Writes output to a string based on the specified format.
SIMPLE I/O FUNCTIONS IN C – FORMAT SPECIFIERS IN C

They define how the data is In formatted input functions like ,


Format specifiers in C are special interpreted or displayed. Format format specifiers are used to specify
codes used in formatted input and specifiers are preceded by a percent the type of the data being read from
output functions to indicate the sign (%) in the format string of the and the input stream. For example, is a
type and format of the data being functions. Correctly using format format specifier used for integers,
read or written. specifiers is essential for proper data for floating-point numbers, for
conversion and formatted output in C. characters, and for strings.

They indicate how the values


In formatted output functions like , should be formatted and
format specifiers are used to specify
displayed. For example, is used to
the type of the data being displayed
and control the formatting of the print integers, for floating-point
output. numbers, for characters, and for
strings.
SIMPLE I/O FUNCTIONS IN C – FORMAT SPECIFIERS IN C
Format Specifier Data Type
%d int
%ld long int
%lld long long int
%u unsigned int
%lu unsigned long int
%llu unsigned long long int
%f float
%lf double
%c char
%s char* (string)
%p Pointer
%x unsigned int (hexadecimal)
%o unsigned int (octal)
SIMPLE I/O FUNCTIONS IN C

#include <stdio.h>
int main() {
// Formatted Input In this example, the scanf() function is
int num1, num2; used to read two integers from the user.
printf("Enter two numbers: "); The format specifier %d is used to
scanf("%d %d", &num1, &num2); indicate that integers are expected. The
printf("Sum: %d\n", num1 + num2); values are stored in the variables num1
// Formatted Output and num2, and their sum is printed
int value = 42; using printf().
printf("The value is: %d\n", value);
return 0;
}
Assignment Questions – Unit 1
ASSIGNMENT 1 QUESTIONS
Q1. Ajay is a first year B.Tech CSE student. His Programming with C faculty has given one task to find the count the number of
digits in a number which will enter by user. Help Ajay to write a C Program to Count number of digits in number without using
mod operator.

Q2. Lally is very weak in mathematics. So Raju challenges Lally to add each digit of a number, if she adds correctly she will get a
chocolate. Help Lally to get a chocolate by writing a C program to find the sum of the digits.

Q3. Arun is interested in Chess game. He joined in a chess club and first task is given by trainer to find the number of squares in
chessboard. Help Arun by writing a C program to find the number of squares in chessboard.

Q4. Gautam is a first year civil engineering student. His Faculty has given a simple task to convert the kilometers into miles.
Write a C program to convert the user entered Kilometers (KM) value into Miles.

Q5. In the Dubai, fuel efficiency for vehicles is normally expressed in miles-per-gallon (MPG). In India, fuel efficiency is normally
expressed in liters-per-hundred kilometers (L/100 km). Use your research skills to determine how to convert from
Miles-per-Gallon to Litres/100 km by writing a Simple C Program.
DISCUSSION
5 MINUTES

Applications !!!!!

Certification Courses!!!!!
Thank You

Regards

Dr. Pundalik Chavan

Associate Professor

You might also like