0% found this document useful (0 votes)
3 views29 pages

C Notes

The document provides an introduction to programming, covering key concepts such as programming languages, algorithms, flowcharts, and the C programming language. It explains different types of computer languages, programming language translators, and the structure of a C program, including its elements, input-output operations, and control statements. Additionally, it highlights the characteristics and uses of C, emphasizing its importance in software development and system applications.

Uploaded by

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

C Notes

The document provides an introduction to programming, covering key concepts such as programming languages, algorithms, flowcharts, and the C programming language. It explains different types of computer languages, programming language translators, and the structure of a C program, including its elements, input-output operations, and control statements. Additionally, it highlights the characteristics and uses of C, emphasizing its importance in software development and system applications.

Uploaded by

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

!!!!HORAAA GAMBAARE GAMBAARE!!!!!

INTRODUCTION TO PROGRAMMING

A language that is acceptable to a computer system is called a computer language or programming


language and the process of creating a sequence of instructions in such a language is called
programming or coding. A program is a set of instructions, written to perform a specific task by the
computer. A set of large programs is called software. To develop software, one must have knowledge of
a programming language.

COMPUTER LANGUAGES
Computer language is defined as syntax or code in which we can write programs or specific applications.
It is used to communicate with the computers and is broadly classified into 3 types:

Machine Language: The machine language is sometimes referred as the machine code or object
code which is a set of binary digits

0's 1's. These binaries, digit is read by the compiler and interpreted easily. It is Considered as native
Language as it can be directly understood by the computer.

Assembly Language: It is Considered as Low-Level language for micro- processors and also
considered as the Second-generation Language. The assembly Language was mostly famous writing and
operating system and also writing most of the desktop applications. The operations Carried out by
programmers using assembly Language are memory management registry access and Clock Cycle
Operations. The drawback of assembly Language is that the codes Cannot be refused and it is not so
easy to understand.

Machine Language: The development of high-level languages was done when the programmers face
the issue of writing programmes as the older languages have portability issues, which means the code
written on one machine cannot be transferred too other. This leads to the development of high-level
languages in which the code can be written more easily and is very user friendly. Since high level
languages is machine independent example of high-level languages are C, C++, Java, etc.

PROGRAMMING LANGUAGE TRANSLATORS


A translator is a program that converts source code written in a high-level programming language into
machine code, which can be executed by a computer. There are different types of translators, including
compilers, interpreters, and assemblers.

Compiler: A compiler is a translator that converts the entire program written in a high-level language
into machine code. It also reports any errors encountered during the translation process. Programming
languages like C and C++ use compilers.
Interpreter: An interpreter is a translator that converts the program written in a high-level language
into machine code line by line. It directly executes the operations specified in the source program when
the input is given by the user. Programming languages like Python, BASIC, and Ruby use interpreters.

Assembler: An assembler is a translator that converts assembly language code into


machine language code.

Linker: A linker or link editor is a computer program that takes one or more object files generated by a
compiler and combines them into a single executable file, library file, or another object file.

ALGORITHM.
An algorithm is a sequence of steps to solve a particular problem or algorithm is an ordered set of
unambiguous steps that produces a result and terminates in a finite time.

Algorithm has the following characteristics

• Input: An algorithm may or may not require input


• Output: Each algorithm is expected to produce at least one result
• Definiteness: Each instruction must be clear and unambiguous.
• Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after
finite number of steps.

The algorithm and flowchart include following three types of control structures.

Sequence: In the sequence structure, statements are placed one after the other and the execution
takes place starting from up to down.

Branching (Selection): Selection control structure is used to execute a particular set of statements
based on a condition. It is also known as conditional control structure. The most common selection
control structures are if-else and switch-case 1.

Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed repeatedly based on
certain loop condition e.g., WHILE, FOR loops.

Advantages of algorithm.
• It is a step-wise representation of a solution to a given problem, which makes it easy to understand.

• An algorithm uses a definite procedure.

• It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
• Every step in an algorithm has its own logical sequence so it is easy to debug.

FLOWCHART.
The first design of flowchart goes back to 1945 which was designed by John Von Neumann. Unlike an
algorithm, Flowchart uses different symbols to design a solution to a problem. It is another commonly
used programming tool. Flowchart is diagrammatic /Graphical representation of sequence of steps to
solve a problem. To draw a flowchart following standard symbols are used.

Advantages of flowchart.
• Flowchart is an excellent way of communicating the logic of a program.

• Easy and efficient to analyze problem using flowchart.

• During program development cycle, the flowchart plays the role of a blueprint, which makes program
development process easier

• It is easy to convert the flowchart into any programming language code.

INTRODUCTION TO C.
C programming is a general-purpose, procedural programming language created in the early 1970s by
Dennis Ritchie at Bell Labs. It is renowned for its simplicity, efficiency, and low-level features, making it
well-suited for system programming and developing operating systems.

WHY IS C POPULAR.
•It is reliable, simple and easy to use.

•C is a small, block-structured programming language.


•C is a portable language, which means that C programs written on one system can be run on other
systems with little or no modification.

WHY TO STUDY C.
•Many software houses use C as the preferred language for producing word processing programs,
spreadsheets, compilers, and other products.

•C is an extremely flexible language—particularly if it is to be used to write operating systems.

•Unlike most other languages that have only four or five levels of precedence, C has 15.

CHARECTERESTICS OF A C PROGRAM.
Here are some of the most important features/characteristics of the C language:

Procedural Language: In a procedural language like C, predefined instructions are carried out step
by step.

Fast and Efficient: C is known for its fast compilation and execution in comparison to other
programming languages.

Modularity: C supports modular programming, which means a big program can be divided into
different modules or functions.

Statically Typed: C is a statically typed language, which means that the data type of a variable is
determined at compile time.

General-Purpose: C is a general-purpose programming language that can be used to write a


variety of applications

USES.
The C programming language is used for developing system applications that forms a major portion of
operating systems such as Windows, UNIX and Linux. Below are some examples of C being used:

•Database systems

•Graphics packages

•Word processors

•Spreadsheets

•Operating system development

STRUCTURE COMPILATION AND EXECUTION OF A C PROGRAM.


The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.

Based on this structure, we can sketch a C program.

Example:

/* This program accepts a number & displays it to the user*/

#include<stdio.h>

void main(void)

int number;

printf( "Please enter a number: " );

scanf( "%d", &number );

printf( "You entered %d", number );

return 0;

Stepwise explanation:
#include:-
#include is a preprocessor directive used to include the contents of a header file
in your program.
<stdio.h>:-
<stdio.h> is a standard header file that stands for "standard input/output header." It provides
functions and macros for performing input and output operations.

Void:-
void is a keyword used to indicate that a function does not return a value or that a pointer does
not point to any data type.

Main:-
main is a special function that serves as the entry point for the execution of a C program. The
main function is where the program starts its execution, and it must be present in every C program.’

(void):-
(void) is used in function declarations to indicate that the function takes no parameters. It
explicitly specifies that the function does not accept any arguments.

{ (Brace):-
the curly braces {} are used to define a block of code. They are used to enclose a set of
statements, creating a compound statement or block.

; (semicolon):-
the semicolon (;) is used as a statement terminator. It signifies the end of a statement and
separates individual statements in C code.

Scanf:-
the scanf function is used to read formatted input from the standard input (keyboard) or other
input streams. It allows you to receive values entered by the user during program execution.

Printf:-
the printf function is used to perform formatted output to the standard output (usually the
console). It allows you to display information, variables, and messages to the user.

FILES USED IN A C PROGRAM.


Source File- This file contains the source code of the program. The file extension of any c file is .c. The
file contains C source code that defines the main function & maybe other functions. 19

Header File- A header file is a file with extension .h which contains the C function declarations and
macro definitions and to be shared between several source files.
Object File-An object file is a compiled file that results from the compilation of one or more source
code files. The compilation process involves translating the human-readable C code into machine-
readable instructions. The output of this process is an object file, typically with a .o extension.

Executable File- The binary executable file is generated by the linker. The linker links the various
object files to produce a binary file that can be directly executed.

COMPLIATION & EXECUTION OF A C PROGRAM.

ELEMENTS OF C.
Every language has some basic elements & grammatical rules. Before starting with programming, we
should be acquainted with the basic elements that build the language.

Character Set:
Communicating with a computer involves speaking the language the computer understands. In C,
various characters have been given to communicate.

Keywords:
Keywords are the words whose meaning has already been explained to the C compiler. The keywords
cannot be used as variable names because if we do so we are trying to assign a new meaning to the
keyword, which is not allowed by the computer. There are only 32 keywords available in C.

Identifier:
Identifiers in C programming are names given to various program elements such as variables,
functions, arrays, etc. They serve as labels to identify and refer to different parts of the program.

Data Type:
Data types in C programming specify the type of data that a variable can hold. They are essential for
memory allocation and defining the operations that can be performed on the data. We can use 2
qualifiers with these basic types to get more types. There are 2 types of qualifiers

Sign qualifier- signed & unsigned

Size qualifier- short & long

Constants:
A constant is an entity that doesn‘t change whereas a variable is an entity that may change.

C constants can be divided into two major categories:

Primary Constants
Secondary Constants

Variables
Variables in C are symbolic names that represent storage locations in the computer's memory. They are
used to store and manipulate data within a program.

Declaring Variables:
There are two places where you can declare a variable:

• After the opening brace of a block of code (usually at the top of a function)

• Before a function name (such as before main() in the program)

Initialization of Variables:
When a variable is declared, it contains undefined value commonly known as garbage value. If we want
we can assign some initial value to the variables during the declaration itself. This is called initialization
of the variable.

Eg int a=21;

Expressions:
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational.
Statements:
A statement is a single, complete line of code that performs a specific action. Statements are the
building blocks of a C program and are executed sequentially.

Compound Statements:
A compound statement, also known as a block, is a group of zero or more statements enclosed within
curly braces {}. A compound statement allows multiple statements to be treated as a single logical unit.

INPUT-OUTPUT IN C.
Input and output operations are fundamental for interacting with the user and displaying results. The
standard input/output functions are provided by the stdio.h (standard input/output) library.

Explanation:
 Every program starts from main() function.

printf() is a library function to display output which only works if #includeis included at the beginning.

 Here, stdio.h is a header file (standard input output header file) and #include is command to paste the
code from the header file when necessary. When compiler encounters printf()function and doesn't
find stdio.h header file, compiler shows error.

 return 0; indicates the successful execution of the program.

FORMATTED INPUT-OUTPUT.
Formatted input and output refers to the ability to control the appearance of data when it is displayed
(output) or read (input). The printf and scanf functions are commonly used for formatted input/output.

OPERATORS.
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of operators:

• Arithmetic Operators: - These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus.
• Relational Operators: -These operators are used to compare the value of two variables.

• Logical Operators: - These operators are used to perform logical operations on the given two
variables.

• Bitwise Operators: -Bitwise operator works on bits and performs bit-by-bit operation. Bitwise
operators are used in bit level programming. These operators can operate upon int and char but not on
float and double.

• Assignment Operators: -In C programs, values for the variables are assigned using assignment
operators.

• Increment and decrement operators: -


1.increment operator: -the increment operator (++) is used to increase the value of a variable by 1. It can
be applied to both integers and floating-point numbers. There are two forms of the increment operator:
pre-increment and post-increment.

2.decrement operator: -the decrement operator (--) is used to decrease the value of a variable by 1.
Similar to the increment operator, the decrement operator can be applied to both integers and floating-
point numbers. There are two forms of the decrement operator: pre-decrement and post-decrement.

• Conditional operators: -Conditional operators are used in decision making in C programming, i.e,
executes different statements according to test condition whether it is either true or false.

• Misc Operators: It is a unary operator which is used in finding the size of data type, constant, arrays,
structure etc.

Operators Precedence in C.
Operator precedence determines the order in which operations are performed in an expression.
Operators with higher precedence are evaluated before those with lower precedence.
CONTROL STATEMENTS.
Control statements are used to control the flow of execution in a program. They determine the order in
which statements are executed based on certain conditions or loops.

SELECTION STATEMENTS.
The selection statements are also known as Branching or Decision Control Statements. Decision control
statements in programming are used to control the flow of execution based on certain conditions. They
allow a program to make decisions and choose different paths depending on whether a condition
is true or false.

if Statement:
The if statement in C is a fundamental decision control statement. It allows you to execute a block of
code if a specified condition is true.
if-else Statement:
The if-else statement in C allows you to make decisions by executing one block of code if a condition is
true and another block if the condition is false.

Nested if-else:
In C programming, you can use nested if-else statements to create multiple levels of decision-making.
else-if Statement:
The else if statement in C allows you to check multiple conditions in a structured way. It's used when
you have a series of conditions to test, and you want to execute the block of code associated with the
first true condition

Switch Case:
The switch statement in C allows you to select one of many code blocks to be executed based on the
value of an expression. It provides an alternative to using multiple if-else if statements when you have to
choose among multiple cases.
ITERATIVE STATEMENTS

While statement:
The while statement is used when the program needs to perform repetitive tasks. The general form of a
while statement is:

while (condition) statement;

The program will repeatedly execute the statement inside the while until the condition becomes false
(0). (If the condition is initially false, the statement will not be executed.)

Consider the following program:


Do-while Loop:
In C programming, the do-while loop is a control flow statement that executes a block of code
repeatedly until a specified condition becomes false. It is a post-check loop, meaning the block of code
will execute at least once, even if the condition is initially false.

Syntax of do-while loop is:

#include <stdio.h>

int main() {

int i = 1;

// A do-while loop to print numbers from 1 to 5

do {

printf ("%d\n", i);

i++;

} while (i <= 5);

return 0;

Output:

2
3

For loop:
In C programming, a for loop is a control flow statement that allows you to repeatedly execute a block of
code. t's commonly used when the number of iterations is known beforehand.

The syntax for for-loop is:

#include <stdio.h>

int main() {

// A for loop to print numbers from 1 to 5

for (int i = 1; i <= 5; i++) {

printf("%d\n", i);

return 0;

Output:

Nesting of loops.
Nested loops in programming refer to loops that are placed inside another loop's body. This structure
allows for more complex iterations, often used when dealing with multidimensional arrays, or
performing tasks that require repeated operations.

Eg;

#include <stdio.h>

int main() {

int rows = 3;
int columns = 4;

// Nested loops to create a 3x4 grid

for (int i = 0; i < rows; i++) {

for (int j = 0; j < columns; j++) {

printf("(%d, %d) ", i, j);

printf("\n"); // Move to the next line after printing a row

return 0;

Output

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

Jump Statements.
The break Statement:
In C, the break statement is used within loops (like for, while, or do-while) and switch statements to
immediately exit the loop or switch block's execution. It allows you to prematurely terminate the loop or
switch statement's normal execution based on certain conditions.

Syntax

#include <stdio.h>

int main () {

for (int i = 1; i <= 10; i++) {

printf ("%d ", i);

if (i == 5) {

break; // Exit the loop when I reach 5

return 0;
}

Output

12345

The Continue Statement:


In C, the continue statement is used within loops to skip the current iteration and proceed to the next
iteration of the loop. When encountered, continue causes the loop to immediately jump to the next
iteration's beginning

Syntax

#include <stdio.h>

int main () {

for (int i = 1; i <= 5; i++) {

if (i == 3) {

continue; // Skip iteration when i is 3

printf ("%d ", i);

return 0;

Output

1245

The goto statement:


The goto statement in C is used to transfer the control of the program to a labeled statement within the
same function. It's a direct and unconditional jump statement that can transfer the control anywhere
within the same function, bypassing normal sequence-based execution.

Syntax

#include <stdio.h>

int main() {

int i = 1;

start: // This is a label

printf("%d ", i);


i++;

if (i <= 5) {

goto start; // Jump to the 'start' label

return 0;

Output

12345

Function
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main (), and all the most trivial programs can define additional functions.

Function Declaration OR Function Prototype:


1. It is also known as function prototype.

2. It inform the computer about the three things

a) Name of the function.

b) Number and type of arguments received by the function.

c) Type of value return by the function.

3. Calling function need information about called function. If called function is place before calling
function then the declaration is not needed.

Function Definition:
1. It consists of code description and code of a function.

It consists of two parts

a) Function header

b) Function coding

2. Function definition can be placed anywhere in the program but generally placed after the main
function.

3. Local variable declared inside the function is local to that function. It cannot be used anywhere in the
program and its existence is only within the function.

4. Function definition cannot be nested.


User Defined Function Vs Standard Function:
User Define Function:
A function that is declared, calling and define by the user is called user define function. Every user define
function has three parts as:

1. Prototype or Declaration.

2. Calling.

3. Definition.

Standard Function:
In C programming, standard functions refer to predefined functions available in the C standard library
that provide common functionalities. These functions serve various purposes, such as input/output
operations, string manipulation, memory allocation, mathematical operations, and more. Some e.g., are
Printf (), Scanf () etc.

Function Categories
There are four main categories of the functions these are as follows:

1. Function with no arguments and no return values.

2. Function with no arguments and a return value.

3. Function with arguments and no return values.

4. Function with arguments and return values.

Actual Arguments and Formal Arguments


Actual Arguments:
An actual argument, also known as an argument, is the value that is passed to a function when it is
called. It is the real data that will be used by the function during its execution

Formal Arguments:
A formal argument, also known as a parameter, is a variable that is listed in the function declaration. It
acts as a placeholder for the value that will be passed to the function when it is called.

Parameter Passing Techniques:


1. call by value

2. call by reference

Call by value:
Here value of actual arguments is passed to the formal arguments and operation is done in the formal
argument. Since formal arguments are photo copy of actual argument, any change of the formal
arguments does not affect the actual arguments

Call by reference:
Here instead of passing value address or reference are passed. Function operators or address rather
than values.

Recursion
Recursion in C refers to a programming technique where a function calls itself directly or indirectly to
solve a problem. In C, just like in many other programming languages, a function can call itself, creating
a loop-like sequence until a specific condition is met to stop the recursive calls.

Example:

Here the function fun1() is calling itself inside its own function body, so fun1() is a recursive function.

Winding Phase and Unwinding Phase:


All recursive functions work in two phases- winding phase and unwinding phase.
Winding Phase: This is the phase where recursive calls are made. When a function invokes itself within
its own body, it initiates a new call stack frame. The function's parameters, local variables, and the
return address are stored in this new stack frame.

Unwinding Phase: This phase involves resolving the recursive calls. As the base case(s) are reached, the
recursion starts to resolve backward. When a base case is met, the function starts returning values,
which 'unwinds' the stack.

Implementation of Recursion:
We came to know that recursive calls execute like normal function calls, so there is no extra technique
to implement recursion. All function calls(Whether Recursive or Non-Recursive) are implemented
through run time stack.

Recursion Verses Iteration:


In both recursion and iteration, the same block of code is executed repeatedly, but in recursion
repetition occurs when a function calls itself and in iteration repetition occurs when the block of code is
finished or a continue statement is encountered.

For complex problems iterative algorithms are difficult to implement but it is easier to solve recursively.
Recursion can be removed by using iterative version.

Tail Recursion:
A recursive call is said to be tail recursive if the corresponding recursive call is the last statement to be
executed inside the function.

Indirect and Direct Recursion:


If a function fun1() calls another function fun2() and the function fun2() in turn calls function fun1(),
then this type of recursion is said to be indirect recursion, because the function fun1() is calling itself
indirectly.

If a function calls itself directly i.e., function fun1() is called inside its own function body, then that
recursion is called as direct recursion.

Arrays
Introduction
An array is a data structure that is a collection of variables of one type that are accessed through a
common name. Each element of an array is given a number by which we can access that element which
is called an index. It solves the problem of storing a large number of values and manipulating them.

Arrays
An array is a group of memory locations related by the fact that they all have the same name and same
type. To refer to a particular location or element in the array we specify the name to the array and
position number of particular element in the array.

One Dimensional Array


A one-dimensional array in C is a collection of elements of the same data type arranged in a linear
sequence. Each element in the array is accessed using an index or a subscript

Declaration:
Before using the array in the program, it must be declared

Syntax:

data_type array_name[size];

Size represents the number of elements that can be stored in the array.

Initialization:
We can explicitly initialize arrays at the time of declaration.

Syntax:

data_type array_name[size]={value1, value2,….....valueN};

Value1, value2, valueN are the constant values known as initializers, which are assigned to the array
elements one after another.

NOTE:

1. In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then
the compiler assumes the size of array equal to the number of initializers.

2. We can ‘t copies the elements of one array to another array by simply assigning it.

Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements
present in the array and in each pass one element is processed.

Two dimensional Arrays


A two-dimensional array is essentially an array of arrays. It can be visualized as a grid with rows and
columns. Each element in the array is identified by two indices: one for the row and one for the column

Declaration:

The syntax is same as for 1-D array but here 2 subscripts are used.

Syntax:

data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows Columnsize

Initialization:
arrays can be initialized in a way similar to 1-D arrays.

Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the
inner loop indicates the columns.

Multidimensional Arrays
More than 2-dimensional arrays are treated as multidimensional arrays.

Example:

int a[2][3][4];

Here a represents two 2-dimensional arrays and each of these 2-d arrays contains 3 rows and 4 columns.

Initialization:
The rule of initialization of multidimensional arrays is that last subscript varies most frequently and the
first subscript varies least rapidly.

Arrays Using Function


1-d arrays using functions
Passing individual array elements to a function
Passing whole 1-D array to a function
We can pass whole array as an actual argument to a function the corresponding formal arguments
should be declared as an array variable of the same type.
Strings
A string is a series of characters treated as a single unit. A string may include letters, digits and various
special characters such as +, -, *, / and $. String literals or string constants in C are written in double
quotation marks

In C language strings are stored in array of char type along with null terminating character ‗\0‘ at the
end. When sizing the string array, we need to add plus one to the actual size of the string to make space
for the null terminating character, ‗\0‘.

Syntax:

char fname[4];

The above statement declares a string called fname that can take up to 3 characters. It can be indexed
just as a regular array as well.

Reading strings:
If we declare a string by writing

char str[100];

then str can be read from the user by using three ways;

1. Using scanf() function


2. Using gets() function

3. Using getchar(), getch(), or getche() function repeatedly

Writing string:
The string can be displayed on screen using three ways:

1. Using printf() function

2. Using puts() function

3. Using putchar() function repeatedly

COMMON FUNCTIONS IN STRING


strcpy(): It is used to copy one string to another string. The content of the second string is copied to the
content of the first string.

Syntax:

strcpy (string 1, string 2);

strcmp(): It is used to compare the contents of the two strings. If any mismatch occurs then it results the
difference of ASCII values between the first occurrence of 2 different characters.

Syntax:

int strcmp(string 1, string 2);

strcat(): It is used to concatenate i.e, combine the content of two strings.


Syntax:

strcat(string 1, string 2);

strlen(): It is used to return the length of a string.


Syntax:

int strlen(string);

strchr(): It is used to find a character in the string and returns the index of occurrence of the character
for the first time in the string.

Syntax:

strchr(cstr);

strstr(): It is used to return the existence of one string inside another string and it results the starting
index of the string.

Syntax:
strstr(cstr1, cstr2);

YAMETO KUDASAI!!!!!!!!!

You might also like