0% found this document useful (0 votes)
9 views40 pages

cnotes

C Language is a general-purpose programming language developed by Dennis Ritchie in 1972, primarily for system software like operating systems and device drivers. It features a simple syntax, is case-sensitive, and supports both low-level and high-level programming, making it widely used in various applications including database management and operating systems. The document also outlines the basic structure of a C program, data types, constants, variables, and input/output functions.

Uploaded by

pawarvidu23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

cnotes

C Language is a general-purpose programming language developed by Dennis Ritchie in 1972, primarily for system software like operating systems and device drivers. It features a simple syntax, is case-sensitive, and supports both low-level and high-level programming, making it widely used in various applications including database management and operating systems. The document also outlines the basic structure of a C program, data types, constants, variables, and input/output functions.

Uploaded by

pawarvidu23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

C Programming

What is C language?
C Language is a general-purpose, programming language. Which was created by
Dennis Ritchie in 1972 at AT & T’S Bell Telephone Laboratories. Dennis Ritchie
wanted to create an operating system named Unix Operating System. to develop
it, the C language was developed.
The special thing is that we can do low-level programming with the help of C
language, due to this feature, C programming language is used to make system
software such as Operating system, Device Driver, Compiler, etc.

Features of C Language
1. C is a simple and easy programming language.
2. There are commands/instructions like English in C language which are very
easy for a programmer to read, understand, and code.
3. C is a Procedure Oriented Programming Language.
4. C is a very powerful and case sensitive programming language.
5. C Language is a Compiler based dynamic programming language.
6. C language is a middle level language due to which both low level and high
level programming can be done.
7. The C language is the most commonly used programming language in
developing operating systems and embedded systems.
8. C language is a very portable and powerful programming language.
9. C language is a Syntax Based Language.
10. C is a general purpose programming language that covers basic
features of all other languages.

1. Libraries with Rich Functions


DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 1
C Programming

Robust libraries and functions in C help even a beginner coder to code with
ease.
2. Middle-Level Language
As it is a middle-level language so it has the combined form of both capabilities
of assembly language and features of the high-level language.
3. Portability
C language is lavishly portable as programs that are written in C language can
run and compile on any system with either no or small changes.
4. Easy to Extend
Programs written in C language can be extended means when a program is
already written in it then some more features and operations can be added to it.
5.Rich set of built-in Operators
It is a diversified language with a rich set of built-in operators which are used in
writing complex or simplified C programs.

Why is C so important?
If C language is your first programming language, then believe me you will
understand programming quite well because C language Is very helpful in
building our programming skills, as well as C language teaches us to understand
the logic.

some applications made with C language -:


Oracle and MySql is a software for database management that is built-in C
Language.
Almost all the device drivers are made in C language. The device driver is a tool
through which the content of your pen drive is read.
Today’s Hot Technology Android’s core library is also written in C language.
All the operating systems of today are also made in C language like – Unix
Operating System
Many parts of Web Browser are also written in C Language.

Applications of C Language
1. You can make a good operating system using C Language like- Windows,
Linux, Mac. because the major part of this operating system is written in C
language.
2. With the help of C Language you can create a Compiler which converts
programming language code into machine language.
3. With this, you can create a Text Editor.
4. Utility Software can be created.
5. Can create software with database management like – Oracle, Mysql, etc.
DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 2
C Programming

Basic Structure of C Program


Whenever we create a program in C language, we can divide that program into
six different sections. This section is as follows:

Documentation (Documentation Section)


Pre-processor Statements (Link Section)
Definition Section
Global Declarations Section
Main functions section
User-Defined Functions or Sub Program
Section
1. Documentation (Documentation Section)
Programmers write comments in the Documentation section to describe the
program. The compiler ignores the comments and does not print them on the
screen. Comments are used only to describe that program. That is
/* Name of the program */ this is called comment line
/* */ comment lline

Preprocessor Statements (Link Section)


Within the Link Section, we declare all the Header Files that are used in our
program. From the link section, we instruct the compiler to link those header files
from the system libraries, which we have declared in the link section in our
program.These can be followe by #(hash) character
Example -:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>

Definition Section
The definition of Symbolic Constant is defined in this section, so this section is
called Definition Section. Macros are used in this section.
Example -:
#define PI 3.14

4. Global Declarations Section


Within the Global Declarations Section section, we declare such variables which
we can use anywhere in our program, and that variable is called Global Variables,
we can use these variables in any function.
DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 3
C Programming

In the Global Declaration section, we also declare functions that we want to use
anywhere in our program, and such functions are called Global Function.
Example -:
int area (int x); //global function
int n; // global Variable

5. Main functions section


Whenever we create a program in C language, there is one main() function in that
program. The main () function starts with curly brackets and also ends with curly
brackets. In the main () function, we write our statements.
The code we write inside the main() function consists of two parts, one
Declaration Part and the other Execution Part. In the Declaration Part, we declare
the variables that we have to use in the Execution Part, let’s understand this with
an example.
Example -:
int main (void)
{
int n = 15; // Declaration Part
printf ("n = %d", n); // Execution Part
return (0);
}

6. User-Defined Functions or Sub Program Section


Declare all User-Defined Functions under this section.
Example -:
int sum (int x, int y)
{
return x + y;
}

/* Program to calculate Area of Circle */ /* comment line */


#include <stdio.h> /* pre-processor directives */
#define PI 3.14159 /* global declaration*/
void main() /* main */
{
float radius, area; /* declaration part */
printf("Enter the radius of the circle: "); /* execution part */
scanf("%f", &radius);
area = PI * radius * radius;
DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 4
C Programming

printf("The area of the circle is: %f", area);


return 0;
}

Creating, compilation and Executing C program


Open a text editor and type the above mentioned code
Save the files as circle
Open a command prompt and to the directory where you want to save the file.
Compile the program by using the keyboard. If there are errors, it displays lien
number and the type of error occurred.
If there are no errors in your code, then run the program to see the output on the
screen.

C Character set
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. C language supports a total of
256 characters.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 5


C Programming

TOKENS
Every C program is a collection of instructions and every instruction is a collection
of some individual units. Every smallest individual unit of a c program is called
token. Every instruction in a c program is a collection of tokens. Tokens are used
to construct c programs and they are said to the basic building blocks of a c
program.

In a c program tokens may contain the following...


Keywords
Identifiers
Operators
Special Symbols
Constants
Strings
Data values
In a C program, a collection of all the keywords, identifiers, operators, special
symbols, constants, strings, and data values are called tokens.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 6


C Programming

Keywords are special words in C programming which have their own predefined
meaning.

Identifiers
Identifiers are user-defined names of variables, functions and arrays. It comprises
of combination of letters and digits. In C Programming, while declaring identifiers,
certain rules have to be followed viz.
1. It must begin with an alphabet or an underscore and not digits.
2. It must contain only alphabets, digits or underscore.
3. A keyword cannot be used as an identifier
4. Must not contain white space.
5. Only first 31 characters are significant.
Let us again consider an example
int age1;
float height_in_feet; Here, age1 is an identifier of integer data type

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 7


C Programming

Constant in C
Constant in C is defined as the value which cannot be modified during the
execution of the program. The constants in C are used for representing the fixed
values which do not change.

Integer Constants
An integer constant is a sequence of digits from 0 to 9 without decimal points
or fractional part or any other symbols. There are 3 types of integers namely
decimal integer, octal integers and hexadecimal integer.

Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or


– sign. Spaces, commas and non digit characters are not permitted between
digits. Example for valid decimal

Integer constants are


1 int y = 123; //here 123 is a decimal integer constant
Octal Integers constant consists of any combination of digits from 0 through 7
with a O at the beginning.
int x = 0123; // here 0123 is a octal integer constant .
Hexadecimal integer constant is preceded by OX or Ox, they may contain
alphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal
digits. Example of valid hexadecimal integers are
int x = 0x12 // here Ox12 is a Hexa-Decimal integer constant
1

RealConstants
Real Constants consists of a fractional part in their representation. Integer
constants are inadequate to represent quantities that vary continuously. These
quantities are represented by numbers containing fractional parts like
26.082. Example of real constants are
float x = 6.3; //here 6.3 is a double constant.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 8


C Programming

float y = 6.3f

SingleCharacterConstants
A Single Character constant represent a single character which is enclosed in a
pair of quotation symbols.
Example for character constants are
char y ='u';

String Constants
A string constant is a set of characters enclosed in double quotation marks. The
characters in a string constant sequence may be a alphabet, number, special
character and blank space. Example of string constants are
1 "VISHAL" "1234" "God Bless""!.....?"

DECLARING A CONSTANT
there are two ways to declare this constant
1.By using the const keyword in a variable declaration which will reserve a
storage memory
#include <stdio.h>
void main()
{
const double PI = 3.14;
printf("%f", PI);
/*PI++; This will generate an error as constants
cannot be changed */
}

2. By using the #define pre-processor directive which doesn't use memory for
storage and without putting a semicolon character at the end of that statement
#include <stdio.h>
#define PI 3.14
void main()
{
printf("%f", PI);
}

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 9


C Programming

C Variables

Declaration and Initialization?


Declaration of a variable in a computer programming language is a statement
used to specify the variable name and its data type. Declaration tells the compiler
about the existence of an entity in the program and its location. When you declare
a variable, you should also initialize it.
1. Initialization is the process of assigning a value to the Variable.
Every programming language has its own method of initializing the variable.
2. If the value is not assigned to the Variable, then the process is only called a
Declaration.
Basic Syntax
The basic form of declaring a variable is:
type identifier [= value] [, identifier [= value]]…];

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 10


C Programming

OR
data_type variable_name = value;
where,
type = Data type of the variable
identifier = Variable name
value = Data to be stored in the variable (Optional field)
int a, b, c; // declare 3 variables.

int z = 35; // declare and initialize variable z with value 35.

Data Type is the classification of the data that is taken as input, processed,
and results in an output
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

The following are some main primitive data types in C:


1. Integer Data Type
The 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
Syntax is int var_name; Ex.int a = 9;

Character Data Type

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 11


C Programming

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
char a = 'a';
Syntax of char char
var_name;
The char keyword is used to declare the variable of character type:

Float Data Type


In C programming 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
Syntax of float float var_name; Eg: float a = 9.0f; float b = 2.5f;
The float keyword is used to declare the variable as a floating point:

Input and Output Functions in C


Input and output functions are available in the C language to perform the most
common tasks. In every C program, three basic functions take place – accepting
of data as input, the processing of data, and the generation of output.
Input means to provide the program with some data to be used in it.
Output means to display data on the screen or write the data to a printer or a file.

The acceptance of data refers to input


The presentation of data refers to the output

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 12


C Programming

1. The printf() function


The printf() function is the most used function in the C language.
This function is defined in the stdio.h header file and is used to show output on
the console (standard output).
Following is how the printf() function is defined in the C stdio.h library.
These functions are called formatted I/O functions because we can use format
specifiers in these functions and hence, we can format these functions according
to our needs
Formatted I/O functions are used to take various inputs from the user and
display multiple outputs to the user

Format Specifiers
To print values of different data types using the printf() statement and while
taking input using the scanf() function, it is mandatory to use format specifiers.
It is a way to tell the compiler what type of data is in a variable.
Some examples are %c, %d, %f, etc.
Example
printf("%d", a + b);
Rules for declaring formatted input function
2. Control string should be enclosed within double quotation marks
3. Every input variable should have individual character group

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 13


C Programming

4. Every character group should begin with a % symbol


5. More than one character group can be enclosed within a single control
string
6. Every input variable should being with a & symbol
7. Arguments are separated by commas.
8. Comma operator separates the control string and the arguments

Here's a look at the format specifiers used by functions in a program:


Format Specifier Datatype
%d, %i int
%c char
%lf double
%f float
%hd short int
%li long int
%u unsigned int
%lu unsigned long int
%lli long long int
%llu unsigned long long int
%Lf long double
%c signed char
%c unsigned char

2. The scanf() function


When we want to take input from the user, we use the scanf() function and store
the input value into a variable.
Following is how the scanf() function is defined in the C stdio.h library.
Here is the syntax for scanf():
scanf("%x", &variable);
Copy
where, %x is the format specifier.
Using the format specifier, we tell the compiler what type of data to expect from
the user.
The & is the address operator which tells the compiler the address of the variable
so that the compiler can store the user input value at that address.

Unformatted Input/Output functions

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 14


C Programming

Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype. These functions are
used to read single input from the user at the console and it allows to display
the value at the console.

3. getchar() & putchar() functions


The getchar and putchar functions are used for taking character input from the
user and printing the character as output.
The getchar() function
The getchar() function reads a character from the terminal and returns it as
an integer.
This function reads only a single character at a time.
Here is the syntax for the getchar() function:
int getchar(void);
Copy
You can use this method in a loop if you want to read more than one character.
The putchar() function
The putchar() function displays the character passed to it on the screen and
returns the same character.
This function too displays only a single character at a time.
Here is the syntax for the putchar() function:
4. gets() & puts() functions
The gets and puts functions are used for taking string input and giving string
output.
The gets() function
The gets() function reads a line of text from stdin(standard input) into the buffer
pointed to by str pointer, until either a terminating newline or EOF (end of file)
occurs.
Here is the syntax for the gets() function:
char* gets(char* str);
Copy
The puts() function
The puts() function writes the string str with a newline character ('\n') at the end
to stdout. On success, a non-negative value is returned.
Here is the syntax for the gets() function:
int puts(const char* str);

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 15


C Programming

Operators in C
C OPERATORS AND EXPRESSION
The operators are types of symbols that inform a compiler for performing some
specific logical or mathematical functions

Expressions perform specific actions, based on an operator, with one or two


operands. An operand can be a constant, a variable or a function result.

Unary arithmetic operators


Unary operators are arithmetic operators that perform an action on a single
operand. The script language recognizes the unary operator negative (-).
EX: A=-10;

Unary operators perform an action with a single operand.


Increment and Decrement Operators in C

Increment Operator in C
The increment operator ( ++ ) is used to increment the value of a variable in
an expression by 1. It can be used on variables of the numeric type such as
integer, float, character, pointers, etc.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 16


C Programming

Syntax of Increment Operator


Increment Operator can be used in two ways which are as follows:
// AS PREFIX
++m
// AS POSTFIX
m++
1. Pre-Increment
In pre-increment, the increment operator is used as the prefix. Also known as
prefix increment, the value is incremented first according to the precedence and
then the less priority operations are done.
Example
result = ++var1;
The above expression can be expanded as
var = var + 1;
result = var;

2. Post-Increment
In post-increment, the increment operator is used as the suffix of the operand.
The increment operation is performed after all the other operations are done. It
is also known as postfix increment.
Example
result = var1++;
The above expression is equivalent
result = var;
var = var + 1;

Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an
expression. In the Pre-Decrement, the value is first decremented and then used
inside the expression. Whereas in the Post-Decrement, the value is first used
inside the expression and then decremented.
Syntax
Just like the increment operator, the decrement operator can also be used in two
ways:
// AS PREFIX
--m
// AS POSTFIX
m--

where m is variable.
DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 17
C Programming

1. Pre-Decrement Operator
The pre-decrement operator decreases the value of the variable immediately
when encountered. It is also known as prefix decrement as the decrement
operator is used as the prefix of the operand.
Example
result = --m;

which can be expanded to


m = m - 1;
result = m;

2. Post-Decrement Operator
The post-decrement happens when the decrement operator is used as the suffix
of the variable. In this case, the decrement operation is performed after all the
other operators are evaluated.
Example
result = m--;

The above expression can be expanded as


result = m;
m = m-1;

EG :int a = 5; int b = 5;
int prefix = --a; int postfix = b--;
Ans: Prefix = 4 Postfix = 5

Binary operators perform actions with two operands


Arithmetic operators ( +, -, *, /, **, % )
Arithmetic operators perform mathematical operations such as addition and
subtraction with operands
Operator precedence
Expressions are normally evaluated left to right. Complex expressions are
evaluated one at a time. The order in which the expressions are evaluated is
determined by the precedence of the operators used
The following tables list the C operator precedence from highest to lowest and
the associativity for each of the operators:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 18


C Programming

Operator

Precedence Description Associativity

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement

2 (type) Cast Operator Right-to-Left

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 19


C Programming

Operator

Precedence Description Associativity

Relational less than, less than or


< , <=
equal to
6 Left-to-Right
Relational greater than, greater
> , >=
than or equal to

Relational is equal to, is not equal


7 == , != Left-to-Right
to

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment
14

Example of Operator Precedence and Associativity


exp = 100 + 200 / 10 - 3 * 10
Here, we have four operators, in which the / and * operators have the same
precedence but have higher precedence than the + and – operators. So,
according to the Left-to-Right associativity of / and *, / will be evaluated first.
exp = 100 + (200 / 10) - 3 * 10
= 100 + 20 - 3 * 10
DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 20
C Programming

After that, * will be evaluated,


exp = 100 + 20 - (3 * 10)
= 100 + 20 - 30
Now, between + and –, + will be evaluated due to Left-to-Right associativity.
exp = (100 + 20) - 30
= 120 - 30
At last, – will be evaluated.
exp = 120 - 30
= 90

Assignment Operator (= )
Use the assignment operator (=) to copy a constant, literal, variable expression
result, or function result to a variable. The script language does not support
multiple assignments in a single statement (such as a=b=c=0). String lengths
are defined based on the size of the string assigned to the variable and can
change dynamically at runtime.

Logical Operators (AND, OR)


Logical operators allow the combining of more than one relational test in one
comparison. Logical operators return a TRUE (1) or FALSE (0) value. Logical
operators have a lower precedence than arithmetic operators.

Symb
Operation Example Description
ol
AND True if both expr1 and expr2 are
AND Expr1 $$ expr2
&& true.
OR || OR Expr1 OR expr2 True if either expr1 or expr2 are true.
Table 2. Logical Operators

Relational Operators
Relational operators are as follows:
SymbolOperation Example Description
< Less than a<b True if a is less than b.
> Greater than a GT b True if a is greater than b.
== Equal a == b True if a is equal to b.
!= Not equal a NE b True if a is not equal to b.
Less than or
<= a <= b True if a is less than or equal to b.
equal
>= Greater than ora GE b True if a is greater than or equal to b.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 21


C Programming

SymbolOperation Example Description


equal
Table 3. Relational Operators

The conditional operator in C


The ternary operator in C is a conditional operator that works on three operands.
It works similarly to the if-else statement and executes the code based on the
specified condition. It is also called conditional Operator. It is also known as
the ternary operator in C as it operates on three operands.
Syntax of Conditional/Ternary Operator in C
The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
Or the syntax can also be in this form
variable = (condition) ? Expression2 : Expression3;

Control Statements

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 22


C Programming

Control statements in C help the computer execute a certain logical statement


and decide whether to enable the control of the flow through a certain set of
statements or not.

Decision making statements


Simple if Statement
Simple if statements are carried out to perform some operation when the
condition is only true. If the condition of the if statement is true then the
statements under the if block is executed else the control is transferred to the
statements outside the if block.
Syntax of the if statement is as given below:

Flow Chart:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 23


C Programming

If-else Statement
In some situations, you may have to execute statements based on true or false
under certain conditions, therefore; you use if-else statements. If the condition is
true, then if block will be executed otherwise the else block is executed.
Syntax of the if-else statement is as given below:

Flow Chart:

Nested if-else Statements


The nested if-else statements consist of another if or else. Therefore; if the
condition of “if” is true (i.e., an outer if) then outer if’s if block is executed which
contains another if (that is inner if) and if the condition of if block is true,
statements under if block will be executed else the statements of inner if’s “else”
block will be executed.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 24


C Programming

Syntax of the nested if-else statement is as given below:

Flow Chart:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 25


C Programming

Else-if Ladder Statements


The else-if ladder statements contain multiple else-if, when either of the condition
is true the statements under that particular “if” will be executed otherwise the
statements under the else block will be executed.
Suppose the “if” condition is true, statements under “if” will be executed else the
other “if” condition is tested, and if that condition is true statements under that
particular “if” will be executed. This process will repeat as long as the else-if’s are
present in the program.
Syntax of the else-if ladder statement is as given below:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 26


C Programming

Flow Chart:

Conditional Control Statements in C (Switch)


As per the value of the switch expression, the switch statement will allow multi-
way branching.
Depending on the expression, the control is transferred to that particular case
label and executed the statements under it. If none of the cases are matched with
the switch expression, then the default statement is executed.
The syntax of the switch statement is as given below:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 27


C Programming

Flow Chart:

Goto Statements in C
The goto statements are used to transfer the flow of control in a program, goto
statement is also known as a jump control statement because it is used to jump
to the specified part of the program. The label in goto statement is a name used
to direct the branch to a specified point in the program.
Syntax of the goto statement is as given below:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 28


C Programming

After goto statements in C, you are now heading towards the loop control
statements in C.
Loop Control Statements in C

While Loop
A while loop is also known as an entry loop because in a while loop the condition
is tested first then the statements underbody of the while loop will be executed.
If the while loop condition is false for the first time itself then the statements
under the while loop will not be executed even once.
The syntax of the while loop is as given below:

Flow Chart:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 29


C Programming

do-while Loop
The do-while is also known as an exit loop because in the do-while loop, the
statements will be executed first and then the condition is checked.
If the condition of the while loop is true then the body of the loop will be executed
again and again until the condition is false. Once the condition is false, the control
will transfer outside the do-while loop and execute statements followed soon after
the do-while loop.
The syntax of the do-while loop is as given below:

Flow Chart:

Example:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 30


C Programming

For Loop
The for loop is also known as a pre-test loop. From the following syntax,
expression1 is an initialization, expression2 is the conditional expression and
expression3 is an updation. The variables can be initialized in for the statement
itself.
The syntax of the do-while loop is as given below:

In the for loop, expression1 is used to initialize the variable, expression2 is


evaluated and if the condition is true, then the body of for loop will be executed
and then the statements under expression3 will be executed. This process is
repeated as long as the for loop condition is true, once the condition is false
control will return to the statements following the for loop and execute those
statements.
Flow Chart:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 31


C Programming

ARRAYS
An array is a collection of data items, all of the same type, accessed using a
common name.
Declaring Arrays
Array variables are declared identically to variables of their data type, except that
the variable name is followed by one pair of square [ ] brackets for each
dimension of the array.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:

How to initialize an array?


It is possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};

There are majorly three types of arrays


There are majorly three types of arrays:
One-dimensional array (1-D arrays)
Two-dimensional (2D) array
Three-dimensional array

. One-dimensional array (1-D arrays) :


You can imagine a 1d array as a row, where elements are stored one after
another.

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 32


C Programming

1D array
Syntax for Declaration of Single Dimensional Array
Below is the syntax to declare the single-dimensional array
data_type array_name[array_size];

data_type: is a type of data of each array block.


array_name: is the name of the array using which we can refer to it.
array_size: is the number of blocks of memory array going to have.
For Example
int nums[5];

2. Two-dimensional (2D) array:


Multidimensional arrays can be considered as an array of arrays or as a matrix
consisting of rows and columns.

2D array
A 2D array is also known as a matrix (a table of rows and columns).

Syntax for Declaration of Two-Dimensional Array


Below is the syntax to declare the Two-dimensional array
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension];
where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in
the corresponding dimension.

For Example
int nums[5][10];

3. Three-dimensional array:

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 33


C Programming

A 3-D Multidimensional array contains three dimensions, so it can be considered


an array of two-dimensional arrays.

3D array
Syntax for Declaration of Three-Dimensional Array
Below is the syntax to declare the Three-dimensional array
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension]
[sizeof_3rd_dimension];

where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in
the corresponding dimension.
For Example
int nums[5][10][2];

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 34


C Programming

STRINGS

A string refers to a collection of characters (including numerals, symbols, letters


and punctuations) represented in a regular, uniform sequence. A string in C is a
sequence of characters terminated with a NULL character '\0'.
Here’s an example of C string declaration.
char str[] =
"Programming.\0";
Strings in C are enclosed within double quotes(" "), and characters are enclosed
within single quotes(' ').
Declaration of C Strings
The data type of string in C is character.
char
variable[array_size];
Based on this syntax, let’s declare the strings.
char
str[10];
Reading C Strings
If you want to read strings in C, you can use the scanf function or its safer
alternative, fgets. The scanf function lets you read input from the standard input
stream. Its syntax is:

The fgets function reads a line of input from any standard input stream and saves
it in a character array. Here’s its syntax.
scanf("%s",
str);
Writing C Strings
If you want to write or output C strings, you can use the printf function or any
other output functions such as fputs or puts.
Syntax of printf function:

printf("String: %s\n",
str);
String Handling Functions in C

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 35


C Programming

C programming language provides a set of pre-defined functions called string


handling functions to work with string values. The string handling functions are
defined in a header file called string.h. Whenever we want to use any string
handling function we must include the header file called string.h.

strcpy() strcpy(string1, string2) Copies string2 value into string1

strlen(): This function can be used to find a string’s length.


Syntax of srtlen():
strlen(string1) returns total number of characters in string1

Eg: strlen(alphabet); Length is 8

strcat(): This function is used to concatenate two strings.


Syntax of strcat():
strcat() strcat(string1,string2) Appends string2 to string1

strupr(): It takes a string as input and converts all the letters in the string to
uppercase.
strupr(string1) Converts all the characters
of string1 to upper case.

Syntax of strupr():

strlwr(): It takes a string as input and converts all the letters in the string to
lowercase.
Syntax of strlwr():
Strlwr(string); eg strlwr(‘RICH’); Output is rich

strcmp strcmp(string1, Returns 0 if string1 and string2 are the

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 36


C Programming

() string2) same;
less than 0 if string1<string2; greater
than 0 if string1>string2
Note:
if Return value if < 0 then it indicates string1 is less than string2
if Return value if > 0 then it indicates string2 is less than string1
if Return value if = 0 then it indicates string1 is equal to string2

What is a Structure in C?
A Structure is a user-defined data type in C/C++ that is used to store similar,
different data types or a combination of both under a single variable. .
Or
Structures (also called structs) are a way to group several related variables into
one place. Each variable in the structure is known as a member of the structure.

Syntax of Declaring a Structure


struct [structure name] Example of Structure
{ struct student
type member_1; {
type member_2; int rollno;
... char name[57];
type member_n; string phone;
}; };

What Is a Union?
A Union is a type of data that is user-defined. It is just like the structure. The
Union combines various objects of different sorts and sizes together. A user can
define a Union using many members, but only one of them holds a value at any
given time. It provides you with an efficient way of using a single memory location
for various purposes. Thus, varying objects can share a similar location. Syntax
of Declaring a Union
union [union name] Example of Union
{ union Student {
type member_1; char name[25];
type member_2; int age;

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 37


C Programming

... string email;


type member_n; };
};

Difference Between Structure and Union in C


Parameter Structure Union
Keyword A user can deploy the A user can deploy the
keyword struct to define a keyword union to define a Union.
Structure.
Internal The implementation of In the case of a Union, the
Implementatio Structure in C occurs internally- memory allocation occurs for only
n because it contains separate one member with the largest size
memory locations allotted to among all the input variables. It
every input member. shares the same location among
all these members/objects.
Accessing A user can access individual A user can access only one
Members members at a given time. member at a given time.
Syntax The Syntax of declaring a The Syntax of declaring a Union in
Structure in C is: C is:
struct [structure name] union [union name]
{ {
type element_1; type element_1;
type element_2; type element_2;
. .
. .
} variable_1, variable_2, …; } variable_1, variable_2, …;
Size A Structure does not have a A Union does not have a separate
shared location for all of its location for every member in it. It
members. It makes the size of a makes its size equal to the size of
Structure to be greater than or the largest member among all the
equal to the sum of the size of data members.
its data members.
Value Altering Altering the values of a single When you alter the values of a
member does not affect the single member, it affects the
other members of a Structure. values of other members.
Storage of In the case of a Structure, there In the case of a Union, there is an
Value is a specific memory location allocation of only one shared
for every input data member. memory for all the input data
Thus, it can store multiple members. Thus, it stores one
DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 38
C Programming

values of the various members. value at a time for all of its


members.
Initialization In the case of a Structure, a In the case of a Union, a user can
user can initialize multiple only initiate the first member at a
members at the same time. time.

Initialize a structure variable


1. Initialize structure using dot operator
In C, we initialize or access a structure variable either through dot . or arrow -
> operator. This is the most easiest way to initialize or access a structure.
Example:
// Declare structure variable
struct student stu1;

// Initialize structure members


stu1.name = "Pankaj";
stu1.roll = 12;
stu1.marks = 79.5f;

2. Value initialized structure variable


you can initialize a structure to some default value during its variable declaration.
Example:
// Declare and initialize structure variable
struct student stu1 = { "Pankaj", 12, 79.5f };

Pointers
A pointer is a variable that contains the address of a variable. This variable can be
of type int, char, array, function, or any other pointer.

Declaring a pointer: The pointer in c language can be declared using * (asterisk


symbol). It is also known as indirection pointer used to dereference a pointer.
1. int *a;//pointer to int
2. char *c;//pointer to char

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 39


C Programming

Pointer Operators • & (address operator) – Returns the address of operand

DR. VIDYA PAWAR, VEDANTA DEGREE COLLEGE 40

You might also like