0% found this document useful (0 votes)
11 views

Introduction CMP 172 Unit I

Uploaded by

SCS is Live
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Introduction CMP 172 Unit I

Uploaded by

SCS is Live
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

CMP 172

Programming Language
“C”

Er. Sameer Kharel, PhD


Introduction to the course
• This course is designed to provide students
with a comprehensive understanding of
computer programming using the C language.

• Nature of the course: Theory + Practical


• Full marks: 100
• Pass marks: 45
• Credit: 3 Hrs
2
Objectives
• To understand the basic principles and concepts of computer
programming.

• To gain proficiency in writing C programs and applying


programming constructs.

• To develop problem-solving and logic building skills through


programming exercises.

• To acquire knowledge of fundamental data structures and


their implementation in C.
3
Cont…
• To learn how to design and implement algorithms
using C programming.

• To apply programming concepts and C programming


skills to solve real-world problems.

4
Evaluation System

5
Prescribed Books and References
• Prescribed Text Books:
– Srivastava. (2009). C - In Depth - 2Nd Revised
Edition. BPB Publications.
– Kanetkar, Y. P. (2006). Let us c. BPB Publications.

• Reference Books:
– Balagurusamy, E. (2019). Programming In Ansi C,
8Th Edition. MC Graw Hill India.

6
Cont…
– Gottfried, B. S. (1996). Programming with C Ind
Adap ed. Tata McGraw-Hill Education.
– Deitel, P. J., & Deitel, H. M. (2016). C: How to
Program. Prentice Hall.
– Kelley, A., & Pohl, I. (1998). A book on c:
Programming in C. Addison-Wesley Professional.
– Mittal, A. (2010). Programming In C: A Practical
Approach. Pearson Education India.

7
Unit 1: Problem Solving with
Computer
• Problem analysis
• Algorithms and Flowchart
• History of C
• Structure of C program
• Testing and Documentation
• Preprocessor and Macros

8
Problem Solving using Computer
• In market, different kind of general-purpose software
packages are available in the market. But, sometimes
these packages cannot fulfill all clients’ (users’)
requirements. So to fulfill the client’s requirements
new software must be developed. Generally, the
client come to the developers’ site with their
problem to be solved and to find a computer-based
solution. The computer-based solution will be
software to fulfill the clients’ requirement. The
develop good quality software, it is required to go
through the following phases.
9
Problem analysis
• It is important to give a clear, concise problem
statement. It is also called problem definition.
The problem definition should clearly specify
the following tasks.

• Objectives: The problem should be stated


clearly so that there will not be the change of
having right solution of the wrong problem.
Simple program can be stated easily and early
10
Cont…
• but for complex problem may need a complex
analysis with careful coordination of people,
procedures and programs.

• Output requirements: Before we know what


should go into the system, we must know
what should come out from the system being
developed. Although the system analyst or
programmer, the best person to design output
11
Cont…
• is the end user. So, it is the better way of
designing output sitting with the end users.

• Input requirements: To get the above


designed output, it is required to define the
input data and source of input data. For
example, in a student information system,
input data may be students’ records and
source may be college administration.
12
Cont…
• Processing requirements: It is required to
clearly define processing requirements to
convert the given input data to the required
output. In processing requirements, there may
be hardware platform, software platform,
manpower etc.

13
Cont…
• Evaluating Feasibility: It is one of the
important phases where we manly decide
whether the proposed software development
task is technically and economically feasible.

• Finally there should be a proper


documentation of the different tasks of
problem analysis done in the previous
mentioned stages.
14
Algorithm and Flowchart
• Algorithm: An algorithm is define as a set of
ordered steps or procedures necessary to
solve a problem. To be an algorithm, the set of
steps must be unambiguous and have a clear
stopping point. Each step tells what task is to
be performed. Algorithms can be expressed in
any language e.g. English.

15
Cont…
• Flowchart: A flowchart is a diagrammatic
representation of an algorithm. It illustration
the sequence of operations to be performed
to get the solution of a problem.

16
Cont…

17
Cont…
• Write algorithm and draw a flowchart to add
two numbers just given by the user.

• Algorithm
Step 1: Start
Step 2: Declare variable a, b, sum.
Step 3: Read values of a and b.

18
Cont…
Step 4: Add a and b and assigned the result to
sum.
sum  a + b
Step 5: Print sum.
Step 6: Stop.

19
Cont…

20
Cont…
• Write algorithm and draw a flowchart to check
whether a number is exactly divisible by 5 but
not by 7.

• Algorithm
Step 1: Start
Step 2: Declare variable n, rem1, rem2
Step 3: Read n
21
Cont…
Step 4: find remainders
rem1  n mod 5
rem2  n mod 7
Step 5: if rem1 = 0
if rem2 ≠ 0
print n is required number
else
print n is divisible by both 5 and 7
else
print n is not required number
Step 6: Stop

22
Cont…

23
Cont…
• Write algorithm and draw a flowchart to find
the largest of three different numbers.

• Algorithm
Step 1: Start
Step 2: Declare variables a, b and c.
Step 3: Read values of a, b and c

24
Cont…
Step 4: if a>b
if a>c
Print a is the greatest number.
else
Print c is the greatest number.
else
if b>c
Print b is the greatest number.
else
Print c is the greatest number.
Stop 5: Stop

25
Cont…

26
Cont…
• Write algorithm and draw a flowchart to find
factorial of a positive integer number entered
by a user.

• Algorithm
Step 1: Start.
Step 2: Declare variables n, i, fact.
Step 3: Read n.
27
Cont…
Step 4: Initialize i1, fact1.
Step 5: Repeat steps 5.1 and 5.2 while i≤n
5.1 fact fact*i
5.2 ii+1
Step 6: Print fact.
Step 7: Stop

28
Cont…

29
Cont…
• Write algorithm and draw a flowchart to find
smaller of two different number entered by
the user using function.

• Algorithm of calling function


Step 1: Start
Step 2: Declare variable a, b, min and function
smaller.
30
Cont…
Step 3: Read a, b.
Step 4: Call function smaller with argument a
and b
min  smaller(a, b)
Step 5: Print min.
Step 6: Stop.

31
Cont…
• Algorithm of called function (smaller)
Step 1: Declare local variable x, y, small.
Step 2: Assign a to x and b to y.
Step 3: if x<y
small x
else
smally
Step 4: Return small.
32
Cont…

33
Cont…

34
History of C
• The history of the C programming language is
closely tied to the development of Unix and
modern computing. Here’s a brief overview of
its key milestones:

• Origins:
1960s: At Bell Labs, the precursor to C was developed as part of research efforts. Initially, the
programming language BCPL (Basic Combined Programming Language) was created by
Martin Richards in 1967 for writing system software. Shortly after, Ken Thompson developed
B, a simpler version of BCPL, to run on early versions of Unix.

35
Cont…
• Development of C:
• 1970-1972: Dennis Ritchie at Bell Labs began working on C, which was
developed from B with improvements that allowed it to take advantage of
the capabilities of the new DEC PDP-11 computer. C was designed to
support low-level memory manipulation, making it ideal for system
programming, particularly operating systems like Unix.

• 1973: C became the language in which the Unix operating system was re-
implemented. Before this, Unix was mostly written in assembly language.
This transition allowed Unix to be more easily ported to different
machines, significantly contributing to the spread of Unix as well as the C
language.

36
Cont…
• Standardization:
• 1978: "The C Programming Language" by Brian Kernighan and Dennis
Ritchie (often referred to as "K&R C") was published, establishing an
informal standard for C.

• 1983: The American National Standards Institute (ANSI) formed a


committee to standardize C. This resulted in the creation of ANSI C or C89,
a version of C that included numerous improvements and better
portability across platforms.

• 1990s: The International Organization for Standardization (ISO) adopted


C89 as ISO C, which came to be known as C90.

37
Cont…
• Modern C:
• 1999: The C99 standard was introduced, adding new features such as
inline functions, new data types (like long long int for 64-bit integers), and
variable-length arrays, which improved C's functionality and modernized
the language for more recent computing needs.

• 2011: C11 was released with further improvements, such as better


support for multithreading and safer memory management features like
static_assert.

• 2018: C18 is the latest version of C, mostly consisting of bug fixes and
minor refinements to C11.

38
Cont…
• Influence:
• C’s simplicity and efficiency made it a foundation for many other
languages, such as C++, Objective-C, C#, and many more. Today, C remains
widely used in system programming, embedded systems, operating
system development, and performance-critical applications due to its
speed and close interaction with hardware.

39
Structure of C program
• A basic structure of a C program follows a specific layout,
containing essential components such as headers, functions,
and statements. Here’s an outline of the general structure of a
C program:

• Preprocessor Directives
– These are lines that begin with #, which instruct the compiler to perform specific tasks
before the actual compilation starts. Common directives include including header files or
defining constants.

– #include <stdio.h> // For input-output functions like printf, scanf


– #define PI 3.14 // Define a constant

40
Cont…
• Global Variables and Function Declarations
– You can declare global variables and function
prototypes outside the main() function, which are
accessible from any function in the program.

– int globalVar = 10; // Global variable


– void someFunction(); // Function prototype

41
Cont…
• main() Function
– Every C program must have a main() function. This is the entry point of the program where the execution starts. Inside the main() function,
you can declare variables, call functions, and write the main logic of the program.

int main() {
// Variable declarations
int a, b;

// Statements
a = 5;
b = 10;

// Function calls
someFunction();

// Return statement
return 0; // Indicates successful program termination
}

42
Cont…
• Functions Definitions
– You can define other functions outside the main()
function to perform specific tasks. These functions
can be called from main() or from other functions.

void someFunction() {
printf("This is a user-defined function.\n");
}

43
Cont…
#include <stdio.h> // Preprocessor directive for input-output functions

// Function declaration (prototype)


void greet();

int main() { // Main function where the program execution starts


// Variable declaration
int num1 = 10, num2 = 20;

// Output result using printf


printf("Sum of %d and %d is %d\n", num1, num2, num1 + num2);

// Call the user-defined function


greet();

return 0; // End of the program, returning 0 indicates successful execution


}

// Function definition
void greet() {
printf("Hello! Welcome to C programming.\n");
}

44
Cont…
• Key Components Explained:

• Preprocessor Directives (#include, #define):

– The #include <stdio.h> includes the standard


input/output library, allowing the use of printf().
– #define can be used to define constants that can
be used throughout the program.

45
Cont…
• main() Function:
– This is the starting point of every C program. Inside it, the
logic is executed, variables are declared, and functions are
called.

• Statements:
– Inside the main() function, different statements (such as
variable assignments, function calls, loops, conditionals)
are written to define the behavior of the program.

46
Cont…
• Functions:
– Functions (like greet() in the example) help
modularize the code and reduce redundancy.

47
Cont…
• Additional Notes:
– Every statement in C ends with a semicolon ;.
– Functions that return a value, such as main(),
should include a return statement (usually return
0; for main() to indicate successful execution).
– C programs typically execute from top to bottom,
starting from the main() function.

48
Testing and Documentation
• Testing in C Programming

• Documentation in C Programming

49
Testing in C Programming
• Manual Testing
– Process: Run the C program and provide different
inputs, then compare the actual output with the
expected output.
– Example: After compiling a program, you run it
and manually input values to check if the output is
as expected:

gcc myprogram.c -o myprogram # Compile the program


./myprogram # Execute the program
50
Cont…
• Unit Testing
– Definition: Unit testing focuses on testing
individual functions or components of a program
in isolation to ensure each works correctly.

– Method: You write test cases for each function,


typically using assert.h or external frameworks like
CUnit or Check.

51
Cont…
• Integration Testing
– Definition: Testing multiple modules or
components together to ensure they work in
combination.

– Approach: After ensuring each function works


individually (through unit testing), you test the
program as a whole, focusing on how different
components interact.

52
Cont…
• System Testing
– Definition: Testing the entire system to ensure it meets the
specified requirements.

– Process: Run the complete program with real-world


scenarios and inputs, and compare the behavior with the
requirements.

– Automated Testing: You can automate system testing using


scripts or tools that simulate different inputs, record
outputs, and compare them with the expected results.
53
Cont…
• Test Plans and Test Cases
– Test Plan: A document that outlines the testing
strategy, scope, and approach for a software
project. It includes the list of features to be tested,
testing techniques, and resources.

– Test Case: A specific scenario with input and


expected output. Each test case should be
documented and executed.

54
Documentation in C Programming
• Proper documentation in C programming
helps make code understandable,
maintainable, and usable for others (and even
for yourself). It involves using comments
within the code, documenting functions and
their parameters, and creating external
documentation that explains how to compile,
use, and maintain the program.

55
Cont…
• Inline Comments
– Single-line Comments: Use // for a single-line
comment.
– Multi-line Comments: Use /* */ for comments
that span multiple lines.

// This function calculates the square of a number


int square(int num) {
return num * num; // Return the result of num squared
}

56
Cont…
• Function Documentation
– Purpose: Provide details about what the function
does, the parameters it takes, and what it returns.
/**
* This function calculates the square of a number.
*
* @param num An integer to be squared
* @return The square of the input number
*/
int square(int num) {
return num * num;
}

57
Cont…
• File-level Comments
– At the beginning of each C source file, include a
block comment that describes the file's purpose,
the author, and the date.
/*
* File: calculator.c
* Author: Sameer Kharel
* Date: November 2024
* Description: This program implements a basic calculator with addition,
subtraction, multiplication, and division functions.
*/

58
Macros
• In C programming, macros are a feature provided
by the preprocessor, which is a phase of the
compilation process that occurs before the actual
compilation of code begins. Macros allow you to
define constants, functions, or blocks of code that
can be replaced during compilation. They are
typically used to make code more readable,
reduce redundancy, and improve performance in
certain scenarios.

59
Cont…
• Types of Macros:

• Object-like Macros
– Used to define constant values.
– Syntax: #define MACRO_NAME value
#define PI 3.14

int main() {
float area, radius = 5.0;
area = PI * radius * radius;
printf("Area of circle: %f\n", area);
return 0;
}
• In this example, every occurrence of PI is replaced by 3.14 during preprocessing.

60
Cont…
• Function-like Macros
– Used to define small, inline code snippets or functions.
– Syntax: #define MACRO_NAME(arguments) code

#define SQUARE(x) ((x) * (x))

int main() {
int num = 4;
printf("Square of %d is %d\n", num, SQUARE(num));
return 0;
}

• In this case, SQUARE(4) is replaced by ((4) * (4)) during preprocessing, resulting in the output
16.

61
Cont…
• Advantages of Macros:
– Performance: Since macros are replaced during
preprocessing, they can lead to faster execution
for small, frequently used code snippets (inline
expansion).

– Code Reusability: Macros help eliminate


redundancy, especially for repetitive tasks like
mathematical operations.

62
Cont…
• Disadvantages of Macros:
– No Type Safety: Unlike functions, macros do not check data
types, which can lead to unexpected behavior.
– Debugging Difficulty: Since macros are replaced during
preprocessing, debugging macro-related issues can be
challenging, as the macro code may not be visible in its
expanded form.
– Maintenance: Overuse of macros can make code less
readable and harder to maintain, especially when macros
are nested or overly complex.

63
Thank You!!!

64

You might also like