0% found this document useful (0 votes)
163 views25 pages

Bca C Unit 1

The document outlines a comprehensive curriculum for a BCA semester I course on Programming Concepts with C, covering topics such as data types, operators, control statements, arrays, strings, functions, pointers, and file management. It includes practical programming exercises and examples to reinforce learning, alongside a discussion of software types, programming languages, and problem-solving techniques. Additionally, it emphasizes the history and importance of the C language, along with guidelines for writing and executing C programs.

Uploaded by

myanadeepak01
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)
163 views25 pages

Bca C Unit 1

The document outlines a comprehensive curriculum for a BCA semester I course on Programming Concepts with C, covering topics such as data types, operators, control statements, arrays, strings, functions, pointers, and file management. It includes practical programming exercises and examples to reinforce learning, alongside a discussion of software types, programming languages, and problem-solving techniques. Additionally, it emphasizes the history and importance of the C language, along with guidelines for writing and executing C programs.

Uploaded by

myanadeepak01
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/ 25

103-PROGRAMMING CONCEPT WITH ”C”

BCA: SEMESTER I

Computer Concepts- Overview of C – Data types – Operators –


Decision making statement- loop statements – Arrays – Strings –
functions – Pointers – File Management.

M.C.Mouli, Department of Commerce & Computer


PROGRAMMING WITH C
Total Marks =100 (80 E + 20I), LAB-50 Marks
*****
UNIT-I: Computing Concepts: Types of Software, Programming Languages, Translator Programs,
Problem Solving Techniques, Using Computer.
Overview of C: History of C, Importance of C, Sample Programs, Basic Structure of C Programs,
Programming Style, Executing a ' C ' Program.
Constants, Variables, and Data Types : Introduction, Character set, C tokens, Keywords and Identifiers,
Constants, Variables, Data Types, Declaration of Variables, Declaration of Storage Class, Assigning
Values to Variables, Defining Symbolic Constant, Declaring Variable as Constant and Volatile, Overflow
and Underflow of Data.
Managing Input and Output Operations: Introduction, Reading a Character, Writing a Character,
Formatted Input and Output.
Operators and Expressions : Introduction, Arithmetic Operators, Relational Operators, Logical
Operators, Assignment Operators, Increment and Decrement Operator, Conditional Operators, Bitwise
Operators, Special Operators, Arithmetic Expressions, Evolution of expressions, Precedence of
Arithmetic Operators, Some Computational Problems, Type Conversions in Expressions, Operator
Precedence and Associativity, Mathematical Functions.

UNIT – II: Decision Making and Branching: Introduction, Decision Making with IF Statement, Simple If
Statement, The If....Else Statement, Nested of If....Else Statements, The else if Ladder, The Switch
Statement, The ? : Operator, The Goto Statement.
Decision Making and Looping: Introduction, The While statement, the do Statement, the For
Statement, Jumps in Loops.
Arrays: Introduction, One-dimensional Arrays, Declaration and Initialization of One dimensional Arrays,
Two-dimensional Arrays, Initializing two-dimensional Arrays, Multi-dimensional Arrays, Dynamic
Arrays.

UNIT- III Character Arrays and Strings: Introduction, Declaring and Initializing String Variables, Reading
Strings from Terminal, Writing Strings to Screen, Arithmetic Operations on Characters, Putting Strings
together, Comparison of Two Strings, String-handling Functions, Table of Strings, Other Features of
Strings.
User-Defined Functions : Introduction, Need for User-Defined Functions, A Multi-function Program,
Elements of user-defined Functions, Definition of Functions, Return Values and their Types, Function
Calls, Function Declaration, Category of Functions, No Arguments and No Return Values, Arguments
but No Return Values, Arguments with Return Values, No Arguments but Returns a Value, Functions
that Return Multiple Values, Nesting of Functions, Recursion, Passing Arrays to Functions, Passing
Strings to Functions, The Scope, Visibility and Lifetime of Variables, Multifile Programs.

UNIT- IV Pointers: Introduction, Understanding Pointers, Accessing the Address of a Variable, Declaring
Pointer Variables, Initialization of pointer Variables, Accessing a Variable through its pointer, Chain of
Pointers, Pointer Expressions, Pointer Increments and Scale Factor, Pointers and Arrays, Pointer and
Arrays, Pointers and Character Strings, Arrays of Pointers, Pointers as Function Arguments, Functions
Returning Pointers, Pointers to Functions, Pointers and Structures.
Structures and Unions : Introduction, Defining a Structure, Declaring Structure Variables, Accessing
Structure Members, Structure Initialization, Copying and Comparing Structure Variables, Operations on

B.C.A: Programming Concept using C 1


Individuals Members, Arrays of Structures, Arrays within Structures, Structures within Structures,
Structures and Functions, Unions, Size of Structures, Bit Fields.
File Management in C: Introduction, Defining and Opening a File, Closing a File, Input/output
Operations on Files, Error Handling during I/O Operations, Random Access to Files, Command Line
Arguments.

Text Book: 1. Computing Fundamentals & C Programming – by E Balagurusamy, 1st Edition McGrawHill
Education.
References: 1. Spoken Tutorial on “C”, as E-resource for Learning. http://spoken-tutorial.org
*****

PRACTICAL: PROGRAMMING WITH C


 All the concepts of programs from Text Book including exercises must be practice, execute and
write down in the practical record book.
 Faculty must take care about UG standard programs it should be minimum 25 – 30.
 In the external lab examination student has to execute at least three programs with
compilation and deployment steps are necessary.
 External Viva-voce is compulsory. Example programs:

1. Write a c program for electricity bill tacking different categories of users, different slabs in each
category. (Using nested if else statement)
2. Write a c program to evaluate the following using loops
a) 1+x2/2!+x4/4!+...up to 5 terms b) x+x3/3!+x5/5!+...up to 5 terms
3. Write a c program to check whether the given number is a. Prime or not b. Perfect or abundant or
deficient.
4. Write a c program to find the mean, mode, median, and variance of list of values by using one
dimensional array.
5. Write a menu driven program to read a list of numbers and perform the following operations
a) Print the list, b) Delete duplicates from the list c) Reverse the list
6. Write a program to read a list of numbers and search for given number using binary search
algorithm and if found display its index otherwise display the message "element not found in the list"
using function.
7. Write a menu driven program to read two matrices and compute their sum and product using
functions
8. Write a menu driven program to read list of student names and perform the following operations
using functions. a. To print list of names b. To sort them in ascending order c. To print the list after
sorting
9. Write a c program that consists of recursive functions to find
a. Factorial of a given number b. Print the Pascal triangle using binomial theorem
10. Write a menu driven program to read list of student names and perform the following operations
using array of character pointers.
a) To insert a student name b) To delete a name c) To print the names.

*****

B.C.A: Programming Concept using C 2


1. What are the Types of Software's?
1. System Software: System software manages and controls computer hardware so that application
software can function. It acts as a bridge between the user and hardware.
Types of System Software:
 Operating Systems (OS): Manages computer hardware and software (e.g., Windows, Linux,
macOS).
 Device Drivers: Allows the OS to communicate with hardware devices (e.g., printer drivers,
sound card drivers).
 Utility Programs: Perform specific tasks to manage system resources (e.g., antivirus software,
disk cleaners).
 Firmware: Pre-installed software on hardware (e.g., BIOS in PCs, firmware in routers).

2. Application Software:
Application software is designed to help users perform specific tasks.
Types of Application Software:
 General-purpose Software: Used for common tasks.
Examples: MS Word, Excel, PowerPoint, web browsers.
 Specialized/Domain-specific Software: Used for specific industries or functions (e.g.,
accounting software like Tally, graphic design tools like Adobe Photoshop).
 Productivity Software: Increases efficiency (e.g., project management tools like Trello, MS
Project).
 Educational Software: Designed for learning and teaching (e.g., Duolingo, Moodle).
 Multimedia Software: For creating and playing media (e.g., VLC Media Player, Adobe Premiere
Pro).
 Web-based Applications: Applications that run on web browsers (e.g., Google Docs, Canva).

3. Other Software Classifications (Cross-cutting types):


These types can span across system or application software:
1. Programming Software: Used by developers to write, test, and maintain software.
Examples: Compilers, Debuggers, Text Editors, IDEs (e.g., Visual Studio, Eclipse).
2. Open-source Software: Software with source code that anyone can inspect, modify, and
enhance.
Examples: Linux, Apache Open Office.
3. Proprietary Software: Commercial software that is owned by an individual or company.
Examples: Microsoft Office, Adobe Suite.
4. Freeware and Shareware: Freeware: Completely free (e.g., Skype, VLC).
Shareware: Free for a limited time or with limited features (e.g., WinRAR).
5. Embedded Software: Software embedded in hardware devices (e.g., software in microwaves,
washing machines, ATMs).

2. What is a Programming Language?


A programming language is a formal language used by programmers to communicate with computers.
It is used to write software programs, scripts, or other sets of instructions for a computer to execute
specific tasks.
Types of Programming Languages

B.C.A: Programming Concept using C 3


Programming languages are categorized based on abstraction level, usage, and paradigm:

1. Low-Level Languages : These are close to machine language and difficult for humans to understand
but offer high performance.
a) Machine Language: Binary code (0s and 1s)
 Directly executed by the CPU.
 Example: 10110000 01100001
b) Assembly Language: Uses mnemonics like MOV, ADD, SUB
 Requires an assembler to convert into machine code
 Hardware-specific
 Example: MOV AX, 1, ADD AX, 2

2. High-Level Languages: Easier to understand, portable, and machine-independent. Examples:


C – Structured, efficient
C++ – Object-oriented
Java – Platform-independent
Python – Easy syntax, dynamic typing
C# – Developed by Microsoft, similar to Java
JavaScript – Web scripting
PHP – Server-side scripting
Swift – iOS/macOS development
Go – Developed by Google, concurrent

3. Very High-Level Languages (VHLL): Focus on reducing complexity, used in specific fields. Examples:
SQL – Database queries
MATLAB – Mathematical computing
R – Statistical computing
Scratch – Visual block-based language for education

4. Scripting Languages: Used for automating tasks; often interpreted, not compiled.
Examples: Python, Perl, Bash, JavaScript

Programming Paradigms (Styles of Programming)


 Procedural – Step-by-step procedures (C, Pascal)
 Object-Oriented – Based on classes and objects (Java, C++, Python)
 Functional – Treats computation as mathematical functions (Haskell, Lisp)
 Logic-based – Based on formal logic (Prolog)

Compiled vs Interpreted Languages


Compiled Language Interpreted Language
Translated into machine code Executed line by line
Faster execution Easier to debug
Examples: C, C++ Examples: Python, JavaScript

B.C.A: Programming Concept using C 4


Popular Programming Languages in Use Today (with Purpose)
Language Use Case
Python AI, ML, Data Science, Web Dev
Java Enterprise, Android apps
JavaScript Web development
C/C++ System programming, Game Dev
C# Windows apps, Unity Games
Swift iOS/macOS apps
PHP Web development
R Statistics, Data analysis
Go (Golang) Cloud systems, APIs
Kotlin Android development

3. Translator Programs, Problem Solving Techniques, Using Computer.


1. Translator Programs: Translator Programs are software tools that convert code written in one
programming language (usually high-level) into another form (typically machine code), so that
computers can understand and execute the instructions.
Types of Translator Programs:
Type Function Examples
Compiler Translates entire source code into machine C, C++, Java (to bytecode)
code before execution
Interpreter Translates and runs code line-by-line Python, JavaScript
Assembler Converts assembly language to machine code MASM, NASM
Hybrid (Both) Uses both compilation and interpretation Java (compiled to byte
code, interpreted by JVM)

2. Problem Solving Techniques: Problem solving in computer science involves identifying a problem,
developing an algorithm, and implementing a solution using a programming language.
Steps in Problem Solving:
 Understanding the Problem
 Identify inputs, outputs, and constraints.
 Planning the Solution
 Choose an approach (algorithm).
Techniques include:
 Flowcharts-Pseudo code-Algorithms
 Designing the Algorithm
 Write logical steps to solve the problem.
 Coding the Solution
 Convert the algorithm into a programming language.
 Testing and Debugging
 Run the program and fix errors (bugs).
 Documentation-Write notes and instructions for future reference.
 Maintenance
 Update or modify the program as needed.

B.C.A: Programming Concept using C 5


Problem-Solving Tools:
Tool Use
Flowchart Graphical representation of steps
Pseudocode Plain English-like steps
Dry Run Manually tracing code logic
Debugging Tools IDE debuggers, print statements

3. Using Computers in Problem Solving


Computers help solve complex problems quickly and efficiently.
Role of Computers:
 Automate Repetitive Tasks (e.g., calculations, data entry)
 Simulate Real-World Problems (e.g., weather models, traffic systems)
 Store & Analyze Large Data (e.g., databases, data mining)
 Support Decision-Making (e.g., MIS, AI tools)
Application Areas:
Field Problem Solved Using Computers
Education e-learning platforms, testing software
Healthcare Diagnosis systems, patient record management
Banking Transaction processing, fraud detection
Engineering CAD software, simulations
Research Data analysis, modeling

4. History of C, Importance of C, Sample Programs, Basic Structure of C Programs, Programming Style,


Executing a ' C ' Program
1. History of C Language
Developed By: Dennis Ritchie at Bell Labs
Year: Around 1972
Purpose: To develop the UNIX Operating System
Predecessors: BCPL → B → C
Standardization: ANSI C (1989) – standardized by ANSI (American National Standards Institute)
ISO C (1990) – standardized by ISO

2. Importance of C Language
Foundation Language: Base for C++, Java, Python, etc.
 Portability: Can run on different hardware platforms.
 Speed: Compiled and fast, close to hardware.
 Structured Language: Allows use of functions and modular code.
 System-Level Programming: Used for OS, compilers, embedded systems.
3. Basic Structure of a C Program
#include <stdio.h> // Preprocessor directive
// Main function - execution starts here
int main() {
printf("Hello, World!"); // Output statement
return 0; // Exit code
}
B.C.A: Programming Concept using C 6
Key Components:
Component Purpose
#include <stdio.h> Includes standard input/output library
main() Entry point of the program
{ ... } Denotes block of code
printf() Prints output to screen
return 0; Ends the program
4. Sample Programs in C
a) Print a Message
#include <stdio.h>
int main() {
printf("Welcome to C Programming!");
return 0; }
b) Add Two Numbers
#include <stdio.h>
int main() {
int a = 5, b = 7;
int sum = a + b;
printf("Sum = %d", sum);
return 0;}
5. Programming Style in C: Good programming style improves readability, debugging, and
maintainability. Guidelines:
 Use meaningful variable names (e.g., totalMarks instead of tm)
 Use indentation and proper spacing
 Add comments to explain code
 Use modular code (break into functions)
 Maintain consistent brace placement
Example (Good Style):
#include <stdio.h>
// Function to add two numbers
int add(int x, int y) {
return x + y;
}
int main() {
int result = add(10, 15);
printf("Sum = %d", result);
return 0;
}

6. Executing a C Program: Steps:


Step Description
1. Write Write source code using a text editor (e.g., program.c)
2. Save Save with .c extension
3. Compile Use compiler to convert to machine code (e.g., GCC)
4. Run Execute the output file
B.C.A: Programming Concept using C 7
Using GCC Compiler (Linux/Windows)
 gcc program.c -o program // Compile
 ./program // Run
Using Turbo C (Windows)
 Open Turbo C IDE
 Write code → Save
 Compile (Alt + F9)
 Run (Ctrl + F9)
 View Output (Alt + F5)

5. Tokens, Keywords and Identifiers, Constants, Variables, Data Types explain with example.
1. Character Set in C: The Character Set refers to all the valid characters that can be used in C
programming. Categories:
Character Type Examples
Letters A–Z, a–z
Digits 0–9
Special Symbols ~, !, @, #, $, %, ^, &, *, (, ), {}, [], ;, :, ,, . etc.
Whitespace Space, Tab, Newline (\n)
Escape Sequences \n, \t, \\, \', \"

2. C Tokens: Tokens are the smallest elements of a C program. The C compiler breaks the program into
these tokens. Types of C Tokens:
Token Type Example
Keywords int, return, if, else
Identifiers sum, main, total_marks
Constants 100, 'A', 3.14
Operators +, -, *, /, ==
Special Symbols (), {}, ;, []
Strings "Hello"

3. Keywords and Identifiers


Keywords:
 Reserved words in C that have predefined meanings.
 Cannot be used as variable names.
Examples of Keywords: int, float, return, void, if, else, while, for, break, continue, switch, case, default

Identifiers: Names used for variables, functions, arrays, etc.


Rules:
 Must begin with a letter (A–Z or a–z) or underscore _
 Followed by letters, digits or underscores
 Case-sensitive (Total ≠ total)
 Cannot be a keyword
Example: int studentName;
float totalMarks;

B.C.A: Programming Concept using C 8


4. Constants in C: Constants are fixed values that do not change during program execution.
Types of Constants:
Type Example
Integer 10, -25, 0
Float 3.14, -0.5
Character 'A', '5'
String "Hello"
Declaration: const int maxMarks = 100;

5. Variables in C: Variables are containers used to store data that can change during program
execution.
 Rules for Declaring Variables:
 Must be declared before use.
 Must have a valid identifier name.
 Data type must be specified.
Example: int age = 21;
float salary = 30000.50;
char grade = 'A';

6. Data Types in C: Data types define the type of data a variable can store.
Primary Data Types:
Type Description Example
int Integer numbers int a = 10;
float Floating-point numbers float b = 3.14;
char Single characters char c = 'A';
double Double precision floatdouble d = 9.81;
void No value (used in functions) void main()

Derived Data Types: Arrays, Pointers, Structures, Unions, Enums


Example Code Using All Concepts:
#include <stdio.h>
int main() {
int age = 20; // integer variable
float height = 5.9; // float variable
char grade = 'A'; // character constant
const int maxMarks = 100; // constant
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Grade: %c\n", grade);
printf("Max Marks: %d\n", maxMarks);
return 0;
}

6. Declaration of Variables, Declaration of Storage Class, Assigning Values to Variables, Defining


Symbolic Constant, Declaring Variable as Constant and Volatile, Overflow and Underflow of Data.

B.C.A: Programming Concept using C 9


1. Declaration of Variables: A variable declaration tells the compiler about the variable’s name and
data type.
Syntax: data_type variable_name;
Example: int age;
float salary;
char grade;
You can also declare multiple variables of the same type: int x, y, z;

2. Declaration of Storage Class: A storage class defines the scope, visibility, lifetime, and default initial
value of a variable.
Storage Classes in C:
Storage Class Scope Lifetime Default Value Keyword
auto Local (default) Inside function Garbage value auto
register CPU Register Inside function Garbage value register
static Local/Global Entire program 0 (if not initialized) static
extern Global Declared elsewhere Actual variable value extern
Example: static int count = 0;
extern int total; // declared in another file

3. Assigning Values to Variables: You can assign a value to a variable at the time of declaration or later.
Examples: int age = 25; // Declaration with assignment
age = 30; // Assignment later
float pi = 3.14;
char grade = 'A';

4. Defining Symbolic Constants: Symbolic constants are created using the #define preprocessor
directive.
Syntax: #define CONSTANT_NAME value
Example: #define PI 3.14159
#define MAX_STUDENTS 100
printf("Value of PI is %f", PI);
Note: No semicolon at the end of #define.

5. Declaring Variable as Constant and Volatile


a) const Keyword:Used to make a variable read-only (its value cannot be changed after initialization).
Example: const int maxMarks = 100;
// maxMarks = 120; ❌— This will cause an error

b) Volatile Keyword: Used to tell the compiler not to optimize a variable because its value may change
unexpectedly (e.g., hardware registers, multi-threading).
Example: volatile int timerRegister;
Useful when variable values are changed outside normal program flow (e.g., interrupt routines or
hardware).

6. Overflow and Underflow of Data


Overflow: Occurs when a value exceeds the maximum limit a data type can hold.
B.C.A: Programming Concept using C 10
Example: #include <stdio.h>
int main() {
unsigned char a = 255; // Max for unsigned char
a = a + 1; // Overflow occurs
printf("%d", a); // Output: 0
return 0;
}

Underflow: Occurs when a value goes below the minimum limit a data type can hold.
Example: #include <stdio.h>
int main() {
float x = 1.0e-38;
float y = x / 10.0; // Underflow may occur
printf("%e", y); // Very small number or 0
return 0;
}
Managing Input and Output Operations: Introduction, Reading a Character, Writing a Character,
Formatted Input and Output.

7. Managing Input and Output Operations in C


In C, Input/Output (I/O) operations allow interaction between the user and the program via keyboard
(input) and screen (output).
1. Introduction: C provides standard I/O functions from the header file #include <stdio.h>.
Input: Accepting data from the user.
Output: Displaying data to the user.
There are two types of I/O operations:
Unformatted I/O: Character-by-character
Formatted I/O: With specific data types using format specifies

2. Reading a Character
Using getchar():
Reads a single character from the keyboard.
Does not require any argument.
Example: #include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Input
printf("You entered: ");
putchar(ch); // Output
return 0;
}
3. Writing a Character: Using putchar(), Outputs a single character to the screen.
Takes a character variable or constant as an argument.
Example: char grade = 'A';
putchar(grade);
B.C.A: Programming Concept using C 11
4. Formatted Input and Output
Formatted Input: scanf() , Used to read values of any data type from the user.
Syntax: scanf("format_specifier", &variable);
Example: int age;
scanf("%d", &age); // Reading integer

Formatted Output: printf(), Used to display values with formatting.


Syntax: printf("message with format_specifier", variable);
Example: int age = 25;
printf("Age is: %d", age); // %d for integer

Common Format Specifies:


Specifier Data Type
%d or %i Integer
%f Float
%c Character
%s String
%lf Double
%u Unsigned int
%x / %X Hexadecimal (lower/upper)
Example Program: Formatted I/O
#include <stdio.h>
int main() {
int roll;
float marks;
char name[20];
printf("Enter roll number, name, and marks:\n");
scanf("%d %s %f", &roll, name, &marks);
printf("Student Info:\n");
printf("Roll: %d\n", roll);
printf("Name: %s\n", name);
printf("Marks: %.2f\n", marks);
return 0;
}

7. Operators and Expressions: Introduction, Arithmetic Operators, Relational Operators, Logical


Operators, Assignment Operators, Increment and Decrement Operator, Conditional Operators, Bitwise
Operators, Special Operators,
Operators and Expressions in C:
 Operators: Symbols used to perform operations on variables and values.
 Expressions: Combinations of variables, constants, and operators that are evaluated to produce
a result.
1. Introduction: Operators allow you to:
 Perform calculations
 Compare values

B.C.A: Programming Concept using C 12


 Assign values
 Control program flow
 C supports a wide range of operator categories.

2. Arithmetic Operators: 3. Relational Operators: Used to compare values.


Used to perform mathematical operations. The result is either true (1) or false (0).
Operator Meaning Example Operator Meaning Example
+ Addition a+b == Equal to a == b
- Subtraction a-b != Not equal to a != b
* Multiplication a*b > Greater than a>b
/ Division a/b < Less than a<b
% Modulus (Remainder) a%b >= Greater than or equal a >= b
<= Less than or equal a <= b

4. Logical Operators: 5. Assignment Operators:


Used to combine multiple conditions. Used to assign values to variables.
Operator Meaning Example Operator Example Equivalent To
&& Logical AND a > 0 && b > 0 = a = 10 Assign 10 to a
|| Logical OR a <0 || b < 0 += a += 5 a=a+5
! Logical NOT !(a > 0) -= a -= 5 a=a-5
*= a *= 2 a=a*2
/= a /= 2 a=a/2
%= a %= 3 a=a%3

6. Increment and Decrement Operators: Used to increase or decrease the value of a variable by 1.
Operator Meaning Example
++ Increment a++, ++a
-- Decrement a--, --a
++a (Pre-increment) → Increments, then uses the value
a++ (Post-increment) → Uses the value, then increments

7. Conditional (Ternary) Operator: Used to evaluate a condition and return one of two values.
Syntax: (condition) ? expression1: expression2;
Example: int a = 5, b = 10;
int max = (a > b) ? a : b;

8. Bitwise Operators: Operate on binary digits (bits).


Operator Meaning Example
& Bitwise AND a&b
| Bitwise OR a|b
^ Bitwise XOR a^b
~ Bitwise NOT ~a
<< Left Shift a << 1
>> Right Shift a >> 1

B.C.A: Programming Concept using C 13


9. Special Operators: Used in advanced operations.
Operator Meaning Example
sizeof Returns the size of a data type sizeof(int)
& Address of a variable &a
* Pointer (value at address) *ptr
-> Access structure member using pointer ptr->name
. Access structure member structVar.name

Example Program Using Multiple Operators


#include <stdio.h>
int main() {
int a = 5, b = 10;
int sum = a + b;
int max = (a > b) ? a : b;
printf("Sum: %d\n", sum);
printf("Max: %d\n", max);
printf("Bitwise AND: %d\n", a & b);
return 0;
}

8. Arithmetic Expressions, Evolution of expressions, Precedence of Arithmetic Operators, Some


Computational Problems
1. Arithmetic Expressions in C: An arithmetic expression is a combination of variables, constants, and
arithmetic operators that produces a numeric result.
Example: int result = a + b * c;
Here, + and * are arithmetic operators, and a, b, c are operands.

2. Evaluation of Expressions: The evaluation of an expression depends on:


 Operator precedence
 Associativity
 Use of parentheses
Example: int a = 4, b = 2, c = 3;
int result = a + b * c;
First, b * c = 6
Then, a + 6 = 10
So, result = 10
3. Precedence of Arithmetic Operators
Operator precedence determines which operator is applied first in an expression.
Operator Precedence Table (Highest to Lowest)
Precedence Level Operators Associativity
1 (Highest) (), [] Left to Right
2. +, - (Unary) Right to Left
3.*, /, % Left to Right
4. +, - (Binary) Left to Right
5. (Lowest) = Right to Left
B.C.A: Programming Concept using C 14
Example with Parentheses:
int a = 4, b = 2, c = 3;
int result = (a + b) * c; // Evaluates as (6) * 3 = 18
Use parentheses to control the order of operations explicitly.

4. Some Computational Problems


Problem 1: Area of a Circle Problem 2: Simple Interest
#include <stdio.h> #include <stdio.h>
#define PI 3.14159 int main() {
int main() { float principal = 1000, rate = 5, time = 2;
float radius = 5.0; float si = (principal * rate * time) / 100;
float area = PI * radius * radius; printf("Simple Interest = %.2f", si);
printf("Area = %.2f", area); return 0;
return 0;} }
Problem 3: Average of 3 Numbers Problem 4: Convert Celsius to Fahrenheit
#include <stdio.h> #include <stdio.h>
int main() { int main() {
int a = 10, b = 20, c = 30; float celsius = 37;
float avg = (a + b + c) / 3.0; float fahrenheit = (celsius * 9 / 5) + 32;
printf("Average = %.2f", avg); printf("Fahrenheit = %.2f", fahrenheit);
return 0; return 0;
} }

9. Type Conversions in Expressions, Operator Precedence and Associativity, Mathematical Functions.


1. Type Conversions in Expressions: Type conversion is the process of automatically or explicitly
converting one data type into another.
Types of Type Conversions:
a) Implicit Type Conversion (Type Promotion): Done automatically by the compiler.
Converts lower data types to higher data types to avoid data loss.
From To
char int
int float
float double
Example: int a = 5;
float b = 6.2;
float result = a + b; // `a` is promoted to float

b) Explicit Type Conversion (Type Casting): Manually converting one data type into another using
casting operator.
Syntax: (type) expression;
Example: int a = 5, b = 2;
float result = (float)a / b; // Output: 2.5

2. Operator Precedence and Associativity


Operator Precedence: Determines the order in which different operators in an expression are
evaluated.
B.C.A: Programming Concept using C 15
Associativity: Determines the direction (Left to Right or Right to Left) in which operators of the same
precedence level are evaluated. Precedence and Associativity Table (Key Operators)
Operators Description Associativity
(), [], . Function call, array, structure Left to Right
++, --, + (unary) Unary operators Right to Left
*, /, % Multiplication/Division/Modulus Left to Right
+, - Addition/Subtraction Left to Right
<, <=, >, >= Relational Left to Right
==, != Equality Left to Right
&& Logical AND Left to Right
|| Logical OR Left to Right
= Assignment Right to Left
?: Conditional Right to Left

Example: int a = 5, b = 10, c = 2;


int result = a + b * c; // b * c = 20; a + 20 = 25
Use parentheses to override default precedence:
int result = (a + b) * c; // a + b = 15; 15 * 2 = 30

3. Mathematical Functions:
C provides a variety of mathematical functions through the header file: #include <math.h>
Common Math Functions in C:
Function Description Example
sqrt(x) Square root of x sqrt(25) → 5.0
pow(x, y) x raised to power y pow(2, 3) → 8.0
fabs(x) Absolute value of float x fabs(-5.5) → 5.5
floor(x) Largest int ≤ x floor(5.9) → 5.0
ceil(x) Smallest int ≥ x ceil(4.1) → 5.0
log(x) Natural log of x log(2.71828) → 1
exp(x) e raised to x exp(1) → 2.71828
sin(x) Sine of x (in radians) sin(0) → 0
cos(x) Cosine of x cos(0) → 1
tan(x) Tangent of x tan(0) → 0
Note: Most functions return double values.
Example Program Using Math Functions
#include <stdio.h>
#include <math.h>
int main() {
double num = 9.0;
printf("Square root: %.2f\n", sqrt(num));
printf("Power: %.2f\n", pow(2, 3));
printf("Ceil: %.2f\n", ceil(3.4));
printf("Floor: %.2f\n", floor(3.4));
return 0;
}
B.C.A: Programming Concept using C 16
UNIT-II
UNIT – II: Decision Making and Branching: Introduction, Decision Making with IF Statement, Simple If
Statement, The If....Else Statement, Nested of If....Else Statements, The else if Ladder, The Switch
Statement, The ? : Operator, The Goto Statement.
Decision Making and Looping: Introduction, The While statement, the do Statement, the For
Statement, Jumps in Loops.
Arrays: Introduction, One-dimensional Arrays, Declaration and Initialization of One dimensional Arrays,
Two-dimensional Arrays, Initializing two-dimensional Arrays, Multi-dimensional Arrays, Dynamic
Arrays.
*****
1. Decision Making and Branching:
Simple if Statement: Executes a block of code only if a specified condition is true.
Syntax: if (condition) {
// statements to execute if condition is true
}
Example: #include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.\n");
}
return 0;
}

2. if...else Statement: Executes one block if condition is true, and another block if it is false.
Syntax: if (condition) {
// true block
} else {
// false block
}
Example: #include <stdio.h>
int main() {
int number = -5;
if (number >= 0) {
printf("The number is non-negative.\n");
} else {
printf("The number is negative.\n");
}
return 0;
}

3. Nested if...else Statements:


if...else statements inside another if...else. Used to make more complex decisions.
Syntax: if (condition1) {
if (condition2) {
// both condition1 and condition2 are true
} else {
B.C.A: Programming Concept using C 17
// condition1 is true, condition2 is false
}
} else
{ // condition1 is false
}
Example: #include <stdio.h>
int main() {
int age = 20;
int hasID = 1;

if (age >= 18) {


if (hasID) {
printf("Entry permitted.\n");
} else {
printf("ID required for entry.\n");
}
} else {
printf("Underage - entry not allowed.\n");
}
return 0;
}

4. else if Ladder: Allows checking multiple conditions in sequence. First true condition’s block is
executed.
Syntax: if (condition1)
{ // block1
} else if (condition2) {
// block2
} else if (condition3) {
// block3
} else {
// default block
}
Example:#include <stdio.h>
int main() {
int marks = 75;
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 75) {
printf("Grade B\n");
} else if (marks >= 60) {
printf("Grade C\n");
} else {
printf("Fail\n");
}
return 0;
}
B.C.A: Programming Concept using C 18
The switch Statement: Used to perform different actions based on the value of a single variable or
expression. It's a good alternative to the else if ladder when there are many possible discrete values.
Syntax: switch (expression) {
case constant1:
// statements
break;
case constant2:
// statements
break;
...
default:
// statements
}
Example: #include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Note:
 break is used to exit the switch block.
 If break is omitted, execution continues to the next case (called fall-through).

2. The Ternary Operator (? :)


The ternary operator is a short form of if...else. It returns one of two values depending on a condition.
Syntax: (condition) ? expression_if_true : expression_if_false;
Example: #include <stdio.h>
int main() {
int a = 10, b = 20;
int max;
max = (a > b) ? a : b;
printf("The maximum is: %d\n", max);
return 0;
}
Usage: Great for simple conditions in a single line.
B.C.A: Programming Concept using C 19
3. The goto Statement: Used to jump to a labeled statement anywhere in the function. Useful in
breaking out of deeply nested loops or error handling (but generally discouraged for clarity reasons).
Syntax: goto label;
// code here is skipped
label:
// code to execute
Example: #include <stdio.h>
int main() {
int number = 5;
if (number < 0)
goto negative;
printf("Number is positive or zero.\n");
goto end;
negative:
printf("Number is negative.\n");
end:
printf("End of program.\n");
return 0;
}

2. The While statement, the do Statement, the For Statement, Jumps in Loops
1. The while Statement: Executes a block as long as the condition is true. The condition is checked
before executing the loop body.
Syntax: while (condition) {
// loop body
}
Example: #include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Output:
12345

2. The do...while Statement: Similar to a while, but executes at least once because the condition is
checked after the loop body.
Syntax: do {
// loop body
} while (condition);
Example:#include <stdio.h>
int main() {
int i = 1;
do {
B.C.A: Programming Concept using C 20
printf("%d ", i);
i++;
} while (i <= 5);
return 0;
}
Output:
12345

3. The for Statement


Ideal for loops with a known number of iterations. Initialization, condition, and update all in one line.
Syntax: for (initialization; condition; update) {
// loop body
}
Example: #include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}

4. Jumps in Loops (break, continue)


 break: Used to exit the loop early.
 continue: Skips the rest of the loop and jumps to the next iteration.
Example using break and continue:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5)
continue; // skips printing 5
if (i == 8)
break; // exits loop when i is 8
printf("%d ", i);
}
return 0;
}
Output:
123467

B.C.A: Programming Concept using C 21


3. Arrays: Introduction, One-dimensional Arrays, Declaration and Initialization of One dimensional
Arrays, Two-dimensional Arrays, Initializing two-dimensional Arrays, Multi-dimensional Arrays,
Dynamic Arrays.
1. Introduction to Arrays
An array is a collection of fixed-size elements (same data type) stored in contiguous memory locations.
Why use Arrays?
 Store multiple values of the same type using a single variable name.
 Efficient for processing bulk data using loops.

2. One-Dimensional Arrays (1D)


Declaration Syntax: data_type array_name[size];
Example Declaration & Initialization:
int marks[5] = {90, 85, 78, 92, 88};
Accessing Elements: printf("%d", marks[2]); // prints 78
Example: #include <stdio.h>
int main() {
int i, marks[5] = {90, 85, 78, 92, 88};
for (i = 0; i < 5; i++) {
printf("Student %d Marks = %d\n", i + 1, marks[i]);
}
return 0;
}

3. Two-Dimensional Arrays (2D): Used to represent tables or matrices (rows × columns).


Declaration Syntax: data_type array_name[rows][columns];
Example Initialization: int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Accessing: printf("%d", matrix[1][2]); // prints 6

Example: #include <stdio.h>


int main() {
int i, j;
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
4. Multi-Dimensional Arrays: Arrays with more than two dimensions, such as 3D, are rarely used but
useful for representing 3D space or tensors.
Declaration:
int cube[2][2][2] = {
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};
B.C.A: Programming Concept using C 22
Access: printf("%d", cube[1][0][1]); // prints 6

5. Dynamic Arrays (Using Pointers and malloc)


When the size of the array is not known at compile time, we use dynamic memory allocation.
Header File Needed:
#include <stdlib.h>
Example: #include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n, i;

printf("Enter number of elements: ");


scanf("%d", &n);

arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory not allocated.\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

free(arr); // release memory


return 0;
}

*****

B.C.A: Programming Concept using C 23


B.C.A: Programming Concept using C 24

You might also like