Unit 9. C Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Unit 9.

C Programming
Basic concepts of computer programming
(design simple algorithm and write program)
Computer Programming
• A computer program is a set of instructions that tells a computer how to perform a specific task or set of
tasks.
• These instructions are written in a programming language and are designed to be executed by a
computer's processor.
• A computer program is a sequence or set of instructions written in a programming language that
enables a computer to perform specific tasks.
• These languages have specific rules and syntax, similar to human languages, but are designed for
computers to understand and interpret.
• Programs define algorithms, which are logical sequences of steps showing the problem-solving process.
• Programs can be designed for various purposes, including:
• Automating tasks (e.g., sorting files, calculating numbers)
• Performing complex calculations (e.g., scientific simulations, engineering analysis)
• Creating interactive experiences (e.g., games, websites, mobile apps)
• Controlling hardware components (e.g., robots, printers, network devices)
What Computer Programs can Do?
Automate Tasks:
• Repetitive tasks: Programs can handle repetitive and boring tasks with accuracy and speed, freeing up
human time and effort. Examples include:
• Automatic file organization and sorting based on specific criteria.
• Generating reports and summaries from large datasets, saving manual data analysis time.
• Scheduling automated emails or social media posts for consistent marketing or communication.
Solve Complex Problems:
• Programming allows computers to tackle intricate problems beyond human capabilities. Examples include:
• Scientific simulations: Modeling weather patterns, analyzing molecular structures, or simulating
complex physical phenomena.
• Data analysis and machine learning: Extracting insights from massive datasets, identifying trends, and
making predictions for various applications like healthcare or finance.
• Optimization problems: Finding the most efficient route for delivery trucks or scheduling resources to
maximize production.
Create Interactive Experiences:
• Programming forms the core of various interactive applications we use daily. Examples
include:
• Developing video games: Creating immersive virtual worlds, designing game
mechanics, and defining player interactions.
• Building websites and web applications: Constructing user interfaces, implementing
functionalities, and managing data interactions.
• Designing mobile apps: Creating interactive features, managing user data, and
connecting to various services.
Control Hardware:
• Programs can instruct and control various hardware components, enabling automation and
interaction with the physical world. Examples include:
• Robotics: Programming robots to perform tasks in manufacturing, healthcare, or
exploration.
• Embedded systems: Controlling devices like smart thermostats, self-driving cars, or
medical equipment.
• Internet of Things (IoT): Programming devices to communicate with each other and
respond to external stimuli, creating smart homes or industrial automation systems.
Enhance Creativity and Expression:
• Programming can be used as a tool for creativity and expression in various ways.
Examples include:
• Generating artistic visuals and animations: Creating digital art, designing 3D
models, or composing music through code.
• Developing interactive simulations or educational games: Combining programming
with other disciplines to create engaging learning experiences.
• Building interactive storytelling experiences: Creating interactive narratives or
virtual environments.
How a Program works
(1) Writing the source code: The programmer writes the instructions using a specific
programming language and a code editor (a specialized text editor for writing code).
(2) Compilation or interpretation: The source code is then passed into a compiler or
interpreter, depending on the language used.
(3) Machine code generation: The compiler translates the entire code into machine code
or the interpreter translates each line into machine code.
(4) Execution: The generated machine code is loaded into the computer's memory and
executed by the processor. The program performs the tasks and calculations outlined in
the code, manipulating data as needed.
Components of Programming
• Algorithm:
• It is a set of steps or instruction statements to be followed to accomplish specific tasks.
A developer can design his algorithm to achieve the desired output.
• For Example, a recipe to cook a dessert. The algorithm describes the steps to be
followed for completing a specific task, but it does not say how to achieve any of the
steps.
• Source Code:
• The human-readable form of a program is called source code.
• Programmers write source code using programming languages like C, Python, Java, C+
+, or JavaScript.
• Source code consists of a series of instructions that guide the computer on what actions
to take.
• Compiler or Interpreter: These are software programs that translate the source code into
a form the computer can understand.
• Compiler: Converts the entire source code into machine code, a low-level language
specific to the computer's processor.
• Interpreter: Executes the source code line by line, translating each line into machine
code on the fly.
• Data Type: Data used in the applications can be of a different type, it can be a whole
number (integer), floating-point (decimal point numbers), characters or objects. For
Example, double currency = 45.86, where double is a data type used for storing numbers
with decimal points.

9
• Variable: Variable is a space holder for the value stored in the memory and this value can
be used in the application. For Example, int age = 25, where age is a variable.
• Conditionals: Knowledge of how to use a certain condition, such that a set of code
should execute only if a certain condition is true. In case of a false condition, the program
should exit and should not continue the code further.
• Array: Array is the variable that stores elements of a similar data type. Knowledge of
using an array in coding/programming will be a great benefit.
• Loop: Loop is used to execute the series of code until the condition is true. For
Example, in C programming, loops can be used as for loop, do-while, while loop or
enhanced for loop.
Top Computer Programming Languages
C Programming
• C is developed by Dennis Ritchie.
• C is a structured programming language.
• C supports functions that enables easy maintainability of code, by breaking large file into
smaller modules.
• Comments in C provide easy readability.
• C is a powerful language.
Program structure
Writing the first program
• A structure of C Program #include<stdio.h>
#include<stdio.h>
int main()
int main()
{
{
Statement1; printf(“Hello World!”);
Statement2; return 0;
}
}
// Comments after double slash
• This program prints Hello on the screen when
we execute it.
Header files
• The files that are specified in the include section is called as header file.
• These are precompiled files that has some functions defined in them.
• We can call those functions in our program by supplying parameters.
• Header file is given an extension .h
• C Source file is given an extension .c
• Eg: #include <stdio.h>, include <conio.h>, include <math.h> , etc.
• The stdio.h stands for "standard input-output header.”
• The conio.h stands for "console input-output header.”
• The math.h header file in C programming provides a set of mathematical functions for
performing common mathematical operations.
Main function
• This is the entry point for the execution of C program.
• When you run a C program, the operating system starts executing the code from the
main() function.
• When a file is executed, the start point is the main function.
• From main function the flow goes as per the programmers choice.
• There may or may not be other function written by user in a program.
• Main function is compulsory for any c program.

Syntax:
Running a C Program Comments in C
Comments are used to provide
explanations, document code, and
1. Type a program
make it more understandable to
2. Save it other programmers. Comments are
3. Compile the program - This will ignored by the compiler and do not
generate an exe file (executable) affect the execution of the program.
1. Single line comment
4. Run the program (Actually the exe
// (double slash)
created out of compilation will run and
Termination of comment is by
not the .c file)
pressing enter key
5. In different compiler we have different
option for compiling and running. 2. Multi line comment
/*…….
……..*/
This can span over to multiple lines.
Data Types in C
• Primitive data types
• - int, float, double, char
• Aggregate data types
• - Arrays come under this category
• - Arrays can contain collection of int or float
or char or double data
• User defined data types
• - Structures and enum fall under this category.
Variables
• Variables are data that will keep on changing
• Declaration
<<Data type>> ‹‹variable name>>;
int a;
• Definition
«<varname>> = <<value>>;
a=10;
• Usage
<<varname>>
a=a+1; //increments the value of a by 1
Variable names- Rules
• Should not be a reserved word like int etc..
• Should start with a letter or an underscore(–)
• Can contain letters, numbers or underscore.
• No other special characters are allowed including space
• Variable names are case sensitive.
:A and a are different.
Keywords in C
• Keywords are reserved words that have predefined meanings and cannot be used variable
names, function names, etc.
• These keywords are part of the C language syntax and serve specific purposes in the code.
• Here are the keywords in C: auto double break else case

continu
char extern const float
e

default goto do if int

long return short signed switch

unsigne
static while void Main
d
Input and Output
• Input
• - scanf(“%d", &a);
• - Gets an integer value from the user and stores it under the name "a"
• Output
• - printf(“%d", a);
• - Prints the value present in variable a on the screen
Operators
• Arithmetic (+,- *, /,%)
• Relational (<, >, <=,>=,= =,!=)
• Logical (&&, || , !)
• Bitwise (&, | )
• Assignment (=)
• Compound assignment(+=,*=,-=,/=,%=,&=,|=)
• Shift (right shift >>, left shift <<)
Loops in C programming
1. “for” Loop:
• The for loop is used when you know the number of times you want to execute a block of
code.
• Syntax:

Example:

Output:
Loops in C programming
2. “While” loop:
• The while loop is used when you want to execute a block of code repeatedly as long as
a condition is true.

Syntax: Example:
Loops in C programming
3. “Do-While” loop:
• The do-while loop is similar to the while loop, but it ensures that the block of code is
executed at least once before checking the condition.

Syntax:
Example:
Control Statements
• Control statements are used to alter the flow of program execution based on certain
conditions or criteria.
• These control statements allow you to make decisions, loop through code blocks, and
control the flow of execution within your program.
1. if statement: It executes a block of code if a specified condition is true.
2. if-else statement: It executes one block of code if the specified condition is true and
another block of code if the condition is false.
3. nested if-else statement: It consists of if-else statements inside other if-else statements,
allowing for more complex decision-making.
1. If Statement
• The if statement in C programming is used to execute a block of code only if a specified
condition is true.
• If the condition is false, the block of code is skipped, and the program continues
executing the code after the if statement.
• Here's an explanation of the if condition with a small example:
• Suppose we want to check if a given number is positive. If the number is positive,
we'll print a message indicating that it's positive; otherwise, we'll print a message
indicating that it's not positive.
1. If Statement
2. if-else statement
• The if-else statement in C programming allows you to execute one block of code if a
specified condition is true and another block of code if the condition is false.
• It provides a way to create alternative paths of execution based on the evaluation of a
condition.
• Syntax:
if (condition) {
// Code block to execute if the condition is true
} else {
// Code block to execute if the condition is false
}
2. if-else statement
3. nested if-else statement
• A nested if-else statement in C programming is a combination of multiple if-else statements, where one
if-else statement is nested inside another.
• This allows for more complex decision-making logic in your program.
• Each nested if-else statement adds another level of conditional evaluation, allowing you to handle
multiple conditions and execute different blocks of code based on those conditions.
• Syntax:
if (condition1) {
// Code block 1
if (condition2) {
// Code block 2
} else {
// Code block 3
}
} else {
// Code block 4
}
3. nested if-else statement
Algorithm
• An algorithm is a step-by-step procedure or set of rules used to solve a specific problem
or perform a particular task.
• It is a sequence of well-defined instructions that transform input data into output.
• It's a step-by-step process that the computer follows to solve a problem or complete a
task.
• Algorithms are the foundation of computer programming and are essential for designing
efficient and effective solutions to various computational problems.
• Algorithms are independent of programming languages and serve as the foundation for
writing code to implement the desired logic.
Algorithm Example
• Algorithm to add two numbers:
Step 1. Start
Step 2. Declare variables to store the two
numbers and the sum.
Step 3. Read the two numbers from the
user.
Step 4. Add the two numbers and store
the result in the sum variable.
Step 5. Display the sum as output.
Step 6. Stop
Q. write a c program to find the
largest number among three

Step 1. Start
Step 2. Initialize the three numbers let say a,b,c.
Step 3. Check if a is greater than b.
Step 4. If true, then check if a is greater than c.
1. If true, then print ‘a’ as the greatest
number.
2. If false, then print ‘c’ as the greatest
number.
Step 5. If false, then check if b is greater than c.
1. If true, then print ‘b’ as the greatest
number.
2. If false, then print ‘c’ as the greatest
number.
Q. Write an algorithm and c program
for finding average of n numbers.
Step 1. Start
Step 2. Initialize variables sum and count to 0.
Step 3. Input the value of n, the total number of
elements.
Step 4. Repeat n times:
a. Input the next number.
b. Add the number to sum.
c. Increment count by 1.
Step 5. Calculate the average by dividing sum by
count.
Step 6. Display the average.
Step 7. End

You might also like