Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

C language notes

C is a general-purpose, middle-level procedural programming language developed in 1972, primarily for system programming, with features like low-level memory access and fast speed. It differs from C++ by lacking object-oriented programming support and exception handling. C is widely used in various applications including operating systems, embedded systems, and scientific applications, and it supports multiple data types and operators.

Uploaded by

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

C language notes

C is a general-purpose, middle-level procedural programming language developed in 1972, primarily for system programming, with features like low-level memory access and fast speed. It differs from C++ by lacking object-oriented programming support and exception handling. C is widely used in various applications including operating systems, embedded systems, and scientific applications, and it supports multiple data types and operators.

Uploaded by

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

C Language

By: RT Rockstar
What is c?

C is a general purpose, middle-level procedural programming language initially


developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs.
It was mainly developed as a system programming language to write the UNIX
operating system.

The main features of the C language include:

General Purpose and Portable

Low-level Memory Access

Fast Speed

Clean Syntax
These features make the C language suitable for system programming like an
operating system or compiler development.
Difference Between C and C++

C++ was created to add the OOPs concept into the C language so they both have
very similar syntax with a few differences. The following are some of the main
differences between C and C++ Programming languages.

C++ supports OOPs paradigm while C only has the procedural concept of
programming.

C++ has exception handling capabilities. In C, we have to resolve exceptions


manually.

There are no references in C.


Structure of the C program
Components of a C Program:

1. Header Files

2. Main Method Declaration

3. Body of Main Method

4. Statement

5. Return Statement
Uses of c language
Operating systems: C is widely used for developing operating systems such as
Unix, Linux, and Windows.

Embedded systems: C is a popular language for developing embedded systems


such as microcontrollers, microprocessors, and other electronic devices.

System software: C is used for developing system software such as device


drivers, compilers, and assemblers.

Networking: C is widely used for developing networking applications such as


web servers, network protocols, and network drivers.

Database systems: C is used for developing database systems such as Oracle,


MySQL, and PostgreSQL.
Gaming: C is often used for developing computer games due to its ability to
handle low-level hardware interactions.

Artificial Intelligence: C is used for developing artificial intelligence and machine


learning applications such as neural networks and deep learning algorithms.

Scientific applications: C is used for developing scientific applications such as


simulation software and numerical analysis tools.

Financial applications: C is used for developing financial applications such as


stock market analysis and trading systems.
variable

variable is a name given to the memory location that helps us to store some
form of data and retrieves it when required. It allows us to refer to memory
location without having to memorize the memory address. A variable name can
be used in expressions as a substitute in place of the value it stores.
Syntax

data_type variable_name;
#include <stdio.h>

int main() {

// Declaring variables

int a;

// Storing data

a = 25;

printf("%d", a);

return 0;

}
Data Types in C

Each variable in C has an associated data type. It specifies the type of data that
the variable can store like integer, character, floating, double, etc. Each data type
requires different amounts of memory and has some specific operations which
can be performed over it.
Primitive Data Types

Primitive data types are the most basic data types that are used for representing
simple values such as integers, float, characters, etc.

int, char, float, double, void.


Derived Data Types

The data types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types.

array, pointers, function.


User-defined datatypes

The user-defined data types are defined by the user himself.

structure, union, enum.


Integer datatypes

Integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part). Octal values, hexadecimal
values, and decimal values can be stored in int data type in C.

Range: -2,147,483,648 to 2,147,483,647

Size: 4 bytes

Format Specifier: %d
Float datatypes

Float data type is used to store floating-point values. Float in C is used to store
decimal and exponential values. It is used to store decimal numbers (numbers
with floating point values) with single precision.
● Range: 1.2E-38 to 3.4E+38
● Size: 4 bytes
● Format Specifier: %f
Char datatypes

Character data type allows its variable to store only a single character. The size of
the character is 1 byte. It is the most basic data type in C. It stores a single
character and requires a single byte of memory in almost all compilers.
● Range: (-128 to 127) or (0 to 255)
● Size: 1 byte
● Format Specifier: %c
Double Data Type

Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding
64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits
after or before a decimal point.
● Range: 1.7E-308 to 1.7E+308
● Size: 8 bytes
● Format Specifier: %lf
Void Data Type

The void data type in C is used to specify that no value is present. It does not
provide a result value to its caller. It has no values and no operations. It is
used to represent nothing. Void is used in multiple ways as function return
type, function arguments as void, and pointers to void.
Void data type example

// use of void pointers

#include <stdio.h>

int main(){

int val = 30;

void* ptr = &val;

printf("%d", *(int*)ptr);

return 0;

}
Type Conversion in C

type conversion refers to the process of converting one data type to another. It
can be done automatically by the compiler or manually by the programmer. The
type conversion is only performed to those data types where conversion is
possible.
Implicit Type Conversion

Implicit type conversion, also known as type coercion, occurs when the C
compiler automatically converts one data type to another without the need for
explicit instructions from the programmer. This typically happens when a smaller
data type is assigned to a larger data type or when different data types are
involved in an arithmetic operation.
Explicit Type Conversion

Explicit type conversion, or typecasting, occurs when the programmer explicitly


tells the compiler to convert a variable from one type to another. This is done
using the casting operator (type).

Syntax:

(type) expression
Header Files in c

A header file is a source file that has the .h extension. Header files contain the
function prototypes or function declaration, whereas the source code contains
the constants, macros, system-wide global variables. Whenever we require the
definition of a function, then we simply include that header file in which
function is declared.

There are two types of header files defined in a program:

○ System defined header file: The header file which is predefined is


known as a system defined header file.
○ User-defined header file: The header file which is defined by the user is
known as a user-defined header file.
Both the user-defined and system-defined header file can be included in a
program with the help of using preprocessing directive (#). These preprocessor
directives are used to instruct the compiler to process these files before
compilation. There are two forms of including header file:

○ #include<file>
○ #include "file"

There is a difference between the header files given above. If the header file is
defined within the predefined source path, we can specify the header within
the angular brackets. If the header file is not defined within the predefined
source path then we can specify the full path of the header file within the
double-quotes.
Multiply.h

// function to multiply two numbers and return the result.


int multiplyoftwonumbers(int a, int b)
{
return (a*b);
}
Multiply.c
// C program to calculate the multiplication of two numbers
#include<stdio.h>

// including header file


#include "multiply.h"
int main()
{
int a =1, b = 2; // definition of two numbers
// function defined in multiply.h header file to calculate the multiplication.

cout << "Result of multiplication is : "


<< multiplyoftwonumbers(a, b);

}
Header Files List

● #include<stdio.h> (Standard input-output header): Used to perform input and output


operations in C like scanf() and printf().
● #include<string.h> (String header): Perform string manipulation operations like strlen
and strcpy.
● #include<conio.h> (Console input-output header): Perform console input and
console output operations like clrscr() to clear the screen and getch() to get the
character from the keyboard.
● #include<stdlib.h> (Standard library header): Perform standard utility functions like
dynamic memory allocation, using functions such as malloc() and calloc().
Header Files List
● #include<math.h> (Math header ): Perform mathematical operations like sqrt() and
pow(). To obtain the square root and the power of a number respectively.
● #include<ctype.h>(Character type header): Perform character type functions like
isaplha() and isdigit(). To find whether the given character is an alphabet or a digit
respectively.
● #include<time.h>(Time header): Perform functions related to date and time like
setdate() and getdate(). To modify the system date and get the CPU time respectively.
● #include<assert.h> (Assertion header): It is used in program assertion functions like
assert(). To get an integer data type in C/C++ as a parameter which prints stderr only
if the parameter passed is 0.
Header Files List
● #include<locale.h> (Localization header): Perform localization functions like
setlocale() and localeconv(). To set locale and get locale conventions respectively.
● #include<signal.h> (Signal header): Perform signal handling functions like signal()
and raise(). To install signal handler and to raise the signal in the program
respectively
● #include<setjmp.h> (Jump header): Perform jump functions.
● #include<stdarg.h> (Standard argument header): Perform standard argument
functions like va_start and va_arg(). To indicate start of the variable-length argument
list and to fetch the arguments from the variable-length argument list in the program
respectively.
Header Files List
● #include<errno.h> (Error handling header): Used to perform error handling operations
like errno(). To indicate errors in the program by initially assigning the value of this
function to 0 and then later changing it to indicate errors.
● <complex.h> - Complex number arithmetic
● <fenv.h> - Floating-point environment
● <float.h> - Limits of floating-point types
● <inttypes.h> - Format conversion of integer types
● <iso646.h> - Alternative operator spellings
● <limits.h>- Ranges of integer types
● <setjmp.h>- Nonlocal jumps
Header Files List

● <signal.h> - Signal handling


● <stdalign.h> - alignas and alignof convenience macros
● <uchar.h> - UTF-16 and UTF-32 character utilities
● <wchar.h> - Extended multibyte and wide character utilities
● <wctype.h> - Functions to determine the type contained in wide character data
Tokens in c

Tokens are the smallest units in a program that have meaningful


representations. Tokens are the building blocks of a C program, and they
are recognized by the C compiler to form valid expressions and statements.
Tokens can be classified into various categories, each with specific roles in
the program.
Classification of C Tokens
● Keywords in C
● Identifiers in C
● Strings in C
● Operators in C
● Constant in C
● Special Characters in C
Keywords in C

Keywords in C can be defined as the pre-defined or the reserved


words having its own importance, and each keyword has its own
functionality. Since keywords are the pre-defined words used by the
compiler, so they cannot be used as the variable names. If the
keywords are used as the variable names, it means that we are
assigning a different meaning to the keyword, which is not allowed. C
language supports 32 keywords given below:
Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers
in C are the user-defined words. It can be composed of uppercase letters, lowercase
letters, underscore, or digits, but the starting letter should be either an underscore or an
alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in C
are given below:

● The first character of an identifier should be either an alphabet or an underscore,


and then it can be followed by any of the character, digit, or underscore.
● It should not begin with any numerical digit.
● In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
● Commas or blank spaces cannot be specified within an identifier.
● Keywords cannot be represented as an identifier.
● The length of the identifiers should not be more than 31 characters.
● Identifiers should be written in such a way that it is meaningful, short, and easy to
read.
Strings in C

Strings in C are always represented as an array of characters having null


character '\0' at the end of the string. This null character denotes the end of
the string. Strings in C are enclosed within double quotes, while characters are
enclosed within single characters. The size of a string is a number of characters
that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of


characters.
What is Operators in c?

An operator in C can be defined as the symbol that helps us to perform some


specific mathematical, relational, bitwise, conditional, or logical computations
on values and variables. The values and variables used with operators are
called operands. So we can say that the operators are the symbols that
perform operations on operands.
Unary Operator

A unary operator is an operator applied to the single operand.


For example: increment operator (++), decrement operator (--),
sizeof, (type)*.
Binary Operator

The binary operator is an operator applied between two operands.


The following is the list of the binary operators:

● Arithmetic Operators
● Relational Operators
● Shift Operators
● Logical Operators
● Bitwise Operators
● Conditional Operators
● Assignment Operator
● Misc Operator
Arithmetic Operator

The arithmetic operators are used to perform


arithmetic/mathematical operations on operands.
S. No. Symbol Operator Description Syntax

1 + Plus Adds two a+b


numeric values.

Subtracts right
2 – Minus operand from a–b
left operand.

3 * Multiply Multiply two a*b


numeric values.

4 / Divide Divide two a/b


numeric values.
Returns the
remainder after
5 % Modulus diving the left a%b
operand with
the right
operand.

Used to specify
6 + Unary Plus the positive +a
values.

7 – Unary Minus Flips the sign of -a


the value.

Increases the
8 ++ Increment value of the a++
operand by 1.

Decreases the
9 — Decrement value of the a–
operand by 1.
Relational Operator

The relational operators in C are used for the comparison of the two
operands. All these operators are binary operators that return true or false
values as the result of comparison.
S. No. Symbol Operator Description Syntax

Returns true if the


left operand is
1 < Less than less than the right a<b
operand. Else
false

Returns true if the


left operand is
2 > Greater than greater than the a>b
right operand.
Else false

Returns true if the


left operand is
3 <= Less than or less than or equal
a <= b
equal to to the right
operand. Else
false
Returns true if the
left operand is
4 >= Greater than or greater than or
a >= b
equal to equal to right
operand. Else
false

Returns true if
5 == both the
Equal to a == b
operands are
equal.

Returns true if
6 != both the
Not equal to a != b
operands are
NOT equal.
Logical Operator

Logical Operators are used to combine two or more


conditions/constraints or to complement the evaluation of the original
condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.
S. No. Symbol Operator Description Syntax

Returns true if
1 && both the a && b
Logical AND
operands are
true.

Returns true if
2 || both or any of a || b
Logical OR
the operand is
true.

Returns true if
3 ! Logical NOT the operand is !a
false.
Bitwise Operator

The Bitwise operators are used to perform bit-level operations on the


operands. The operators are first converted to bit-level and then the
calculation is performed on the operands. Mathematical operations such as
addition, subtraction, multiplication, etc. can be performed at the bit level
for faster processing.
S. No. Symbol Operator Description Syntax

Performs
bit-by-bit AND
1 & Bitwise AND operation and a&b
returns the
result.

Performs
bit-by-bit OR
2 | Bitwise OR operation and a|b
returns the
result.

Performs
bit-by-bit XOR
3 ^ Bitwise XOR operation and a^b
returns the
result.
Flips all the set
4 ~ Bitwise First
and unset bits ~a
Complement
on the number.

Shifts the
number in
binary form by
5 << Bitwise
one place in the a << b
Leftshift
operation and
returns the
result.

Shifts the
number in
binary form by
6 >> Bitwise
one place in the a >> b
Rightshilft
operation and
returns the
result.
Assignment Operator

Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and the right side
operand of the assignment operator is a value. The value on the right side
must be of the same data type as the variable on the left side otherwise
the compiler will raise an error.
The assignment operators can be combined with some other operators in C
to provide multiple operations using single operator. These operators are
called compound operators.
S. No. Symbol Operator Description Syntax

Assign the value of


1 = Simple a=b
the right operand to
Assignment
the left operand.

Add the right


operand and left
2 += Plus and assign operand and assign a += b
this value to the left
operand.

Subtract the right


operand and left
3 -= Minus and assign operand and assign a -= b
this value to the left
operand.
Multiply the right
operand and left
4 *= Multiply and a *= b
operand and
assign
assign this value
to the left operand.

Divide the left


operand with the
5 /= Divide and assign right operand and a /= b
assign this value
to the left operand.

Assign the
remainder in the
6 %= Modulus and division of left a %= b
assign operand with the
right operand to
the left operand.
Performs bitwise
7 &= AND and assigns a &= b
AND and assign
this value to the
left operand.

Performs bitwise
8 |= OR and assigns a |= b
OR and assign
this value to the
left operand.

Performs bitwise
9 ^= XOR and assigns a ^= b
XOR and assign
this value to the
left operand.
Performs bitwise
Rightshift and
10 >>= Rightshift and a >>= b
assign this value
assign
to the left
operand.

Performs bitwise
Leftshift and
11 <<= Leftshift and a <<= b
assign this value
assign
to the left
operand.
Conditional or Ternary Operator (?:) in C

The conditional operator in C is kind of similar to the if-else statement as it


follows the same algorithm as of if-else statement but the conditional operator
takes less space and helps to write the if-else statements in the shortest way
possible. It is also known as the ternary operator in C as it operates on three
operands.

Syntax:

variable = Expression1 ? Expression2 : Expression3;


Example of Ternary Operator
// C program to find largest among two

// numbers using ternary operator

#include <stdio.h>

int main(){

int m = 5, n = 4;

(m > n) ? printf("m is greater than n that is %d > %d",m, n)

: printf("n is greater than m that is %d > %d",n, m);

return 0;

}
Constants in C

A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

● Using const keyword


● Using #define pre-processor
Types of constant
Special characters in C

● Some special characters are used in C, and they have a special meaning
which cannot be used for another purpose.
● Square brackets [ ]: The opening and closing brackets represent the single
and multidimensional subscripts.
● Simple brackets ( ): It is used in function declaration and function calling.
For example, printf() is a pre-defined function.
● Curly braces { }: It is used in the opening and closing of the code. It is used
in the opening and closing of the loops.
● Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single
printf statement.
● Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
● Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
● Tilde (~): It is used as a destructor to free memory.
● Period (.): It is used to access a member of a structure or a union.
Control Statements in C
Decision Making in C (if , if..else, Nested if, if-else-if ):

The conditional statements (also known as decision control structures) such as


if, if else, switch, etc. are used for decision-making purposes in C programs.

Need of Conditional Statements:

There come situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next. Similar situations
arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code. For example, in C if x
occurs then execute y else execute z. There can also be multiple conditions like
in C if x occurs then execute p, else if condition y occurs execute q, else execute
r. This condition of C else-if is one of the many ways of importing multiple
conditions.
Types of Conditional Statements in C
Following are the decision-making statements available in C:

● if Statement
● if-else Statement
● Nested if Statement
● if-else-if Ladder
● switch Statement
● Conditional Operator
● Jump Statements:
● break
● continue
● goto
● return
1. if in C

The if statement is the most simple decision-making statement. It is used to


decide whether a certain statement or block of statements will be executed or
not i.e if a certain condition is true then a block of statements is executed
otherwise not.
Syntax of if Statement:

if(condition)

// Statements to execute if

// condition is true

}
2. if-else in C

The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do
something else when the condition is false? Here comes the C else statement.
We can use the else statement with the if statement to execute a block of code
when the condition is false. The if-else statement consists of two blocks, one for
false expression and one for true expression.
Syntax of if else in C
if (condition){

// Executes this block if

// condition is true

else{

// Executes this block if

// condition is false

}
3. Nested if-else in C

The if else if statements are used when the user has to decide among multiple
options. The C if statements are executed from the top down. As soon as one of
the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the C else-if ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed. if-else-if ladder
is similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)

statement;

else if (condition)

Statement;

else

statement;
5. switch Statement in C

The switch case statement is an alternative to the if else if ladder that can be
used to execute the conditional code based on the value of the variable specified
in the switch statement. The switch block consists of cases to be executed
based on the value of the switch variable.
Syntax of switch
switch (expression) {

case value1:

statements;

case value2:

statements;

default:

statements;
Jump Statements in C

These statements are used in C for the unconditional flow of control throughout
the functions in a program. They support four types of jump statements:

A) break

This loop control statement is used to terminate the loop. As soon as the break
statement is encountered from within a loop, the loop iterations stop there, and
control returns from the loop immediately to the first statement after the loop.

Syntax of break:

break;
B) continue

This loop control statement is just like the break statement. The continue
statement is opposite to that of the break statement, instead of terminating the
loop, it forces to execute the next iteration of the loop.

As the name suggests the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the loop,
the code inside the loop following the continue statement will be skipped and the
next iteration of the loop will begin.

Syntax of continue:

continue;
C) goto

The goto statement in C also referred to as the unconditional jump statement


can be used to jump from one point to another within a function.
D) return

The return in C returns the flow of the execution to the function from where it is
called. This statement does not mandatorily need any conditional statements.
As soon as the statement is executed, the flow of the program stops
immediately and returns the control from where it was called. The return
statement may or may not return anything for a void function, but for a non-void
function, a return value must be returned.

Syntax of return:

return [expression];

You might also like