0% found this document useful (0 votes)
27 views33 pages

LDP - Unit-1 & Unit-2

The document provides an introduction to the C programming language, covering its history, importance, types of programming languages, and the roles of compilers and interpreters. It also discusses C tokens, keywords, identifiers, ASCII codes, flowcharts, and algorithms, along with their characteristics, advantages, and examples. Additionally, it includes practical examples of algorithms for various tasks, emphasizing the structured approach to problem-solving in programming.
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)
27 views33 pages

LDP - Unit-1 & Unit-2

The document provides an introduction to the C programming language, covering its history, importance, types of programming languages, and the roles of compilers and interpreters. It also discusses C tokens, keywords, identifiers, ASCII codes, flowcharts, and algorithms, along with their characteristics, advantages, and examples. Additionally, it includes practical examples of algorithms for various tasks, emphasizing the structured approach to problem-solving in programming.
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/ 33

Subject: Logic Development Programming

Prepared By: Prof. Ankit Patel


BCA- SEM-1

UNIT-1 Introduction of C
 History and Importance of C:

 History: C was developed in the early 1970s by Dennis Ritchie at AT&T Bell Labs.
It is a successor of the B language and was designed to be a system programming
language to write operating systems.

 Importance:

o C is highly efficient and portable, making it suitable for system and application
software.
o Many other programming languages (like C++, Java, and Python) were
influenced by C.
o C allows direct memory access and manipulation, making it ideal for low-level
programming.

 Different Types of Languages in C:

 High-Level Language: A programming language designed for ease of use, with


syntax close to natural languages. Examples include Python, Java, and C++, and they
require a compiler or interpreter to convert code into machine code.
 Assembly-Level Language: A low-level language using mnemonics and symbols to
represent machine code instructions. It is processor-specific and requires an
assembler to convert into machine code.

Page 1
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Machine-Level Language: The lowest-level language consisting of binary code (0s


and 1s) directly understood by the CPU. It is difficult for humans to write but is
directly executed by the computer.

 Compiler and Interpreter:

 The computer understands only machine language. So, a translator is needed to


translate the symbolic statements of a high level language into computer executable
machine language.
 The programs that translate high-level programs into machine language are called
interpreters and compilers.
 Compiler: A compiler is a program which translates the source code written in a
high-level language into computer-readable machine language that can be directly
loaded and executed.

Page 2
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Interpreter: An interpreter translates a high-level language statement in a source


program to a machine code and executes it immediately, before translating the next
source language statement. When an error is found, the execution of the program is
halted and an error message is displayed on the screen of the computer.

 Header Files in C:
 Header files are essential components that help organize and manage the structure of
a program. A header file typically contains declarations of functions, variables,
macros, constants, and types that are shared across multiple source files in a project.

 Purpose of Header Files:

1) Code Reusability
2) Modularization
3) Efficient Compilation

 How Header Files Work:

 Header files are typically included in a C program using the #include preprocessor
directive.

Page 3
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 When you use #include <filename.h>, the compiler searches for the specified header
file in the system directories (for standard library headers).
 When you use #include "filename.h", the compiler looks for the header in the current
directory first, then in the system directories.

 Common Header Files:

o <stdio.h>: Standard input-output functions (e.g., printf, scanf).


o <stdlib.h>: Functions for memory allocation, process control, etc.
o <math.h>: Mathematical functions (e.g., sqrt, sin).
o <string.h>: Functions for manipulating strings (e.g., strlen, strcpy).
o <ctype.h>: Functions for character classification (e.g., isalpha, isdigit).

 C Tokens:
 Tokens are the smallest units in a C program. The different types of C tokens are:

1. Keywords: Reserved words like int, if, while.


2. Identifiers: Names given to variables, functions, etc.
3. Constants: Fixed values like 5, 3.14, 'A'.
4. Operators: Symbols like +, -, *, /.
5. Punctuation/Separators: Symbols like ;, {, }.

 Keywords and Identifiers in C:

 Keywords:

o Keywords are predefined or reserved words that have special meanings to the
compiler.

Page 4
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

o These keywords cannot be used as variable names, function names, or any other
identifiers within the program except for their intended purpose.
o There are 32 keywords in C.
o A list of keywords in C or reserved words in the C programming language are
mentioned below:

 Identifiers:

o An identifier is a name used to identify variables, functions, arrays,


structures, etc. It helps the compiler distinguish between different elements in
the code.
o Identifiers are unique names that are assigned to variables, structs, functions,
and other entities.

Rules for Naming Identifiers:

o An identifier must begin with a letter (uppercase or lowercase) or an


underscore (_).
o After the first character, the identifier can contain letters, digits (0-9), and
underscores.
o Identifiers are case-sensitive, meaning variable, Variable, and VARIABLE are
considered different identifiers.
o An identifier cannot be a keyword in C (e.g., int, if, return, etc.).
o Identifiers should not begin with a digit (e.g., 1stNumber is not valid, but
firstNumber is).

Page 5
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Examples of Identifiers:

o Variable: int age;


o Function: void calculate();
o Array: int numbers[10];
o Structure: struct Student { int id; char name[50]; };

 ASCII Codes:

 In C programming, ASCII (American Standard Code for Information Interchange) codes


are used to represent characters as numerical values.
 ASCII is a 7-bit character encoding system that assigns a unique integer value to each
character, including letters, digits, punctuation, and control characters.

Key Points:

o ASCII codes range from 0 to 127.


o Each character is assigned a specific code, making it easy to store and
manipulate text in C programs.
o C allows you to use ASCII codes directly in your program, particularly useful
for character processing.

Common ASCII Codes:

o Digits: '0' to '9' are represented by ASCII codes 48 to 57.


o Uppercase Letters: 'A' to 'Z' are represented by ASCII codes 65 to 90.
o Lowercase Letters: 'a' to 'z' are represented by ASCII codes 97 to 122.
o Control Characters: Include codes like 0 (NULL), 9 (TAB), 10 (Line Feed),
and 13 (Carriage Return).

Usage in C Programming:

o Displaying ASCII Values: You can use printf to print the ASCII value of a
character.

Example- char ch = 'A';


printf("ASCII value of %c is %d\n", ch, ch);

// Output: ASCII value of A is 65

Page 6
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

o Converting Case: By adding or subtracting 32, you can convert between


uppercase and lowercase characters.

Example- char upper = 'A';


char lower = upper + 32; // Converts 'A' to 'a'
printf("Lowercase: %c\n", lower);

// Output: Lowercase: a

 Introduction to Flowchart:

 ”It is defined as the pictorial representation of a process, which describes the sequence
and flow of control and information within the process.”
 The flow of information is represented inside the flowchart in a step by step form.
 Flowchart uses different symbols for depicting different activities, which are performed
at different stages of a process.

Advantages of Flowchart:

o The flowchart is a good way of conveying the logic of the system.


o Facilitates the analysis of the problem.
o Provides a proper documentation.
o Easy identification of the errors and bugs.
o It directs the program development.
o Maintenance of the program becomes easy.
o Disadvantages of Flowchart
o The complex logic could result in the complex flow chart.
o A flowchart must be recreated to employ modification and alterations.

The various symbols used in a flowchart are:

Page 7
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 1: Draw a flowchart to add two integers and display the result.

Example 2: Draw a flowchart to find out whether a given number is even or odd.

Page 8
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 3: Draw a flowchart to check positive number

Example 4: Draw a flowchart to print Area of Square

Page 9
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 5: Draw a flowchart to print Area of Rectangle

Page
10
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 6: Draw a flowchart to Calculate Simple Interest

Example 7: Draw a flowchart to subtract two numbers

Page
11
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Introduction to Algorithm:

 ”An algorithm is a sequence of steps written in the form of English phrases that specify
the tasks that are performed while solving a problem.”
 It helps the programmer in breaking down the solution of a problem into a number of
sequential steps.

Qualities of Good Algorithm

 Input and output should be defined precisely.


 Each step in the algorithm should be clear and unambiguous.
 Algorithms should be most effective among many different ways to solve a problem.
 An algorithm shouldn't include computer code. Instead, the algorithm should be written
in such a way that it can be used in different programming languages.

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.
 By using algorithm, the problem is broken down into smaller pieces or steps hence, it is
easier for programmer to convert it into an actual program

Disadvantages of Algorithm

 Writing algorithm takes a long time.


 An Algorithm is not a computer program, it is rather a concept of how a program should
be.
 An algorithm is a step-by-step procedure for solving a problem or task. Algorithms are
essential in programming for defining logic and functionality.

Characteristics and Usage of Algorithm:

 Clear and unambiguous: Each step must be clearly defined.


 Effective: Should be capable of being executed in a reasonable amount of time.

Page
12
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Correctness: The algorithm must solve the problem as intended, providing the correct
output for all valid inputs.
 Input and Output: Must have well-defined input and produce output.
 Efficiency: The algorithm should use minimal resources, such as time (fast execution)
and memory (low space usage).
 Finiteness: A good algorithm must terminate after a finite number of steps. It should not
run indefinitely.
 Robustness: The algorithm should handle unexpected or erroneous inputs gracefully,
providing meaningful error handling or results.

Examples of Algorithm:

Example 1: Write an algorithm to add two integers and display the result.

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values for num1, num2.
Step 4: Add num1 and num2 and assign the result to a variable sum.
Step 5: Display sum
Step 6: Stop

Example 2: Write an algorithm to find out whether a given number is even or odd.

Step 1: Start
Step 2: Take any number and store it in n
Step 3: if n=multiple of 2 print "even" else print "odd"
Step 4: Stop

Example 3: Write an algorithm to find out whether a given number is prime or not.

Step 1: Start
Step 2: Read number n
Step 3: Set f=0
Step 4: For i=2 to n-1
Step 5: If n mod 1=0 then
Step 6: Set f=1 and break
Step 7: Loop
Step 8: If f=0 then print 'The given number is prime' else print 'The given number is not prime'
Step 9: Stop

Page
13
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 4: Write an algorithm to find largest number amongst three numbers.


Step 1: Start
Step 2: Declare variables a, b and c.
Step 3: Read variables a, b and c.
Step 4: If a > b If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Example 5: Write an algorithm to determine whether the given year is leap year or not.

Step 1: Start
Step 2: Read year
Step 3: If the year is divisible by 4 then go to Step 4 else go to Step 7
Step 4: If the year is divisible by 100 then go to Step 5 else go to Step 6 Step 5: If the year is
divisible by 400 then go to Step 6 else go to Step 7
Step 6: Print "Leap year" Step 7: Print "Not a leap year"
Step 8: Stop

Example 6: Write an algorithm to determine whether a given string is a palindrome or


not.
Step 1: Start
Step 2: Accept a string from the user (str).
Step 3: Calculate the length of string str (len).
Step 4: Initialize looping counters left=0, right=len-1, and chk=’t’
Step 5: Repeat steps 6-8 while left<right and chk=’t’
Step 6: If str(left)=str(right) goto Step 8 else goto step 7
Step 7: Set chk=’f’
Step 8: Set left=left+1 and right=right+1
Step 9: If chk=’t’ goto Step 10 else goto Step 11
Step 10: Display “The string is a palindrome” and goto Step 12
Step 11: Display “The string is not a palindrome”
Step 12: Stop

Page
14
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 7: Write an algorithm to print Fibonacci series up to given number N.


Step 1: Start
Step 2: Declare variables N, N1, N2, N3, i.
Step 3: Read value of N from user.
Step 4: if N < 2, display message “Enter number > 2” and go to step 9.
Step 5: Initialize variables N1 = 0, N2 = 1, i = 0
Step 6: Display N1, N2
Step 7: Compute N3 = N1 + N2
Step 8: Repeat following statements until i < N - 2
Display N3
N1 = N2
N2 = N3
N3 = N1 + N2
i =i+1
Step 9: Stop

Example 8: Write an algorithm to find factorial of a given number N

Step 1: Start
Step 2: Declare variables: N, fact, i.
Step 3: Initialize variables
fact = 1
i=1
Step 4: Read value of N from user.
Step 5: Repeat following steps until i = N
fact = fact * i
i=i+1
Step 6: Print fact variable.
Step 7: Stop

Example 9: Write an algorithm to add given two numbers.

Step 1: Start.
Step 2: Read two numbers A and B.
Step 3: Total = A+B.
Step 4: Display Total.
Step 5: Stop.

Page
15
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example 10: Write an algorithm for Subtracting two Numbers.

Step 1: Start.
Step 2: Read two numbers A and B.
Step 3: Answer = A - B.
Step 4: Display Answer.
Step 5: Stop.

 Structure of a C Program:

 Any C program is consists of 6 main sections. Below you will find brief explanation of
each of them.

 Documentation Section: This section consists of comment lines which include the
name of programmer, the author and other details like time and date of writing the
program. Documentation section helps anyone to get an overview of the program.
 Link Section: The link section consists of the header files of the functions that are used
in the program. It provides instructions to the compiler to link functions from the system
library.

Page
16
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Definition Section: All the symbolic constants are written in definition section. Macros
are known as symbolic constants.
 Global Declaration Section: The global variables that can be used anywhere in the
program are declared in global declaration section. This section also declares the user
defined functions.
 main() Function Section: The entry point of the program, It is necessary have one main()
function section in every C program. This section contains two parts, declaration and
executable part. The declaration part declares all the variables that are used in executable
part. These two parts must be written in between the opening and closing braces.
 Subprogram Section: The subprogram section contains all the user defined functions
that are used to perform a specific task. These user defined functions are called in the
main() function.

Example of a Simple C Program:

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{

Page
17
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

int y = 55;
printf("Sum: %d", sum(y));

return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}

Output:

Sum: 75

Page
18
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

UNIT-2 Fundamentals of C
 Features of C:

 Simple and Easy to Learn: C has a simple syntax and structure, making it easy for
programmers to learn and use.
 Efficient and Fast: C programs are highly efficient in terms of memory and
execution speed. It provides low-level access to memory through pointers.
 Portable: C code can be run on any machine with minimal changes, making it highly
portable across different platforms.
 Structured Language: C supports structured programming, allowing programs to be
divided into functions for better organization and clarity.
 Rich Library: C has a vast standard library that provides many built-in functions for
tasks like input/output, string manipulation, and mathematical computations.
 Low-Level Access: C allows direct manipulation of hardware and memory using
pointers, which is useful for system-level programming.
 Recursion: C supports recursion, where functions can call themselves to solve
problems.
 Memory Management: C provides manual memory management using functions
like malloc(), free(), which gives the programmer control over memory allocation and
deallocation.
 Dynamic Memory Allocation: C allows dynamic memory allocation at runtime,
enabling more flexible use of memory resources.

 Types of Comments:

 Single-line Comment:
 A single-line comment starts with // and continues until the end of the line. It is used
to add brief descriptions or explanations of a single line of code.
Example-

Page
19
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

// This is a single-line comment


int x = 5; // Assign value to x

 Multi-line Comment:
 A multi-line comment begins with /* and ends with */. It can span multiple lines and
is typically used for longer explanations or for commenting out blocks of code.
Example-
/* This is a multi-line comment
It can span multiple lines
and is useful for detailed explanations */
int y = 10;

 Data Types:

 Each variable in C has an associated data type.


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

1. Primitive Data Types:

 These are the most basic data types provided by C, used to represent simple values
like numbers and characters.
 int: Represents integers (whole numbers). It usually occupies 4 bytes.
Example: int x = 10;
 char: Represents a single character (such as a letter, number, or symbol). It usually
occupies 1 byte.
Example: char letter = 'A';
 float: Represents a floating-point number (decimal). It usually occupies 4 bytes.

Page
20
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example: float pi = 3.14f;


 double: Represents a double-precision floating-point number. It usually occupies 8
bytes and provides more precision than float.
Example: double distance = 3.141592653589793;
 void: Represents the absence of a value, commonly used for function return types that
don’t return a value.
Example: void myFunction() {}

2. Derived Data Types:

 Derived data types are created from primitive data types and are used to store more
complex data structures.
 Array: A collection of elements of the same data type, stored in contiguous memory
locations.
Example: int numbers[5] = {1, 2, 3, 4, 5};
 Pointer: A variable that stores the memory address of another variable.
Example:
int x = 5;
int *ptr = &x;
 Function: A set of statements that perform a specific task. Functions are blocks of
code that can take inputs (parameters) and return an output (return type).
Example:
int add(int a, int b)
{
return a + b;
}

3. User-Defined Data Types:

 These are custom data types created by the user to represent more complex structures
or organize data more efficiently.
 Structure (struct): Allows grouping variables of different data types under one
name. Useful when you need to represent complex entities with different attributes.

Page
21
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example:
struct person
{
char name[50];
int age;
float height;
};
 Union: Similar to a structure, but all members of a union share the same memory space.
Only one member can hold a value at a time, saving memory space.
Example:
union data
{
int i;
float f;
char c;
};
 Enumeration (enum): A user-defined data type that consists of a set of named integer
constants. It provides a way to group related constants together under a single type.
Example:
enum day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

 Constants and Variables:

1. Constant:

 A constant is a value that cannot be changed during the execution of a program.


 Once a constant is defined, its value remains fixed and cannot be modified.
 Constants can be of any data type (such as int, char, float, etc.), but the key difference is
that they are immutable.

Types of Constants:

 Literal Constants: Values directly written in the program code (e.g., numbers,
characters).
Example: 5, 'A', 3.14

Page
22
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Defined Constants (using #define): Constants defined using the #define preprocessor
directive. This is commonly used to define symbolic names for constant values
Example:
#define PI 3.14159
This defines PI as a constant value, and throughout the program, PI will represent
3.14159.
 Constant Variables (using const): Constants defined using the const keyword. This
allows defining constants at a variable level, but the value cannot be changed once
initialized.
Example:
const int MAX_VALUE = 100;
 Enumerated Constants (enum): Constants defined within an enumeration (enum) type.
Example:
enum days { Sunday, Monday, Tuesday };

2. Variable:

 A variable is a named storage location in memory that holds a value, which can change
during the program's execution.
 The value of a variable can be modified at any point in the program.

Types of Variables:

 Local Variables: Variables that are declared within a function or block and are
accessible only within that scope.
Example:
void myFunction()
{
int a = 5; // 'a' is a local variable
}
 Global Variables: Variables that are declared outside of any function and are accessible
throughout the entire program, including inside functions.

Page
23
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example:
int globalVar = 10; // 'globalVar' is a global variable
 Static Variables: Variables that retain their value between function calls. They are
initialized only once and maintain their state across multiple calls to the function.
Example:
void myFunction()
{
static int count = 0;
count++;
printf("%d\n", count);
}

 Types of Operators:

 An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables.
 The values and variables used with operators are called operands.

1. Arithmetic Operator :
o The arithmetic operators are used to perform arithmetic/mathematical operations
on operands.
o Arithmetic operators are used to perform basic mathematical operations like
addition, subtraction, multiplication, division, and modulus. These operators
include +, -, *, /, and %, allowing calculations between numerical values.
o For example, a + b adds two variables, while a % b returns the remainder of the
division of a by b.

Page
24
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

2. Relational Operator :

o Relational operators are the symbols that are used for comparison between two
values to understand the type of relationship a pair of numbers shares.
o The result that we get after the relational operation is a boolean value, that tells
whether the comparison is true or false.

3. Logical Operator :

o Logical operators are used to combine multiple conditions or expressions. These


include && (AND), || (OR), and ! (NOT).
o They evaluate to true or false based on the logical relationship between the
operands, allowing for more complex condition checks in control flow
statements.

Page
25
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

4. Assignment Operator :

o Assignment operators are used to assign values to variables. The most common
assignment operator is =, which assigns the right operand's value to the left
variable.
o Compound assignment operators like +=, -=, *=, /=, and %= modify the value of
the left operand using the operation specified on the right.

5. Bitwise Operator:

o Bitwise operators perform operations at the bit level. They include & (AND), |
(OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).
o These operators are often used for low-level data manipulation, like modifying
individual bits of data types.

Page
26
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

6. Increment / Decrement Operator:

o Increment (++) and decrement (--) operators are used to increase or decrease the
value of a variable by 1, respectively.
o These can be used in two forms: pre-increment (++a) or post-increment (a++),
affecting the value before or after the expression, respectively.

7. Conditional (Ternary) Operator:

o Increment (++) and decrement (--) operators are used to increase or decrease the
value of a variable by 1, respectively.
o These can be used in two forms: pre-increment (++a) or post-increment (a++),
affecting the value before or after the expression, respectively.

8. Sizeof Operator:

o The sizeof operator is used to determine the size (in bytes) of a data type or
variable.
o It helps to understand the memory requirements of different data types, such as
sizeof(int) or sizeof(variable).

Page
27
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

9. Comma Operator:

o The comma operator (,) allows multiple expressions to be evaluated in a single


statement.
o It separates expressions and returns the result of the last one. It's often used in
loops or function calls where multiple operations need to be executed
sequentially.

 Evaluation of Expressions:

 the evaluation of expressions is a key aspect of understanding how the program


performs calculations or operations.
 An expression in C is a combination of variables, constants, operators, and function calls
that are evaluated to produce a value.
 The evaluation follows certain rules and operator precedence. Here's an overview:

Types of Expressions:

 Arithmetic expressions: Involve arithmetic operators like +, -, *, /, and %.


Example: x + y * z
 Relational expressions: Compare values using relational operators like >, <, >=, <=,
==, !=.
Example: x > y
 Logical expressions: Use logical operators && (AND), || (OR), and ! (NOT).
Example: x && y
 Assignment expressions: Involve the assignment operator =, +=, -=, etc.
Example: x = y + z
 Bitwise expressions: Operate on bits with operators like &, |, ^, <<, >>.
Example: x & y
 Conditional expressions: Use the ternary operator ?:.
Example: x > y ? z : w

Page
28
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Type Conversion:

 Type conversion in C refers to the process of converting one data type to another. This
can be done either implicitly or explicitly.
 Type conversion is essential in C because it allows you to work with different data types
in operations, assignments, and function calls.

1. Implicit Type Conversion :

 Also known as automatic type conversion, this occurs when the compiler automatically
converts one data type to another, typically from a smaller type to a larger type.
 This is done to preserve data accuracy during operations that involve multiple data
types.
Example-
int a = 5;
float b = 2.5;
float result;
result = a + b; // 'a' is implicitly converted to float before addition

2. Explicit Type Conversion :

 Also known as manual type casting, explicit type conversion is performed by the
programmer using a cast operator.
 This is necessary when the compiler doesn't perform an implicit conversion or when you
want to convert between types that are not automatically convertible.
Example-
double pi = 3.14159;
int intPi = (int) pi; // Explicit conversion from double to int

Page
29
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

 Precedence and Associativity:

 operator precedence and associativity determine the order in which operators are
evaluated in an expression.
 Understanding these concepts is essential to ensure that operations are performed
correctly and as expected.

1. Operator Associativity:

 Associativity defines the direction in which operators of the same precedence level are
evaluated. Operators can have left-to-right or right-to-left associativity.
 Left-to-Right Associativity: Most operators in C (like +, -, *, &&, etc.) follow left-to-
right associativity. This means if multiple operators with the same precedence appear,
they are evaluated from left to right.
Example:
int x = 5;
int y = 10;
int result = x + y - 3; // Left-to-right evaluation: (x + y) - 3

 Right-to-Left Associativity: Some operators, such as assignment =, conditional ?:, and


increment/decrement (++, -- when used as postfix) follow right-to-left associativity. This
means they are evaluated from right to left when there are multiple operators of the same
precedence.
Example:
int x = 5;
x = 10 + 3; // Right-to-left associativity for assignment: x = (10 + 3)

2. Operator Precedence:

 Operator precedence defines the priority in which operators are evaluated in an


expression. Operators with higher precedence are evaluated before operators with lower
precedence.

Page
30
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Precedence of C Operators:

 C has a well-defined hierarchy of operator precedence. Here’s a simplified list, starting


with the highest precedence:

 I/O functions:

 I/O functions (Input/Output functions) are used to interact with the user, read input from
the keyboard, and print output to the screen.
 These functions are part of the standard input-output library (stdio.h).

1 Printf() - Output to Console

 The printf() function is used to print output to the console or terminal.

Page
31
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

Example-
#include <stdio.h>
int main()
{
int age = 25;
printf("Hello, I am %d years old.\n", age);
return 0;
}

2. Scanf() - Input from Console

 The scanf() function is used to read user input from the keyboard.
Example-
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num); // Read integer input from user
printf("You entered: %d\n", num);
return 0;
}

3. Getchar() - Input a Single Character

 The getchar() function reads a single character from standard input (keyboard).
Example-
#include <stdio.h>
int main()
{
char c;

Page
32
Subject: Logic Development Programming
Prepared By: Prof. Ankit Patel
BCA- SEM-1

printf("Enter a character: ");


c = getchar(); // Read a single character
printf("You entered: %c\n", c);
return 0;
}

4. Putchar() - Output a Single Character

 The putchar() function prints a single character to the standard output (screen).
Example-
#include <stdio.h>
int main()
{
char c = 'A';
putchar(c); // Print a single character
putchar('\n'); // Print newline
return 0;
}

Page
33

You might also like