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

C Programming Notes

i an notes for c ++ language

Uploaded by

anshukiran.s30
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

C Programming Notes

i an notes for c ++ language

Uploaded by

anshukiran.s30
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

C programming

What is C?
It is a very powerful and general-purpose language used in programming. We can use C to develop software such as
databases, operating systems, compilers, and many more. This programming language is excellent to learn for beginners
in programming

Benefits of C Programming Language


 Simple
 Machine Independent or Portable
 Mid-level programming language
 structured programming language
 Rich Library
 Memory Management
 Fast Speed
 Extensible

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard Institute (ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.
C Character
Character is 1-byte information that denotes alphabets, digits, and some special characters like !, @, etc. So simple it
seems, but it has a long history of varying standards like EBCDIC, ASCII, etc. As every language contains a set of
characters used to construct words, statements, etc., C language also has a set of characters which include alphabets,
digits, and special symbols.
In the early days, there used to be an encoding system called Extended Binary-Coded Decimal Interchange
Code(EBCDIC), developed by IBM. EBCDIC can support 256 different types of characters. A few important features
of EBCDIC are:

 Each character fits in 8 bits.


 The same type of characters are not grouped together.
 Different versions of EBCDIC are not compatible.
Slowly, ASCII encoding was developed in 1963 by American Standards Association (ASA). ASCII was simpler and accommodated
fewer characters than EBCDIC. It has 128 characters and needs 7 bits to display a single character.

C Character Set

Every C program contains statements. These statements are constructed using words and these words are constructed
using characters from C character set.
Character Set includes a set of valid characters we can use in our program in different environments. C language has
broadly two character sets.
 Source Character Set (SCS): This is the set of characters that can be used to write source code. Before
preprocessing phase, the first step of C PreProcessor (CPP) is to convert the source code's encoding into Source
Character Set (SCS).This set includes Basic Character Set and White-space Characters.
 Execution Character Set (ECS): ECS is used to store character string constants. Other than Basic Character Set,
this set contains Control Characters and Escape Sequences. This is the set of characters that can be interpreted by
the running program. After preprocessing phase, CPP converts character and string constant's encoding into
Execution Character Set (ECS).
Basic Character Set

 Alphabets
 Digits
 Special Symbols

Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters together support 52
alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z

Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special symbols

C language supports a rich set of special symbols that include symbols to perform mathematical operations,
to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell backspace vertical
tab etc.,

White spaces
These characters are a part of the Source Character Set. They affect the text on display, but are visually blank.

The white spaces in the C programming language contain the following:

 Blank Spaces
 Carriage Return
 Tab
 New Line
C program to print all characters

Every character in C language has its equivalent ASCII (American Standard Code for Information
Interchange) value.
C - Basic Syntax

Comments - They are ignored by the compiler

This section is used to provide a small description of the program. The comment lines are simply ignored by the
compiler, that means they are not executed. In C, there are two types of comments.

1. Single Line Comments: Single line comment begins with // symbol. We can write any number of single line
comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */. We can write
any number of multiple lines comments in a program.

In a C program, the comment lines are optional. Based on the requirement, we write comments. All the comment
lines in a C program just provide the guidelines to understand the program and its code .

Tokens
tokens are the basic building blocks of a program. They are the smallest unit of a program that has meaning to the
compiler. tokens in C is the building block or the basic component for creating a program in C language.

Classification of tokens

Tokens in C language can be divided into the following categories

o Keywords
o Identifiers
o Strings
o Operators
o Constant
o Special Characters
KEYWORDS

Keywords in C can be defined as the pre-defined or the reserved words having special meaning to the compiler and
each keyword has its own functionality.

C language supports 32 keywords given below:

Some common C keywords include:


 int: used to declare integer variables
 char: used to declare character variables
 float: used to declare floating point variables
 double: used to declare double precision floating point variables
 void: used to declare functions that do not return a value
 return: used to exit a function and return a value to the calling function
 for: used to create a loop that executes a block of code a specified number of times
 while: used to create a loop that executes a block of code as long as a certain condition is true
 if: used to create conditional statements that execute a block of code only if a certain condition is true
 else: used to create an alternate block of code that is executed if the condition in an if statement is false

Identifier
Names given to identify a variable,functions,class modules or other object Identifiers in C are the user-defined words

RULES
 A valid identifier cab letter c both uppercase and lowercase digits and underscore
 First letter of a identifiers should be either a letter or an underscore
 You cannot use keyword as identifier
 There is no rule on how long and identifier can be
 Identifier should be written in such a way that it is meaningful , short and easy to read.

Operators
Separate PDF has made

Constants
There might be some data whose values remain constant throughout the program execution. Such variables are
known as Constant Variables. The values assigned to the variables are known as the literal.

How to Use Constants in C?

In the C programming language, A variable can be used as a constant by the following methods:

There are several ways to define constants in C:

#define preprocessor directive: This directive is used to define symbolic constants, which are replaced by the
preprocessor with their corresponding values before the program is compiled

#define PI 3.14159

#define MAX_LEN 100

const keyword: This keyword is used to declare a variable as a constant, which means that its value cannot be
modified once it has been assigned.

const double PI = 3.14159;

const int MAX_LEN = 100;


enum keyword: This keyword is used to define an enumerated type, which is a set of named integer constants.

enum boolean {false, true};

enum weekdays {Monday, Tuesday,

Constants in C
Constants are the variables whose values cannot be changed throughout the execution of the program once they
are initialized at the beginning of the program. Constants are also known as literals. A number, a character, a
string of characters, an array, a structure, a union, a pointer, and an enum can be set as a constant.

Types of Constants in C

Primary Constants

Constants of type float, integer, and character are known as Primary constants.

Example for Primary constants:


1, 1.23, "Scaler", 'h', etc.

As you can see that float, integer, and character are primary constants and we know that float, integer, and
character are primary data types. As the constants are of primary data type, they are known as primary
constants.

Primary constants can be once again divided into


 Numeric Constants
 Character Constants

Numeric Constants

Numeric constants contain signed or unsigned numerals, or a zero or a decimal. In a nutshell, all types of
numbers come under Numeric constants.

Numeric constants are once again divided into three types:

 Decimal Integer
 Octal Integer
 Hexadecimal Integer

Integer Constants
Integer constants are the numbers with decimals (base 10), hexadecimal (base 16), binary (base 2), or octal
(base 8). We will understand this better once we look into each of the Integer constants.

Let us know more about each integer constant in detail.

Decimal Integer
Decimal integers are the constants with base 10. Non-zero decimal digits (1 to 9) are decimal integers followed
by zero or more decimal digits (0 to 9 ).

Example: 255,100,69,999, etc.

Octal Integer
Octal integers are the constants with base 8. The digit zero (0) is followed by zero or more octal digits (0 to 7).

Example:0, 0125, 034673, 03245, etc.

Hexadecimal Integer
Hexadecimal integers are the constants with base 16. The sequence starts with 0x followed by one or more
hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).

Example:0x3b24, 0XF96, 0x21, 0x3AA, 0X29b, 0X4bD, etc.

Real Constants
A constant with the combination of positive, negative, or zero followed by a decimal point and the fractional
part is known as a real constant.

Example:-89, 0.123, 45, etc.

Character Constants

One or more characters are enclosed within a single quote (' ') or ("") depending on the type of characters.

Single Character Constants


Character constants having a single character enclosed within the ' ' (Single quote) are known as character
constants.
Example: 's', 'c', 'a', 'l', 'e', 'r', etc.
String Constants
Character constants with various special symbols, digits, characters, and escape sequences enclosed within the "
"(double quotes) are known as string constants.

Let us look at the examples and try to understand them better.


Example: "Scaler", "by", "InterviewBit", "123", "number1" etc.

As we can see in the above examples, all the words or the strings are enclosed within the double-quotes. If we
look at the last two examples, we can see numbers, but the numbers are treated as strings by the computer
because they are enclosed inside the double quotes.

Backslash Character Constants

Backslash characters or escape sequences are the types of character constants. A definite backslash character
performs a specific task.

also known as escape sequences


Secondary Constant
The datatypes such as Array, Pointers, Structure, Union, and Enum having a constant fixed value that remains
the same during the entire execution of the program are known as secondary constants.
We can see that these are secondary data types and we can conclude that the secondary data types are
considered Secondary data types.

Strings
a string is a sequence of characters. It can include letters, numbers, punctuation, and other symbols, and is often used to
represent text or other data that can be represented as a series of characters.

 String are used for storing text/character it is an array of character that is terminated by a NULL
character ‘\0’ for example:-
 char str[] = "xyz.\0";
 It is an one dimensional array

The null character indicates the end of string the null character used to the termination of a string.

Highlights:
The main difference between an array of character and string in c is that an array of character is a collection of
individual character while string is a collection of group of character >[word] that is treated as a single entity

Character arrays are used for declaring strings in C.

It is a good practice to end an array of characters with a \0 while initializing. However, when the compiler
comes across a double quotation marked a string of characters, it adds \0 at its end by default.

Declaration of string

The general syntax of declaring a string in C is as follows:

char variable[array_size];

Initializing a string in C
There are four methods of initializing a string in C:

1. Assigning a string literal with size

char str[8] = "xyz";

2. Assigning a string literal without size

char str[] = "xyz";

3. Assigning character by character with size

char str[8] = {'x', 'y', 'z','\0'};

4. Assigning character by character without size


char str[] = {'x', 'y', 'z','\0'};

Assign value to strings

We can use the strcpy() function to copy the value we want to assign to the character array. The syntax for strcpy() is
as follows:

strcpy(char* destination, const char* source);

It copies the string pointed by the source (including the null character) to the destination.

char str[20];

strcpy(str,"Strings.");

Read String from the user

The most common operation used for reading a string is scanf() .which reads a sequence of characters until it
encounters whitespace

Example

Note -

The format specifier used to input and output strings in C is %s.

To read a line of text

1. To read and print strings with whitespace, we can use the combination of fgets() and puts()
2. The fgets() function is used to read a specified number of characters. Its declaration looks as follows:
fgets(name_of_string, number_of_characters, stdin);
3. puts() is very convenient for displaying strings
puts(name_of_string);

An example using both functions:


Passing strings to functions
A string can be passed to a function as a character array or in the form of a pointer.

There might be many ways of doing this task. In this tutorial, we will be deliberating two methods for
performing this task:

1. Normally, passing a string array.


2. Pass the string using pointers.

The return type is kept void because it will display a success message on the successful passing of
string into the function.

Creating single string and double string normally

1.Checking length of the string and make changes Normally


2.pass the string using pointer

Commonly Used String Functions

 strlen() - calculates the length of a string


 strcpy() - copies a string to another
 strcmp() - compares two strings
 strcat() - concatenates two strings

Variable
Variable is the name of a memory locations which store some Data (variable is a container to hold DATA)

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter
or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.
RULES for writing variable
 The first letter of a variable should be either a letter or an underscore
 No commas, blanks and other symbol than under score are allowed
 A variable name consist of digit alphabet and even special symbol such as an underscore
 Then name of the variable must not being with a digit

Data Type of the Variable

We must assign a data type to all the variables that are present in the C language. These define the type of data that we
can store in any variable. If we do not provide the variable with a data type, the C compiler will ultimately generate a
syntax error or a compile-time error.

The data Types present in the C language are float, int, double, char, long int, short int, etc., along with other modifiers

General syntax for declaring a variable in C:


type variable_name;

TYPES Of Variable
1. Local Variables
When we declare variables inside a function or an inner block of code, then these variables are
known as local variables. They can only be used inside the function scope or the block scope.

2 Global Variables
When we declare variables outside of all the functions then these variables are known as global variables.
These variables always have file scope and can be accessed anywhere in the program, they also remain in
the memory until the execution of our program finishes

3. Formal Parameters

When we define a function and declare some variables in the function parameters, then these parameters
are known as formal parameters/variables. They have a function prototype scope.

Highlights
1. Global variables have a file scope, i.e. they are available for the whole program file.
2. The scope of a local variable in C starts at the declaration point and concludes at the conclusion of the block or a
function/method where it is defined.
3. The scope of formal parameters is known as function prototype scope and it is the same as its function scope,
we can access the variables only in the function definition and not outside it.
4. Although the scope of a static local variable is confined to its function, its lifetime extends to the end of program
execution.

Lifetime of a variable

Lifetime of a variable is defined as for how much time period a variable occupies a valid space in the system's
memory or lifetime is the period between when memory is allocated to hold the variable and when it is freed.
Once the variable is out of scope its lifetime ends. Lifetime is also known as the range/extent of a variable
A variable in the C programming language can have a

 static,
 automatic, or
 dynamic lifetime.
 Static Lifetime

Objects/Variables having static lifetime will remain in the memory until the execution of the program
finishes. These types of variables can be declared using the static keyword, global variables also have a
static lifetime: they survive as long as the program runs.

C Storage Classes
storage classes are used to define things like storage location (whether RAM or
REGISTER), scope, lifetime and the default value of a variable.

the memory of variables is allocated either in computer memory (RAM) or CPU Registers. The allocation of
memory depends on storage classes.

there are FOUR storage classes and they are as follows...

1. auto storage class


2. extern storage class
3. static storage class
4. register storage class

auto storage class


The default storage class of all local variables (variables declared inside block or function) is auto storage class.
Variable of auto storage class has the following properties...

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>

int main(){ int main(){


int a=10;
int i;
auto char c; {
float f; int a=20;
printf("i = %d\tc = %c\tf = %f",i,c,f); printf("%d",a);
}
return 0; printf(" %d",a);
} return 0;
}
External storage class
The default storage class of all global varibles (variables declared outside function) is external storage class.
Variable of external storage class has the following properties...
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>

int i; //By default it is extern variable extern int i; //extern variable


int main(){
int main(){
printf("%d",i);
printf("%d",i); return 0;
return 0; }
}

Static storage class


The static storage class is used to create variables that hold value beyond its scope until the end of the
program. The static variable allows to initialize only once and can be modified any number of times. Variable
of static storage class has the following properties...
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>

static int a; static int i=10;


int main(){ int main(){
printf("%d",a); i=25; //Assignment statement
return 0; printf("%d",i);
} return 0;
}

Register storage class


The register storage class is used to specify the memory of the variable that has to be allocated in CPU
Registers. The memory of the register variable is allocated in CPU Register but not in Computer memory
(RAM). The register variables enable faster accessibility compared to other storage class variables. As the
number of registers inside the CPU is very less we can use very less number of register variables. Variable of
register storage class has the following properties...
#include<stdio.h>
#include<conio.h>

int main(){
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}

Storage Keyword Memory Default Scope Life Time


Class Location Value
Automatic auto Computer Garbage Local to the Till the control
Memory Value block in which the variable remains within the block
(RAM) has defined in
which variable is defined
External extern Computer Zero Global to the As long as the
Memory program (i.e., Throughout program’s execution does
(RAM) the program) not
come to end
Static static Computer Zero Local to the The value of the
Memory block in which the variable persists between
(RAM) has defined different
function calls (i.e.,
Initialization
is done only once)
Register register CPU Garbage Local to the Till the control
Register Value block in which the variable remains within the block
has defined in which variable is
defined

You might also like