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

Introduction –

C Programming
UNIT I
Programming Language?
A programming language is the communication bridge between a programmer and computer,
which is designed to communicate instructions to a machine, particularly a computer.
We have three types of programming languages
1.Low level language(Machine level language)
2.Mid-level language(Assembly level language)
Example:
LD R1 7; LOAD 1st VALUE in r1
LD R2 10; LOAD 2nd VALUE in r2
ADD R1, R2; R1=R1+R2
3.High level language
Translators?
High level and Mid-level languages require translators for communicating
the instructions to the computer. We have three types of translators.
1. Assembler
2. Interpreter
3. Compiler
Source Code: Source code is the code that is input to a translator.
Executable code: Executable code is the code that is output from the
translator.
Assembler
Assembler: An Assembler converts an assembly program into machine code.
Interpreter:
An Interpreter is also a program that translates high-level source code into
Executable code.
Compiler:
A Compiler is a program that translates a high level language into machine code.
Algorithm:
Algorithm is nothing but step-by-step solution of a problem which is written in a normal language
is called “Algorithm”.
An algorithm must possess the following properties:
1. Input: An Algorithm must take zero or more inputs (or) may not take inputs.
Output: An Algorithm should provide at least one output.
2. Finiteness: If we trace out the instructions of an algorithm, then for all cases the algorithm will
Terminate after a finite number of steps (An Algorithm should give results in a finite number of
steps).
3. Definiteness: An Algorithm should not contain ambiguous statements (or) instructions (Each
instruction must be clear and unambiguous).
4. Effective: Each statement in an algorithm is easily converted into an instruction and it can be
executed in a finite amount of time.
Examples: #1
1.Algorithm to read the name and print the name
Algorithm: Step 1 : Start
Step 2 : Read input name
Step 3 : Print name
Step 4 : Stop

2.Algorithm to print “hello welcome to C”


3.To calculate the area of a square.
4.To perform addition of two numbers.
5.To Find the average of three numbers.
Examples: #2
6. Algorithm for finding the maximum of two numbers:
Algorithm:
Step1: start
Step2: Read three numbers (A,B)
Step3: If A>B , then goto step4 otherwise goto step5
Step4: Print ‘A’ as maximum otherwise
Step5: Print ‘B’ is maximum.
Step6: Stop.
7. Algorithm to find the given number is even (or)odd.
8.To find given number is positive or negative.
Solution:

Algorithm:
Step1: start
Step2: Read number num.
Step3: Compute the modulus operation i.e.a=num%2.
Step4: If a=0 then
Display the given number is even
Step5: If a=1 then
Display the given number is odd
Step6: stop
Flowchart:
Graphical or symbolic representation of an algorithm is “Flow chart”
Advantages of Flowchart:
1. Conveys Better meaning.
2. Analyses the problem effectively:
3. Effective Coding:
4. Systematic Debugging
Symbols:
Ex 1: Read two numbers and produce the sum of those numbers.
Ex 2:Flowchart to find the average of three numbers
Ex 3: Flowchart to calculate area of square
Ex 4: Read two numbers & print the greater number.
Program Control Structures:
The structure of an algorithm(or)Flowchart(or)program decides the order of
execution of the steps.
The steps in an algorithm can be divided into three categories
Sequence
Selection
Iteration
Sequence:
The steps described in an algorithm are performed successively one by one
without skipping any step.
Ex: Algorithm:
Step 1 : Start
Step 2 : Read input name
Step 3 : Print name
Step 4 : Stop
Selection:
If the failure occurs in the sequence, there must be some alternative to handle. The selection statement is
If (Condition)
Statement1;
Else
Statement 2;
Example:Algorithm:
Step1:start
Step2:Read two numbers (A,B)
Step3:If A>B , then goto step4 otherwise goto step5
Step4:print ‘A’ as maximum otherwise
Step5:Print ‘B’ is maximum.
Step6:Stop.
Iteration:#1
§ In a program it is sometimes necessary to perform the same action for number of times.
§ If the statement is written repetitively, it will increase the program code.
§To avoid this problem, iteration mechanism is applied.
§The statements used are for and while.
1. for loop:
for (expression1; expression2; expression3)
{
Statement;
}
Iteration:#2

2. While loop:
-expression1;
While (expression2)
{
Statement;
expression3;
}
Example:
Software Development Method:
The Following are the steps required for developing the software.
1. Specify the Problem requirements
2. Analyze the Problem
3. Design the algorithm to solve the problem
4. Implement the algorithm
5. Test and verify the program
6. Maintain and update the program
Contents
1. What is C?
2. Features of C program.
3. Rules for Writing, Compiling and Executing the C program.
4. Structure of C program.
5. Library and IDE.
6. C Tokens.
7. Control characters (Escape sequences).
8. Receiving input values from keyboard.
9. Control Structures: Conditional and Iterative Statements
What is C?
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972 by
Dennis Ritchie.
Any programming Language can be divided in to two categories.
Problem oriented (High level language)
Machine oriented (Low level language)
But C is considered as a Middle level Language.
C is modular, portable, reusable.

[PTR: Language, Computer Language, Compiler, Interface, Applications]


Feature of C Program
1. Structured language
2. General purpose language
3. Portability
4. Code Re-usability & Ability to customize and extend
5. Limited Number of Key Word
Difference?
Compilers Interpreters
Compiler reads the entire source code
of the program and converts it into
Interpreter reads the program source
binary code. This process is called
code one line at a time and executing
compilation.
that line. This process is called
Binary code is also referred as
interpretation.
machine code, executable, and object
code.
Program speed is fast. Program speed is slow.
Interpretation occurs at every line of
One time execution.
the program.
Example: C, C++
Example: RUBY,Python
Rules for Writing, Compiling and
Executing the C program
•C is case sensitive means variable named "COUNTER" is different from a variable named "counter".
•All keywords are lowercased.
•Keywords cannot be used for any other purpose (like variable names).
•Every C statement must end with a ;. Thus ;acts as a statement terminator.
•First character must be an alphabet or underscore, no special symbol other than an underscore, no
commas or blank spaces are allowed with in a variable, constant or keyword.
•Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank spaces are allowed within a variable, constant or keyword.
•Variable must be declared before it is used in the program.
•File should be have the extension .c
•Program need to be compiled before execution.
Structure of C program
.

Pre-processor directives

Global declarations

main()
{
Local variable declaration
Statement sequences
Function invoking
}
C Input and Output(I/O)
As we all know the three essential functions of a computer are reading, processing and writing
data.
In C programming you can use scanf() and printf() predefined function to read and print data.

The above program scanf() is used to take input from the user, and respectively printf() is used
to display output result on the screen.
C Preprocessor Directives

Before a C program is compiled in a compiler, source code is processed by a program called


preprocessor. This process is called preprocessing.
The C preprocessor is a macro processor that is used automatically by the C compiler to
transform your program before actual compilation (Proprocessor direcives are executed before
compilation.).
Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
Example:
1. # include:
The #include preprocessor directive is used to paste code of given file into current file. It is used
include system-defined and user-defined header files.
Continued…..
2.# define
Macro is defined by # define directive.
Syntax:
#define token value
There are two types of macros:
1.Object like macros
2.Function like macros
Object like macros:

The object like macros is an identifier that is replaced by value.it is widely used to represent
numeric constants.
Example: #define PI 3.1415
Here, PI is the macro name which will be replaced by the value 3.14. Let's see an example of
Object-like Macros :

Output:3.1415
Function like macros

The function-like macro looks like function call.


For example:

Here, MIN is the macro name. Let's see an example of Function-like Macros :

Output: Minimum between 10 and 20 is:10


C library functions
Basic functions applicable to wide variety of common problems
§Input and Output
§Mathematical Operations
§Character Manipulation
§String Manipulation
§Sorting and Searching
§Time and Date
§Other Utility Functions
Library and IDE.
.
Stdio.h Conio.h

printf() clrscr()
scanf() getch()

graphics.h math.h

sqrt()
Setcolor()
pow()
Various parts of the C program
/* Comments */ Comments are a way of explaining what makes a program..

#include<stdio.h> stdio is standard for input / output, this allows us to use some commands which includes
a file called stdio.h.or
This is a preprocessor command.
int/void main() int/void is a return value,
main() The main() is the main function where program execution begins. Every C program must
contain only one main function.
Braces Two curly brackets "{...}" are used to group all statements.or
Curly braces which shows how much the main() function has its scope.

printf() It is a function in C, which prints text on the screen.


This is another pre-defined function of C which is used to be displayed text string in the
screen.
return 0 At the end of the main function returns value 0.
Steps….
STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:
Below are the steps to be followed for any C program to create and get the
output. This is common to all C program and there is no exception whether its a
very small C program or very large C program.
1. Create
2. Compile
3. Execute or Run
4. Get the Output
Variables:
In programming, a variable is a container (storage area/place holder) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location. For example:
int age=15;
Rules for naming a variable
A variable name can have letters (both uppercase and lowercase letters), digits and underscore
only.
The first letter of a variable should be either a letter or an underscore.
There is no rule on how long a variable name (identifier) can be. However, you may run into
problems in some compilers if variable name is longer than 31 characters.
Data Types
•Variables are placeholders used to store values.
•placeholders are called format specifiers.
• The data type of a variable determines how the bits representing
those values are stored in the computer's memory.
• When you declare a variable, you can also supply a data type for it.
•All variables have a data type that determines what kind of data they
can store.
Data types & Placeholders
C has 5 basic built-in data types.
Data type defines a set of values that a variable can store along with a set of operations that can be
performed on it.
General form for declaring a variable is:
type name;
*TTR
Format specifiers define the type of data to be printed on standard output. You need to use format
specifiers whether you're printing formatted output with printf() or accepting input with scanf().
Some of the % specifiers that you can use in ANSI C are as follows:
Range……
Example Programs 1:
(input ,output, data types and variables)

1. Write a program to print output as below:


Hello!, everyone#
Life is beautiful**
2. Write a C program to swap the two numbers.
3. Write a program to convert Fahrenheit to Celsius and viceversa
Celsius to Fahrenheit: (C × 9/5) + 32
Fahrenheit to Celsius ((F-32)*5)/9
4. C Program to Multiply Two Floating-Point Numbers.
5. Print the sum and difference of both integers separated by a space on the first line, and the sum and
difference of both float (scaled to 1 decimal place) separated by a space on the second line.
6. Program to Compute Quotient and Remainder.
Example Programs 1:
7. C Program to Find ASCII Value of a Character
8.Program to print the character, ch, in the first line. Then print string,s in next line. In the last
line print the sentence, sen.
C
Language
Welcome To C!!
9.Write a program to print your details as below:
My name is John.
I am studying First year at MITS college.
I belongs to CSE stream and A section.
My roll number is 20691A0501 and my favourite subject is Programming.
C Tokens:
•C tokens are the basic buildings blocks in C language which are constructed together to write a C program.
•Each and every smallest individual units in a C program are known as C tokens.C tokens are of six types.
They are:
Keywords
These are reserved words used in programming. There are 32 keywords predefined
by ANSI C.
e.g. int n;
Here int is keyword and it indicates n is of type integer.
Keywords used Control flow Storage class User defined data Special operator
while declaring related keywords related keywords type related related keyword
variables keywords
1. Int 1. If 1. Auto 1. Enum 1. Sizeof
2. Char 2. Else 2. Static 2. Typedef
3. Float 3. Switch 3. Register 3. Struct
4. Double 4. Case 4. Extern 4. Union
5. Long 5. Default
6. Short 6. Do
7. Signed 7. While
8. Unsigned 8. For
9. Volatile 9. Return
10. Void 10. Break
11. Const 11. Continue
12. Goto
Identifiers:
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique. They are created to give unique name to a entity to identify it during the
execution of the program. For example:
int money;
int account balance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an identifier
because int is a keyword.
Rules for naming identifiers
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. There is no rule on how long an identifier can be. However, you may run into problems in some
compilers if identifier is longer than 31 characters.
Constants:
What is Constant ?
Constant in C means the content whose value does not change at the time of execution of a
program.
Different Types of C Constants :

Constant Type of Value Stored Example


Constant which stores integer
Integer Constant 5, 9, 35
value

Floating Constant Constant which stores float value 5.25,0.22E-5, -2.0

Constant which stores character


Character Constant ‘a’, ’x’
value

String Constant Constant which stores string value “hello”, “sample”, ”good”
How to Declare Constant in C :

Declaration Explanation
read as “a is an integer which is
const int a = 1;
constant”
int const a = 1; read as “a is a constant integer”
Strings
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus,
a null-terminated string contains the characters that comprise the string followed by a null.
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
How to declare and initialize a string?

Here's how you can declare strings:


char s[5]=“sample”;
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0’};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Read String from the user
Example 1: scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
How to read a line of text?
You can use the fgets() function to read a line of string. And you can use puts() to display the string.
fgets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
, (comma) { (opening curly bracket)

. (period) } (closing curly bracket)

; (semi-colon) [ (left bracket) Special


: (colon)

? (question mark)
] (right bracket)

( (opening left parenthesis)


Symbols
' (apostrophe) ) (closing right parenthesis) Special characters in 'C' are shown in
the given table,
" (double quotation mark) & (ampersand)

! (exclamation mark) ^ (caret)

|(vertical bar) + (addition)

/ (forward slash) - (subtraction)

\ (backward slash) * (multiplication)

~ (tilde) / (division)

_ (underscore) > (greater than or closing angle bracket)

$ (dollar sign) < (less than or opening angle bracket)

% (percentage sign) # (hash sign)


Operator Meaning of Operator

+ addition or unary plus Operators


C Arithmetic Operators
- subtraction or unary minus An arithmetic operator performs
mathematical operations such as
addition, subtraction, multiplication,
* multiplication division etc on numerical values
(constants and variables).

/ division

remainder after division


%
(modulo division)
C Expressions
An expression is a formula in which operands are linked to
each other by the use of operators to compute a value.
Let's see an example:
a-b;
In the above expression, minus character (-) is an operator,
and a, and b are the two operands.
There are four types of expressions:
Arithmetic and Relational Expressions
Relational Expression Description

An arithmetic expression is an expression that x%2 = = 0 This condition is used to check


whether the x is an even number
consists of operands and arithmetic operators. or not. The relational expression
results in value 1 if x is an even
An arithmetic expression computes a value of type number otherwise results in value
int, float or double.. 0.
a!=b It is used to check whether a is
Ex:8 * (8/4) not equal to b. This relational
expression results in 1 if a is not
Relational Expressions equal to b otherwise 0.
a+b = = x+y It is used to check whether the
expression "a+b" is equal to the
A relational expression is an expression used to expression "x+y".
compare two operands. a>=9 It is used to check whether the
value of a is greater than or equal
to 9.
Logical Expressions
Logical Expressions Description
A logical expression is an expression
that computes either a zero or non-zero ( x > 4 ) && ( x < 6 ) It is a test condition to check
whether the x is greater than 4
value. and x is less than 6. The result
of the condition is true only
It is a complex test condition to take a when both the conditions are
decision. true.
x > 10 || y <11 It is a test condition used to
check whether x is greater than
10 or y is less than 11. The
result of the test condition is
true if either of the conditions
holds true value.
! ( x > 10 ) && ( y = = 2 ) It is a test condition used to
check whether x is not greater
than 10 and y is equal to 2. The
result of the condition is true if
both the conditions are true.
Conditional Expressions
A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator
Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
Ex:
Int a=10;
a>5? “T”:”F”
Topics covered
ØStructure of C Program
ØC Tokens: Variables, Data types, Constants,
Identifiers, key words and Operators
ØExpressions.
ØInt a=10,b=20;
CONTROL STRUCTURES
Conditional Statements
Conditional Statements in C programming are used to make decisions based on the conditions.
Conditional statements execute sequentially when there is no condition around the statements.
If statement
The If-Else statement
Nested If-else Statements
Nested Else-if statements
Switch statements
Relational Operators
C has six relational operators that can be used to formulate a Boolean expression for making a
decision and testing conditions, which returns true or false :
1. < less than
2. <= less than or equal to
3. > greater than
4. >= greater than or equal to
5. == equal to
6. != not equal to
If statement

üIt is one of the powerful conditional statement.


üIf statement is responsible for modifying the flow of execution of a program.
ü If statement is always used with a condition.
üThe condition is evaluated first before executing any statement inside the body
of If.
üThe syntax for if statement is as follows:
if (condition)
instruction;
Example programs
1.Program to check the number is equal to the given number 100.
2.Program to check the first num is greater than second number.
3.Program to print “yes” if input is nonzero value.
4.Program to print “Success” if sum of two numbers greater than 10.
If-Else statement
The if-else is statement is an extended version of If.
The general form of if-else is as follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
Example Programs
1. Program to determine if the value is less than ten or greater than ten.
2. Program to check the biggest among the two numbers.
3. Program to check even or odd.
4. Write a C program to check whether a number is divisible by 5 and 11 or not.
5. Write a C program to input any alphabet and check whether it is vowel or consonant.
6. Write a C program to check whether a year is leap year or not.
7. Write a C program to check whether a number is negative or positive.
Nested If-else Statements
In this example of nested if-else,
it first tests Condition1, if this condition is TRUE then it tests Condition2, if Condition2 evaluates to TRUE then
Statement1 is executed otherwise Statement2 will be executed.
if(condition)
{ //Nested if else inside the body of "if”
if(condition2)
{ //Statements inside the body of nested "if"
}
Else
{ //Statements inside the body of nested "else" }
}
else
{
//Statements inside the body of "else”
}
Example programs
1.Program to check a number is equal to 10,less than 10 or greater than 10 and prints the result using
nested if-else construct.
2. Write a C program to check whether a number is divisible by 5 and 3 or not using nested if-else
construct.
3.Write a C program to print positive,negative or Zero using nested if-else construct .
4.Write a C program to check leap year or not using nested if-else construct .
5.Write a program to find biggest among three numbers.
Nested Else-if statements
if (test - expression 1)
{ statement1; }
else if (test - expression 2)
{ Statement2; }
else if (test - expression 3)
{ Statement3; }
else if (test - expression n)
{ Statement n; }
else { default; } Statement x;
Example programs
.Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and
Computer. Calculate percentage and grade according to following:
Percentage >= 90% : Grade A
Percentage >= 80% : Grade B
Percentage >= 70% : Grade C
Percentage >= 60% : Grade D
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
2.Write a C program to input basic salary of an employee and calculate its Gross salary according to
following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%
3.Write a C program to input week number and print week day.
4.Write a C program to input month number and print number of days in that month.
Switch statements
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the
case match is found, a block of statements associated with that particular case is executed.
switch( expression )
{ case value-1: Block-1;
Break;
case value-2: Block-2;
Break;
case value-n: Block-n;
Break;
default: Block-1;
Break; }
Statement-x;
Key points on switch
1.Duplicate cases are not allowed.
2.Expressions allowed in switch may be an integral constant value.
3.Float values is not allowed as a constant value in case label.Only integer constants,constant
expressions are allowed in class label.
4.Defaults can be places anywhere in switch.
Key points:
Only Integer or Character.
In C , while using switch() are allowed to use :
Variables
◦ swtich(a){}
◦ A can be int a; or char a.

Arithmetic expressions
◦ switch(a++ + b + 1)…

You can even call a fucntion which returns some value.


◦ swtich(getValue())
◦ getVlaue() must return some value (int or char)

(Character value is allowed because it can use the ASCII value of the character as input to match the
cases.)
Example Programs
1.Write a C program to print day of week name using switch case.
2.Write a C program print total number of days in a month using switch case.
3.Write a C program to check whether an alphabet is vowel or consonant using
switch case.
4.Write a C program to find maximum between two numbers using switch case.
5.Write a C program to check whether a number is even or odd using switch case.
6.Write a C program to check whether a number is positive, negative or zero using
switch case.
7.Write a C program to create Simple Calculator using switch case.
ITERATIVE STATEMENTS
Loops
ØA Loop executes the sequence of statements many times until the stated condition becomes false. A loop consists of two
parts, a body of a loop and a control statement.
ØThe purpose of the loop is to repeat the same code a number of times.
Types of Loops in C
1. Entry controlled loop: In an entry controlled loop, a condition is checked before executing the body of a loop. It is
also called as a pre-checking loop.
2. Exit controlled loop: In an exit controlled loop, a condition is checked after executing the body of a loop. It is also
called as a post-checking loop.

'C' programming language provides us with three types of loop constructs:


1. The while loop
2. The do-while loop
3. The for loop
While Loop in C
ØIt is an entry-controlled loop.
ØA while loop is the most straightforward looping structure.
ØSyntax of while loop in C programming language is as
follows:
while (condition)
{
statements;
}

ØIn while loop, if the condition is not true, then the body of a
loop will not be executed, not even once;
Example Programs on while loop
1.Program to print the values from 1 to 100 using while loop.
2.Program to print multiplication table.
3.Program to find a factorial of a number.
4.Program to find the sum of first 10 natural numbers.
5.Program to print all the even numbers from 1 to 50 using while loop.
6.Program to check prime or not using while loop.
7.Program to print all the numbers divisible by both 3 and 5 from 1 to 100 using while loop.
8.Program to check Armstrong number or not.
9.Program to check perfect number or not.
11.Program to print the alphabets from a to z.
12.Program to print capital alphabet and ASCII value.
13. Program to check palindrome or not
Do While loop in C
A do...while loop in C is similar to the while loop except that
the condition is always executed after the body of a loop. It is
also called an exit-controlled loop.
Syntax of do...while loop in C programming language is as
follows:
Syntax of Do-While Loop in C:
do
{
Statements
} while (expression);
Example Programs on do-while loop
1. Write a program to print the values in a given range
2. Write a C program to find sum of all odd numbers between 1 to n.
3. Write a C program to count number of digits in a number.
4. Write a C program to find first and last digit of a number and also sum of first and last digit.
5. Write a C program to calculate sum and products of digits of a number.
6. Write a C program to enter a number and print its reverse.
For loop
A for loop is a more efficient loop structure in 'C'
programming. The general structure of for loop syntax in C is
as follows:
Syntax of For Loop in C:
for (initial value; condition; incrementation or
decrementation)
{
statements;
}
Example Programs on for loop
1. Program to print numbers from 50 to 1.
2. Write a C program to find square of a number from 1 to 10 using for loop.
3. C program to find it square root for a number from 1 to 10.
4. Program to print the prime number series.
5. Program to print the Armstrong number series.
6. to print all Strong numbers between 1 to n. Write a C program
7. Write a C program to print Fibonacci series up to n terms.
8. Write a C program to print lucas series up to n terms.
The Lucas numbers are in the following integer sequence:
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 …………..
Example programs on for loop(patterns)
1.C program to print half pyramid star pattern.
2.C program to print inverted half pyramid star pattern.
3.C program to print half pyramid number pattern.
4.C program to print half pyramid alphabet pattern.
5.C program to print full pyramid of star pattern.
Log10 (to count number of digits)
#include<stdio.h>
#include<math.h>
int main()
{
int n=45677345,a;
a=log10(n)+1;
printf("%d",a);
return 0;
}
Difference between while(non-zero) and
while(0)
üwhile(0) is treated as while with false condition. So this kind of loop is useless. It will never
execute the inner statement as 0 is treated as false.
üThe while(1) or while(any non-zero value) is used for infinite loop. There is no condition for
while. As 1 or any non-zero value is present, then the condition is always true. So what are
present inside the loop that will be executed forever. To come out from this infinite loop, we have
to use conditional statement and break statement.
Jump Statements
Break
The break is a keyword in C which is used to bring the program
control out of the loop.
The break statement in C can be used in the following two
scenarios:
ØWith switch case
ØWith loop
Syntax:
//loop or switch case
break;
Example programs on break
1. C program to take input from the user until he/she enters zero.
2. Program to calculate the sum of numbers (10 numbers max) // If the user enters a negative
number, the loop terminates
3. program asks a user input a integer number x. If x is divisible by 5, this causes the exit from
the loop.
Continue
The continue statement in C language is used to bring the program control to the beginning of
the loop.
The continue statement skips some lines of code inside the loop and continues with the next
iteration.
It is mainly used for a condition so that we can skip some code for a particular condition.
Syntax:
//loop statements
continue;
//some lines of the code which is to be skipped
Example programs on continue
1. C program to print sum of odd numbers between 0 and 10
2. Program to calculate the sum of numbers (10 numbers max) . If the user enters a negative
number, it’s should not be added to the result
3. write a program that will print 1 to 25, excluding the multiples of three.
Enumeration data type(enum)
ØThe enum in C is also known as the enumerated type. It is a user-defined data type that consists of
integer values, and it provides meaningful names to these values.
ØThe enum is defined by using the enum keyword.
ØThe enum is used when we want our variable to have only a set of values.
The following is the way to define the enum in C:
enum name{integer_const1, integer_const2,.....integter_constN};
For example:
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3.
If we want to change these default values, then we can do as given below:
enum fruits{ mango=2, apple=1, strawberry=5, papaya=7};
Example
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
printf("The value of Wednesday is %d",Wednesday);
return 0;
}
Output:
The value of Wednesday is 4
Topics covered
Control Structures
ØConditional Statements
(Simple if, if-else, Nested -if-else, Switch).
ØIterative Statements
(for, While, Do-While)
ØJump Statements
(break, Continue).
End of unit 1

You might also like