0% found this document useful (0 votes)
42 views27 pages

C Programming Chapter-1 Notes

Uploaded by

Jensen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
42 views27 pages

C Programming Chapter-1 Notes

Uploaded by

Jensen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

Chapter-1: Introduction to C Programming

1st Year (1st semester)


Batch: 2024-25
Notes:
Edited By,
Dr. Pundalik Chavan
Associate Professor,
School of Computer Science and Engineering
Reva University Bengaluru-64

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.

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 Content:

Chapter-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.

1.1 Overview of C language


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.
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-1 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.

It can be defined by the following ways:


 Mother language
 System programming language
 Procedure-oriented programming language
 Structured programming language
 Mid-level programming language
High-Level Languages:
 Very easy to understand.
 Programmer-friendly.
 Debugging is not very difficult.
 Come with easy maintenance and are thus simple and
manageable.
 One can easily run them on different platforms.
 They require a compiler/interpreter for translation into a
machine code.
 A user can port them from one location to another.
 It consumes more memory than the low-level languages.
 widely used and popular in today’s times.
 Java, C, C++, Python, etc., are a few examples of high-level
languages.
Low-Level Languages
 Machines can easily understand it.
 Debugging them is very difficult.
 Not very easy to understand.
 All the languages come with complex maintenance.
 They are not portable.
 These languages depend on machines.
 Always require assemblers for translating instructions.
 Low-level languages do not have a very wide application in
today’s times.
 Some examples of low-level languages include the Machine
language and Assembly language.

Features of C Language
 Simple
 Machine Independent or Portable
 Mid-level programming language
 Structured programming language
 Rich Library
 Memory Management
 Fast Speed
 Pointers
 Recursion
 Extensible
1) Simple:
 Provides a structured approach to break the problem into parts
 the rich set of library functions, data types, etc.
2) Rich Library:
 Provides a lot of inbuilt functions that make the development
fast.
3) Memory Management:
 It supports the feature of dynamic memory allocation.
 We can free the allocated memory at any time by calling the
free() function in C.
4) Speed
 The compilation and execution time of C language is fast
5) Pointer
 Can directly interact with the memory by using the pointers.
 Can use pointers for memory, structures, functions, array, etc.
6) Extendability
 Ability to extend the existing software by adding some new
features.
7) Recursion:
o A function that calls itself is known as a recursive function. And,
this technique is known as recursion.
Application of C
 Operating System
 Embedded Systems
 GUI
 Game Development
 Drivers
 Database Design

1.2 BASIC STRUCTURE OF C PROGRAMMING

Section Description

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

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

Includes preprocessor directive, which contains symbolic constants. E.g.: #define allows
Definition
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() For every C program, the execution starts from the main() function. It is mandatory to
Function include a main() function in every C program.
Includes all user-defined functions (functions the user provides). They can contain the
Subprograms inbuilt functions and the function definitions declared in the Global Declaration section.
These are called in the main() function.

Preprocessor directives are lines in your program that start with #


. The # is followed by an identifier that is the directive name.
• For example, #define is the directive that defines a macro.
Whitespace is also allowed before and after the #. For better
readability, a preprocessor directive should start in the first
column.
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.
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;
}

The steps involved in Creating and Running Programs are:


1. Writing and Editing Programs
2. Compiling Programs
3. Linking Programs
4. Executing Programs

1.3 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.

The following types of tokens are available:


1. Identifiers
2. Keywords
3. Constants
4. Operators
5. Special Characters
Tokens in c language – 1. Identifiers
• Identifiers in C are short and informative names that uniquely
identify variables or function names.
• Each program element in a C program is called an identifier. An
identifier is a variable that holds a value and stores it in the
memory.
• These are user-defined words used for naming of functions,
variables, structures, unions, arrays etc.
• These can be composed of lowercase letters, uppercase letters,
underscore or digits, but the first character should be either an
underscore or an alphabet.
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 whose meaning has already been defined
by the computer – they are pre-defined words in the C compiler.
• Keywords in C language are the collection of pre-defined or
reserved words. These are case-sensitive and written in lower
cases.
• Their meaning and functionality are already known to the
compiler. Each Keyword is meant to perform a specific function
in a C program.
• There are a total of 32 keywords supported by the C
language:

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.
• 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 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.
• 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.

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.

Example:
#include <stdio.h>
int main() {
const int NUM = 10;
const float PI = 3.14159;
const char LETTER = 'A';
const char *MESSAGE = "Hello, world!";
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


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.

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).

Example:
#include <stdio.h>
int main() {
int a = 5, b = 2;
float c = 7.5, d = 2.0;
// Arithmetic operators
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("c + d = %f\n", c + d);
printf("c - d = %f\n", c - d);
printf("c * d = %f\n", c * d);
printf("c / d = %f\n", c / d);
// Increment and decrement operators
printf("a++ = %d\n", a++);
printf("a = %d\n", a);
printf("++b = %d\n", ++b);
printf("b = %d\n", b);
// Relational operators
printf("a == b : %d\n", a == b);
printf("a != b : %d\n", a != b);
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);
// Logical operators
// Bitwise operators
printf("a & b : %d\n", a & b);
printf("a | b : %d\n", a | b);
printf("a ^ b : %d\n", a ^ b);
printf("~a : %d\n", ~a);
printf("a << 1 : %d\n", a << 1);
printf("b >> 1 : %d\n", b >> 1);
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.
printf("(a == b) && (c > d) : %d\n", (a == b) && (c > d));
\" - 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.
printf("(a
\a - alert or bell character: != b)produces
This character || (c <and) : %d\n",
audible (a != b) || (c < d));
or visible alert.
\b - backspace character: This character moves the cursor back one position.
printf("!(a
\r - carriage return character: == b)moves
This character : %d\n", !(ato the
the cursor ==beginning
b))Here's an example
of the current line. of using
\f - form feed character: This character moves the cursor to the next page or form.

#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 one, like this:

1.4 DATATYPES IN C
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.
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 arrays: a collection of similar data items


to store a single character or stored in contiguous memory locations.
a small integer value.

int: integer type, used to pointers: variables that hold the memory
store integer values. addresses of other variables.
enum: user-defined data type used
float: floating-point type, structures: user-defined data types that to assign names to integral
used to store floating-point combine a group of variables of different constants, making the code more
values with a single data types under a single name. readable.
precision.

double: floating-point type, unions: similar to structures, but the


used to store floating-point memory allocated to a union is shared
values with double between all of its members.
precision.
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)

1.5 VARIABLES IN C
• Variables are a fundamental concept in programming, including
in C 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 initial value.
• In C programming language, a variable is a named location in
memory that stores a value of a certain data type.

Declaring a variable in C:
To declare a variable in C, we need to specify its name and its data
type.
Syntax datatype variable_name;

Initializing a Variable
We can also initialize a variable when you declare it, by assigning a
value to it.
Syntax datatype variable_name = value;
Example:
1.6 SIMPLE I/O (INPUT/OUTPUT) FUNCTIONS IN C
• Input and Output statement are used to read and write the data in
C programming.
• These are embedded in stdio.h (standard Input/Output header
file).
• Input means to provide the program with some data to be used
in the program
• Output means to display data on screen or write the data to a
printer or a file.

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.
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.
#include <stdio.h>
int main() {
// Unformatted Input
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
// Unformatted Output
char str[] = "Hello, World!";
puts(str);
return 0;
}
In this example, the getchar() function is used to read a single
character from the user, and putchar() is used to display the entered
character. The puts() function is used to write the string "Hello,
World!" to the standard output.
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.
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)

#include <stdio.h>
int main() {
// Formatted Input
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Sum: %d\n", num1 + num2);
// Formatted Output
int value = 42;
printf("The value is: %d\n", value);
return 0;
}
In this example, the scanf() function is used to read two integers from
the user. The format specifier %d is used to indicate that integers are
expected. The values are stored in the variables num1 and num2, and
their sum is printed using printf().

Thank You for Reading


Edited By,
Dr. Pundalik Chavan
Associate Professor,
School of Computer Science and Engineering
Reva University Bengaluru-64

You might also like