C Simplified for Beginners



Introduction and Programming languages​

Disclaimer: The contents are taken from various sources, which are mentioned for each figures and reference list provided at the end. it is just the compilation work done by the author of this blog. The information contained in this blog is compiled and published for educational purposes only. I acknowledge my gratitude towards the websites YouTube, Wikipedia, and Google search engine. 

Contents:

Chapter: 1

Programming Paradigms, Types of Programming Languages, Language Translators, Problem Solving Techniques: Algorithm, Flow Chart, Pseudo code, ​

 Chapter: 2

History of C, Features of C, Compilation, Process in C , Data Types in c, Keywords in c, C Identifiers, C Operators, Comments, Variables in C,C Format Specifier, C Escape Sequence, ASCII value in C, Constants in C.​

Chapter: 3

C Control Statements: if-else, Switch, if-else vs switch, do-while loop, while loop, for loop, Nested Loops, Infinite Loop in C, break, continue, goto, Type Casting 


Chapter: 1

Introduction:

Understanding Computer Systems

computer system is a combination of all the components required to process and store data using a computer. Every computer system is composed of multiple pieces of hardware and software.

Hardware is the equipment, or the physical devices, associated with a computer. For example, keyboards, mice, speakers, and printers are all hardware.

Software is computer instructions that tell the hardware what to do. Software is programs, which are instruction sets written by programmers.

Software can be classified into two broad types:

1.   Application software comprises all the programs you apply to a task, such as

Word processing programs, spreadsheets, payroll and inventory programs, and games. 

2.   System software comprises the programs that you use to manage your computer, including operating systems such as Windows, Linux, or UNIX for larger computers and Google Android and Apple iOS for smartphones. Together, computer hardware and software accomplish three major operations in most programs:

a.   Input—Data items enter the computer system and are placed in memory, where they can be processed. Hardware devices that perform input operations include keyboards and mice. Data items include all the text, numbers, and other raw material that are entered into and processed by a computer.

b.   Processing—Processing data items may involve organizing or sorting them, checking them for accuracy, or performing calculations with them. The hardware component that performs these types of tasks is the central processing unit, or CPU.

c.   Output—After data items have been processed, the resulting information usually is sent to a printer, monitor, or some other output device so people can view, interpret, and use the results. Programming professionals often use the term data for input items, but use the term information for data that has been processed and output. Sometimes you place output on storage devices, such as your hard drive, flash media, or a cloud-based device. (The cloud refers to devices at remote locations accessed through the Internet.)

 

      TYPES OF PROGRAMMING LANGUAGES 

1.    Machine Language

A collection of very detailed, cryptic(coded) instructions that control the computer’s internal circuitry.

Very few computer programs are actually written in machine language for following two significant reasons:

i.      Machine language is very cumbersome(complicated) to work with.

ii.      Every different type of computer has its own unique instruction set. Thus, a machine-language program written for one type of computer cannot be run on another type of computer without

significant alterations.

 2.   High-level language

In high-level language instruction set is more compatible with human languages and human thought processes. Some high-level programming languages are C, Pascal, FORTRAN and BASIC)

 There are also various special-purpose languages that are specifically designed for  some particular type of application. Some common examples are CSMP and SIMAN, which are special-purpose simulation languages, and LISP, a List processing language that is widely used for artificial intelligence applications.

 

Generation of programming Languages:

1. The first generation languages, or 1GL, are low-level languages that are machine language.

2. The second-generation languages, or 2GL, are also low-level assembly languages. They are sometimes used in kernels and hardware drives, but more commonly used for video editing and video games.

3. The third-generation languages, or 3GL, are high-level languages, such as C, C++, Java, JavaScript, and Visual Basic.

4. The fourth-generation languages, or 4GL, are languages that consist of statements similar to statements in a human language. Fourth generation languages are commonly used in database programming and scripts examples include Perl, PHP, Python, Ruby, and SQL.

5. The fifth-generation languages, or 5GL, are programming languages that contain visual tools to help develop a program. Examples of fifth generation languages include Mercury, OPS5, and Prolog.

Advantages of High-level programming over Machine language 

Simplicity:- As a rule, a single instruction in a high-level language will be equivalent to several instructions in machine language. This greatly simplifies the task of writing complete, correct programs. 

Uniformity:- The rules for programming in a particular high-level language are much the same for all computers 

Portability:- The rules for programming in a particular high-level language are much the same for all computers a program written for one computer can generally be run on many different computers with little or no alteration.

  Compilation, Interpretation and linker:

A program that is written in a high-level language must, however, be

translated into machine language before it can be executed. This is known as

compilation or interpretation

 Compiler

A compiler translates high-level instructions directly into machine language

before executing any of the instructions.

         Interpreter

An interpreter translates high-level instructions into an intermediate form, which it then executed.                       

A compiler or interpreter is itself a computer program. It accepts a program written in a high-level language (e.g., C) as input, and generates a corresponding machine-language program as output. The original high-level program is called the source program, and the resulting machine-language program is called the object program. Every computer must have its own compiler or interpreter for a particular high-level language.

 

        linker

A linker is an important utility program that takes the object files, produced by the assembler and compiler, and other code to join them into a single executable file.

 

Programming Paradigms:

Following Programming models are available in general:

1.     1.     Imperative Programming​
2.      Object-Oriented Programming (OOP)​
3.      Functional Programming​
4.      Logical Programming​
5.      Declarative Programming​
6.      Event-Driven Programming​

 1.      Imperative Programming​:

Imperative programming focuses on describing the step-by-step sequence of actions needed to achieve a specific goal. Example Language: C​

 Code Example:​

 #include <stdio.h>​

 int main() ​

 {​

     float area, radius = 5;​

     const float pi = 3.14;​

     area = pi * radius * radius;​

     printf("Area = %f", area);​

     return 0;​

  }​

2.      Object-Oriented Programming (OOP)​:

OOP emphasizes organizing code into objects, which are instances of classes, and using concepts like inheritance and encapsulation.​

• Example Language: Java​

//Code Example:​

  class Circle {​

     double radius;​

     double calculateArea() {​

         return Math.PI * radius * radius;​

     }​

 }​

  public class Area ​

 {​

     public static void main(String[] args) {​

         Circle circle = new Circle();​

         circle.radius = 5.0;​

         double area = circle.calculateArea();​

         System.out.println("Area: " + area);​

     }​

 }​

3.      Functional Programming​:

Functional programming treats computation as the evaluation of mathematical functions and promotes immutability and higher-order functions. Example Language: Haskell​

-- Function to calculate the factorial of a number​

factorial :: Integer -> Integer​

factorial 0 = 1​

factorial n = n * factorial (n - 1)​

main :: IO ()​

main = do​

    let n = 5​

    putStrLn ("Factorial of " ++ show n ++ ": " ++ show (factorial n))​

Logical Programming​:

Logical programming involves expressing the program as a set of logical rules and facts, and the execution derives conclusions from these rules. Example Language: Prolog. Code Example:​

parent(john, jim).​

parent(john, sara).​

sibling(X, Y) :- parent(Z, X), parent(Z, Y), X \= Y.​

% Query: Is Jim a sibling of Sara?​

?- sibling(jim, sara).​


Declarative Programming​:

Declarative programming focuses on expressing what needs to be done, rather than how to do it.​

Example Language: SQL (Structured Query Language)​

Code Example:​

-- SQL query to retrieve names of employees in a specific department​

SELECT name FROM employees WHERE department = 'Sales';​

Event-Driven Programming​:

Event-driven programming responds to events, like user actions or messages, to determine the flow of the program. Example Language: JavaScript (for web development)​

Code Example (Node.js):​

const readline = require('readline');​

const rl = readline.createInterface({​

    input: process.stdin,​

    output: process.stdout​

});​

rl.question('What is your name? ', (name) => {​

    console.log(`Hello, ${name}!`);​

    rl.close();​

});​

 


Chapter : 2

History of C

C was originally developed in the 1970s by Dennis Ritchie at Bell Telephone Laboratories, Inc. (now a part of AT&T). It is an outgrowth of two earlier languages, called BCPL and B, which were also developed at Bell Laboratories.

Early commercial implementations of C differed somewhat from Kernighan and Ritchie’s original definition, resulting in minor incompatibilities between different implementations of the language. These differences diminished the portability that the language attempted to provide. Consequently, the American National Standards Institute (ANSI committee X3J11) has developed a standardized definition of the C language.

In the early 1980s, another high-level programming language, called C++, was developed by Bjarne Stroustrup at the Bell Laboratories. C++ is built upon C, and hence all standard C features are available within C++.

 

 

 

Features of C Language

1.   Simple:- C is a simple language in the sense that it provides structured approach (to break the problem into parts), rich set of library functions, data types etc.

2.   Machine Independent or Portable:- Unlike assembly language, c programs can be executed  in  many  machines  with  little  bit  or  no  change.  But  it  is  not  platform- independent.

3.   Mid-level programming language:- C is also used to do low level programming. It is used to develop system applications such as kernel, driver etc. It also supports the feature of high level language. That is why it is known as mid-level language.

4.   Structured programming language:- C is a structured programming language in the sense  that  we  can  break  the  program  into  parts  using  functions.  So,  it  is  easy  to understand and modify.

5.   Rich Library:- C provides a lot of inbuilt functions that makes the development fast.

6.   Memory Management:- It supports the feature of dynamic memory allocation. In C

language, we can free the allocated memory at any time by calling the free() function.

7.   Fast Speed:- The compilation and execution time of C language is fast.

8.   Pointers:-  C  provides  the  feature  of  pointers.  We  can  directly  interact  with  the memory by using the pointers. We can use pointers for memory, structures, functions, array etc.

9.   Recursion:-  In  c,  we  can  call  the  function  within  the  function.  It  provides  code reusability for every function

10. Extensible:- C language is extensible because it can easily adopt new features.

 

 

Applications of C

        1.   C language is used for creating computer applications

2.   Used in writing Embedded softwares

3.   Firmware for various electronics, industrial and communications products which use micro-controllers.

4.   It is also used in developing verification software, test code, simulators etc. for various applications and hardware products.

5.   For Creating Compiles of different Languages which can take input from other language and convert it into lower level machine dependent language.

6.   C is used to implement different Operating System Operations.

7.   UNIX kernel is completely developed in C Language.

Algorithm and Flowchart

   Algorithm and flowchart are the powerful tools for learning programming. An algorithm is a step-by-step analysis of the process, while a flowchart explains the steps of a program in a graphical way.

  Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language.

Characteristics of an Algorithm

Not all procedures can be called an algorithm. An algorithm should have the following characteristics −

  • Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning.
  • Input − An algorithm should have 0 or more well-defined inputs.
  • Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.
  • Finiteness − Algorithms must terminate after a finite number of steps.
  • Feasibility − Should be feasible with the available resources.
  • Independent − An algorithm should have step-by-step directions, which should be independent of any programming code.

 

Algorithm writing is a process and is executed after the problem domain is well-defined.

Ex 1: Write an algorithm to add 2 numbers and print the sum.

Step 1 – START.

Step 2 – Read A, B.

Step 3 – SUM=A+B.

Step 4 –  Print SUM.

Step 5 –  STOP.

 

Ex 2:  Write an algorithm to find the average of 3 numbers.

Step 1 –  START.

Step 2 – Read A, B,C.

Step 3 – SUM=A+B+C.

Step 4:  AVERAGE=SUM / 3.

Step 5 –   Print AVERAGE.

Step 6 –    STOP.

                                                  Flowchart

The flowchart is a diagram which visually presents the flow of data through processing systems. This means by seeing a flow chart one can know the operations performed and the sequence of these operations in a system.

                                                    Flowchart Symbols

There are 6 basic symbols commonly used in flowcharting of assembly language Programs: Terminal, Process, input/output, Decision, Connector and Predefined Process.

            source : http://naveenkandwal.blogspot.com/2014/01/flowchart_18.html


General Rules for Flowcharting

1. All boxes of the flowchart are connected with Arrows.

2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all flowchart symbols is on the bottom except for the Decision symbol.

3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.

4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does not exceed 3 symbols.

5. Connectors are used to connect breaks in the flowchart. Examples are:

       • From one page to another page.

       • From the bottom of the page to the top of the same page.

 6. Subroutines and Interrupt programs have their own and independent flowcharts.

7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol.

8. All flowcharts end with a terminal or a contentious loop.

 Ex1: Flowchart to add sum of two numbers. 

 Pseudocode is an English-like representation of the logical steps it takes to solve a problem. It is not necessarily follow all the syntax rules of any specific language to write pseudocode.

e.g. a pseudocode representation of a number-doubling problem:

start

            input myNumber

            set myAnswer = myNumber * 2

            output myAnswer

stop

 

Pseudocode Standards

      Programs begin with start and end with stop; these two words are always aligned.

      Whenever a module name is used, it is followed by a set of parentheses.

      Modules begin with the module name and end with return. The module name and return are always aligned.

      Each program statement performs one action—for example, input, processing, or output.

      Program statements are indented a few spaces more than start or the module name.

      Each program statement appears on a single line if possible. When this is not possible, continuation lines are indented.

      Program statements begin with lowercase letters.

      No punctuation is used to end statements.

 

Sentinel value to end a program

 

     A program that contains an infinite loop is one that never ends. Such programs can be stopped by giving some predefined values. A preselected value that stops the execution of a program is often called a dummy value or a sentinel value.

     Many programming languages use the term fe (for file end) to refer to a marker that automatically acts as a sentinel.

For eg:

The program can be used to add up a list of numbers. But the user first has to count up how many numbers are to be added up. This could be annoying. Instead of counting numbers user can specify sentinel value like zero to stop the program. i.e.  The user will enter numbers, one by one, and the program will add each number to SUM. The user tells the program to stop by entering a zero. The zero is how the user "signals" that the program should stop looping.

 

DESIRABLE PROGRAM CHARACTERISTICS

1.   Integrity: This refers to the accuracy of the calculations. It should be clear that all other program enhancements will be meaningless if the calculations are not carried out correctly. Thus, the integrity of the calculations is an absolute necessity in any computer program.

2.   Clarity refers to the overall readability of the program, with particular emphasis on its underlying logic. If a program is clearly written, it should be possible for another programmer to follow the program logic without undue effort. It should also be possible for the original author to follow his or her own program after being away from the program for an extended period of time.

3.   Simplicity: The clarity and accuracy of a program are usually enhanced by keeping things as simple as possible, consistent with the overall program objectives.

4.   Efficiency is concerned with execution speed and efficient memory utilization.

5.   Modularity: Many programs can be broken down into a series of identifiable subtasks. It is good programming practice to implement each of these subtasks as a separate program module. In C, such modules are written as functions.

6.   Generality: Usually we will want a program to be as general as possible, within reasonable limits. For example, we may design a program to read in the values of certain key parameters rather than placing fixed values into the program.

 

Fundamentals

Structure of a program

A C program basically consists of the following parts −

   Documentation

   Preprocessor Commands

   Functions

   Variables

   Statements & Expressions

   Comments

 

Eg:

// C program to print Hello world!

#include <stdio.h>

int main()

{

                     /* my first program in C */

printf("Hello, World! \n");

return 0;

}

   The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation.

   The next line int main() is the main function where the program execution begins.

   The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.

   The next line printf(...) is another function available in C which causes the message

"Hello, World!" to be displayed on the screen.

   The next line return 0; terminates the main() function and returns the value 0.

Character Set

C uses the uppercase letters to Z, the lowercase letters a to z, the digits 0 to 9, and certain special characters as building blocks to form basic program elements (e.g., constants, variables, operators, expressions, etc.). The special characters are listed below.

  

IDENTIFIERS AND KEYWORDS

   ldentifiers are names that are given to various program elements, such as variables, functions and arrays.

   Identifiers consist of letters and digits, in any order, except that the first character    must be a letter.

   Both upper- and lowercase letters are permitted.

    Upper- and lowercase letters are not interchangeable (i.e., an uppercase letter is not equivalent to the corresponding lowercase letter.)

    The underscore character ( - ) can also be included, and is considered to be a letter. An underscore is often used in the middle of an identifier.

   An identifier may also begin with an underscore.

  

Example1:

The following names are valid identifiers:

 

Example2:

The following names are not valid identifiers for the reasons stated.

 Keywords

There are certain reserved words, called keywords, that have standard, predefined meanings in C. These keywords can be used only for their intended purpose; they cannot be used as programmer-defined identifiers.

 The standard keywords are

 

DATA TYPES

Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

 

Type      

Description

 

Basic Types                

They are arithmetic types and are further classified into:

(a) integer types and

(b) floating-point types

Enumerated types       

       They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program.

The type void              

The type specifier void indicates that no value is available.

Derived types

They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.

 

Integer Types

Type

Storage Space

Value Range

Char

1 byte

-128 to 127 or 0 to 255

 

unsigned char

1 byte

0 to 255

signed char

1 byte

-128 to 127

 

Int

2 or 4 bytes

-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int

2 or 4 bytes

0 to 65,535 or 0 to 4,294,967,295

 

Short

2 bytes

-32,768 to 32,767

 

unsigned short

2 bytes

0 to 65,535

Long

4 bytes

-2,147,483,648 to 2,147,483,647

unsigned long

4 bytes

0 to 4,294,967,295

 

Floating-Point Types

Type

Storage Space

Value Range

Precision

Float

4 bytes

1.2E-38 to 3.4E+38

6 decimal places

Long

8 bytes

2.3E-308 to 1.7E+308            

15 decimal places

Double

10 bytes

3.4E-4932 to 1.1E+4932       

19 decimal places

 

 CONSTANTS

There are four basic types of constants in C.

   integer constants

   floating-point constants

   character constants

   string constants

The following rules apply to all numeric-type constants.

   Commas and blank spaces cannot be included within the constant.

   The constant can be preceded by a minus (-) sign if desired. (Actually the minus sign is an operator that changes the sign of a positive constant, though it can be thought of as a part of the constant itself.)

   The value of a constant cannot exceed specified minimum and maximum bounds. For each type of constant, these bounds will vary from one C compiler to another.

 

1.    Integer Constants

             An integer constant is an integer-valued number. Thus it consists of a sequence of  

             digits. Integer constants can be written in three different number systems: decimal (base    10), octal (base

8) and hexadecimal (base 16). Some valid decimal integer constants:

0             12           -234        76543     -8901

The following decimal integer constants are written incorrectly for the reasons stated.

 

  Unsigned and Long Integer Constants

Unsigned integer constants may exceed the magnitude of ordinary integer constants by

approximately a factor of 2, though they may not be negative.* An unsigned integer constant can be identified by appending the letter U (either upper- or lowercase) to the end of the constant.

Long integer constants may exceed the magnitude of ordinary integer constants, but require more memory within the computer. To create a long integer constant by appending the letter L (either upper- or lowercase) to the end of the constant.

 

Some unsigned and long integer constants are shown below

500000U               (decimal unsigned)

123456789L          (Decimal Long)

123456789UL       (Decimal unsigned long)

 

2.    Floating-Point Constants

A floating-point constant is a base- 10 number that contains either a decimal  point or an exponent (or both).

Some valid floating-point constants are shown below.



  The following are not valid floating-point constants for the reasons stated.

 


3.    Character Constants

character constant is a single character, enclosed in apostrophes (i.e., single quotation marks). Some character constants are shown below:

Character constants have integer values that are determined by the computer's particular character set. Most computers make use of the ASCII (i.e., American Standard Code for Information Interchange) character set, in which each individual character is numerically encoded with its own unique 7-bit combination (hence a total of 2' = 128 different characters).

Some character constants and their corresponding values, as defined by the ASCII character set, are shown below.

 

 Escape Sequences

An escape sequence always begins with a backward slash(\) and is followed by one or more special characters.

 


String Constants

string constant consists of any number of consecutive characters (including none), enclosed in (double) quotation marks. Some string constants are shown below.

 


the string constant "Line 1\nLine 2\nLine 3" extends over three lines, because of the newline characters that are embedded within the string. Thus, this string would be displayed as

Line 1

Line 2

Line 3

 

VARIABLES AND ARRAYS

   A variable is an identifier that is used to represent a single data item; i.e., a numerical quantity or a character constant within a designated portion of the program.

   The data item must be assigned to the variable at some point in the program.

   The data item can then be accessed later in the program simply by referring to the variable name.

   A given variable can be assigned different data items at various places within the program.

   Thus, the information represented by the variable can change during the execution of the program. However, the data type associated with the variable cannot change.

   Example:

C program contains the following lines

 


The first two lines are type declarations, which state that a, b and c are integer variables, and that d is a char-type variable.

The next four lines cause the following things to happen: the integer quantity 3 is assigned to a, 5 is assigned to b, and the quantity represented by the sum a + b (i.e., 8) is assigned to c. The character 'a' is then assigned to d.

The last four lines redefine the values assigned to the variables as follows: the integer quantity 4 is assigned to a, replacing the earlier value, 3; then 2 is assigned to b, replacing the earlier value, 5; then the difference between a and b (i.e., 2) is assigned to c, replacing the earlier value, 8. Finally, the character ' W' is assigned to d, replacing the earlier character, ' a ' .

Array

   An array is an identifier that refers to a collection of data items that all have the same name. The data items must all be of the same type (e.g., all integers, all characters, etc.).

   The individual data items are represented by their corresponding array-elements (i.e., the first data item is represented by the first array element, etc.).

   The individual array elements are distinguished from one another by the value that is assigned to a subscript.

 

Declaration

   A declaration associates a group of variables with a specific data type. All variables must be declared before they can appear in executable statements.

   A declaration consists of a data type, followed by one or more variable names, ending with a semicolon.

   Each array variable must be followed by a pair of square brackets, containing a positive integer which specifies the size (i.e., the number of elements) of the array.

   A C program contains the following type declarations

int a, b, c ;

float   root l , root2;

char flag , text [ 80] ;

These declarations could also have been written as follows.

int a;

int b;

 

float rootl; float root2; char flag;

char text[80];

 

EXPRESSIONS

An expression represents a single data item, such as a number or a character. The expression may consist of a single entity, such as a constant, a variable, an array element or a reference to a function. It may also consist of some combination of such entities, interconnected by one or more operators.

Expressions can also represent logical conditions that are either true or false. However, in C the conditions true and false are represented by the integer values 1 and 0,respectively

 

Some simple expressions are shown below.

a + b x = y

c = a + b x <= y

x == Y

i=i+1

 

 

STATEMENTS

A statement causes the computer to carry out some action. There are three different classes of statements in C. They are expression statements, compound statements and control statements. An

expression statement consists of an expression followed by a semicolon.

 

Some expression statements are shown below.

a = 3;

c = a + b ;

i++;

 

compound statement consists of several individual statements enclosed within a pair of braces

{ }. The compound statement provides a capability for embedding statements within other statements. Unlike an expression statement, a compound statement does not end with a semicolon.

 

A typical compound statement is shown below.

{

p i = 3.141593;

circumference = 2. * p i * radius;

area = p i * radius * radius;

}

 

Control statements are used to create special program features, such as logical tests, loops and branches.

 if(a>b)

     printf(“first no is greater”);

}

else

{

    printf(“second no is greater”);

}

 

SYMBOLIC CONSTANTS

A symbolic constant is a name that substitutes for a sequence of characters. The characters may represent a numeric constant, a character constant or a string constant. Thus, a symbolic constant allows a name to appear in place of a numeric constant, a character constant or a string. When a program is

compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. Symbolic constants are usually defined at the beginning of a program.

A symbolic constant is defined by writing

#define   name   text

where name represents a symbolic name, typically written in uppercase letters, and text represents the sequence of characters that is associated with the symbolic name.

 

A C program contains the following symbolic constant definitions.

#define TAXRATE 0.23 

#define P I 3.141593 

#define TRUE 1 

#define FALSE 0 

#define FRIEND "Susan"

 

Now suppose that the program contains the statement

area = PI * radius * radius;

During the compilation process, each occurrence of a symbolic constant will be replaced by its corresponding text. Thus, the above statement will become

area = 3.141593 * radius * radius;

 

 Question Bank:

1.   What are different types of programming language? Explain in detail.

2.   Explain any five features of C language.

3.   What are the applications of C language?

4.   What are the different phases of program development cycle? Explain in detail.

5.   What do you mean by sentinel value? Explain in detail.

6.   What are different desirable program characteristics?

7.   Explain basic structure of a C program.

8.   What are identifiers?  What are naming rules for identifiers?

9.   Explain different basic data types in C.

10. Explain different types of constants in C.

11. What are escape sequences? Explain.

12. What are variables? Explain with example.

13. What are different types of statements in C?

14. What are symbolic constants? Explain with example.

15. Explain different symbols in flowchart?

        16. Draw a flowchart and a pseudo code of a program that doubles the number. 

        17. What is a statement in C? Explain Different classes of statements in C.

        18. What do you understand from simple program logic? Discuss with suitable example.

        19. What are the rules for writing identifiers?

        20. What are constants in c? Discuss various types of constants used in c.

  1. 21.  Write a pseudo code to find out the factorial of a number.
  2. 22.  What do you understand from simple program logic? Discuss with suitable example.
  3. 23.   How is the variable declared and used in an expression?
  4. 24.   What is a statement in C? Explain Different classes of statements in C.




Chapter 3


Control / Conditional Statements

If Statement

Simple if

if-else

else if ladder

Nested if else

Switch statement

if Statement

The if statement has the following syntax:



Logic of an if statement



A program to illustrate the use of if statement.

# include <stdio.h>

 int main()

{

    int x=10,y=20;

    if(y>x)

    {

          printf(“Y is greater than x”);

    }

    return 0;

}

output:

y is greater than x



if else

An else clause can be added to an if statement to make an if-else statement

Syntax:

if (condition )

   statement1;

else

   statement2;

If the condition is true, statement1 is executed;  if the condition is false, statement2 is executed

One or the other will be executed, but not both.

Flowchart of if else

      A program to decide whether to give 10% discount or not based on the total qty purchased.
#include<stdio.h>
int main()
{
   int qty, rate=100;
   float disc, amt;
   printf("\nEnter quantity: ");
   scanf("%d",&qty);
   if (qty>100)
      disc = qty*rate*(.10);
   else
      disc = 0.0;
   amt = qty*rate - disc;
   printf("\n quantity %d, amount =%12.2f",qty, amt);
   return 0;

                } 

              output:

         

          


else if Ladder

It  generally looks like a ladder hence it is also called as an else-if ladder. 

The test-expressions are evaluated from top to bottom. 

Whenever a true test-expression if found, statement associated with it is executed. 

When all the n test-expressions becomes false, then the default else statement is executed.

else if Ladder syntax

 if (test==expression1)

{

     Statement1;

}

else if (test==expression2)

{

     Statement 2;

}

else if (test==expressionn)

{

      Statement n; 

}

else

{

      Statement;

}

a program on else if ladder

// check for a vowel or a consonant

#include<stdio.h>

int main()

{

    char ch;

    printf("Enter an Alphabet: ");

    scanf("%c", &ch);

    if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u’)

        printf("\nIt's a Vowel");

    else if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U’)

        printf("\nIt's a Vowel");

    else

        printf("\nIt's a Consonant");

    return 0;

}


Activity – Class work

// read a number and check whether it is positive, negative or zero.

// read percentage of a student and find the class awarded.

// displaying greeting of the day

Nested if else

When a series of decision is required, nested if-else is used. 

Nesting means using one if-else construct within another one.

Syntax

if (condition1)  

    if (condition2) 

        statement1;  

    else

        statement2;

else  

    if (condition3) 

        statement3;  

    else

        statement4;

A program on Nested If else statement

// To find greatest of 3 numbers

#include <stdio.h>

int main() {

  int n1, n2, n3;

  printf("Enter three numbers: ");

  scanf("%d %d %d", &n1, &n2, &n3);

if (n1 >= n2) {

    if (n1 >= n3)

      printf("%d is the largest number.", n1);

    else

      printf("%d is the largest number.", n3);

 }

else {

    if (n2 >= n3)

      printf("%d is the largest number.", n2);

    else

      printf("%d is the largest number.", n3);

  }

  return 0;

}

switch case statement

      When we use nested if-else statement to check more than 1 condition then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch case'.


       Syntax of switch...case:

switch (<expression>) 

{

     case <expr1>: 

          <sequence of statements>;

          break;

     case <expr2>: 

          <sequence of statements>;>;

          break;

     case <exprn>:

          <sequence of statements>;>;

          break;

     default:       

         <sequence of statements>;>;

 }

The expression followed by each case label must be a constant expression. e.g. 1,2,3 or 'a', 'b' 'c' etc.

Case labels must end with (:) colon.

No two case labels can have the same value. 

Two case labels may be associated with the same statements. 

Break statement will bring the control out of the switch..case.

The default label is not required. 

There can be only one default label, and it is usually last. 

C program to create a simple calculator

// Program to create a simple calculator

#include <stdio.h>

int main() {

    char operation;

    double n1, n2;

    printf("Enter an operator (+, -, *, /): ");

    scanf("%c", &operation);

    printf("Enter two operands: ");

    scanf("%lf %lf",&n1, &n2);

    switch(operation)

    {

        case '+':

            printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);

            break;

        case '-':

            printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);

            break;

        case '*':

            printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);

            break;

        case '/':

            printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);

            break;

        default:

            printf("Error! operator is not correct");

    }

    return 0;

}

ADVANTAGES OF switch case:

Easy to use.

Easy to find out errors.

Debugging is made easy in switch case.

Complexity of a program is minimized.

Difference  between if and switch 


Difference  between if and switch 

    

TYPES OF LOOPING STATEMENTS

Basically, the types of looping statements depend on the condition checking mode. 

Condition checking can be made in two ways as: Before loop and after loop. So, there are 2(two) types of looping statements:

  • Entry controlled loop
  • Exit controlled loop

1. Entry controlled loop:

In such type of loop, the test condition is checked first before the loop is executed.

Some common examples of entry controlled looping statements are:

o while loop

o for loop

while loop:

This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.

Syntax:

while(condition)

{

statements;

increment/decrement;

}

Flowchart:


 
Here, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.

/*  Program to demonstrate while loop. */

#include <stdio.h>

#include <conio.h>

void main()

{

int  a;

clrscr();

a=1;

while(a<=5)

{

printf("\n Hello");

a+=1      // i.e. a = a + 1

}

getch();

}

output


For loop:

This is an entry-controlled looping statement.

In this loop structure, more than one variable can be initialized. 

One of the most important feature of this loop is that the three actions can be taken at a time like variable initialization, condition checking and increment/decrement. 

The for loop can be more concise and flexible than that of while and do-while loops.

Syntax:

for(initialization; test-condition; increment /decrement)

{

statements;

}

In above syntax, the given three expressions are separated by ';' (Semicolon)

Flowchart


Features:

o More concise

o Easy to use

o Highly flexible

o More than one variable can be initialized.

o More than one increments can be applied.

o More than one conditions can be used.

/*  Program to demonstrate for loop.*/

#include <stdio.h>

#include <conio.h>

void main()

{

int  a;

clrscr();

for(i=0; i<5; i++)

{

printf("\n\t Hello");  

}

getch();

}

output:


2. Exit controlled loop:

In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed at least one time compulsorily.

Some common example of this looping statement is:

do-while loop:

This is an exit controlled looping statement.

Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.

Syntax:

do

{

statements;

(increment/decrement);

}

while(condition);

flowchart

Here, the first the block of statements are executed.

At the end of loop, while statement is executed. 

If the resultant condition is true, then program control goes to evaluate the body of a loop once again. 

This process continues till condition is true.

When it becomes false, then the loop terminates.

Note: The while statement should be terminated with ; (semicolon).

/*  Program to demonstrate do while loop. */

#include <stdio.h>

#include <conio.h>

void main()

{

int  a;

clrscr();

a=1;

do

{

printf("\n\t Hello");  

a+=1;      // i.e. a = a + 1

}while(a<=5);

a=6;

do

{

printf("\n\n\t Hello");  

a+=1;      // i.e. a = a + 1

}while(a<=5);

getch();

}

output:



Print a multiplication table of a number using do…while loop

#include <stdio.h>

void main()

{

    int num, i = 1;

    printf("\n Enter any Number:");

    scanf("%d", &num);

    printf("Multiplication table of %d: \n", num);

    do

   {

        printf("\n %d x %d = %d", num, i, num * i);

        i++;

   } while (i <= 10);

}

Nested Loops

A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required.

Types of nested loops

Nested while loop

Nested for loop

Nested do-while loop

Nested while loop

A while loop inside another while loop is called nested while loop.

Syntax of Nested while loop

while (condition1)

{

    statement(s);

    while (condition2)

    {

        statement(s);

   }

}

C program to print the number pattern.

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

#include <stdio.h>

int main()

{

    int i=1,j;

    while (i <= 5)

    {

        j=1;

        while (j <= i )

        {

            printf("%d ",j);

            j++;

        }

        printf("\n");

        i++;

    }

    return 0;

}

Nested for loop

Syntax of Nested for loop

for (initialization; condition; increment/decrement)

{

    statement(s);

    for (initialization; condition; increment/decrement)

    {

        statement(s);

    }

}

// C program to calculate the area of a rectangle using nested for loop

#include <stdio.h>

int main() {

    int rows = 10;

    int cols = 10;

    // Outer loop for rows

    for (int i = 1; i <= rows; i++) {

        // Inner loop for columns

        for (int j = 1; j <= cols; j++) {

            printf("%4d", i * j); // Printing each multiplication result

        }

        printf("\n"); // Move to the next line after each row

    }

    return 0;

}

Nested do-while loop

Syntax of Nested do-while loop

do

{

    statement(s);

    do

    {

        statement(s);

     }while (condition2);

}while (condition1);

C program to print the given star pattern.

*

**

***

****

*****

#include <stdio.h>

int main()

{

    int i=1,j;

    do

    {

        j=1;

        do

        {

            printf("*");

            j++;

        }while(j <= i);

        i++;

        printf(“\n");

    }while(i <= 5);

    return 0;

}

C program to print the given star pattern.

*

**

***

****

*****

****

***

**

*

#include <stdio.h>

int main()

{

    int i=1,j;

    do

    {

        j=1;

        do

        {

            printf("*");

            j++;

        }while(j <= i);

        i++;

        printf("\n");

    }

    while(i <= 5);

    

 i = 4; 

do

    {

        j = 1;

        do

        {

            printf("*");

            j++;

        }while(j <= i);

        i--;

        printf("\n");

    }

    while(i >= 1);

    return 0;

}

Infinite Loop in C

An infinite loop is a looping construct that does not terminate the loop and executes the loop forever. It is also called an indefinite loop or an endless loop. 

When to use an infinite loop

In the following situations, this type of loop can be used:

All the operating systems run in an infinite loop as it does not exist after performing some task. It comes out of an infinite loop only when the user manually shuts down the system.

All the servers run in an infinite loop as the server responds to all the client requests. It comes out of an indefinite loop only when the administrator shuts down the server manually.

All the games also run in an infinite loop. The game will accept the user requests until the user exits from the game.

#include <stdio.h>  

int main()  

{  

   for(;;)  

   {  

     printf("Hello everyone!!");  

   }  

return 0;  

C break

The break statement ends the loop immediately when it is encountered. 

Its syntax is:

                    break;

The break statement is almost always used with if...else statement inside the loop.

How break statement works


Find the output of the following code:


output:

C continue

The continue statement skips the current iteration of the loop and continues with the next iteration.

 Its syntax is:

        continue;

The continue statement is almost always used with the if...else statement.

How continue statement works

find the output of the following code


output:


C goto

The goto statement allows us to transfer control of the program to the specified label.

Syntax:

goto label;

... .. ...

... .. ...

label: 

statement;

The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.



practical

1 a

// Print your name 

#include <stdio.h>

#include<conio.h>

int main()

{

    clrscr();

    printf(“My name is Beena Kapadia");

    getch();

    return 0;

}

1 b

// Greatest of three numbers

#include <stdio.h>

#include<conio.h>

int main()

{

    int num1, num2, num3;

    clrscr();

    printf("Enter three numbers\t");

    scanf("%d%d%d",&num1,&num2,&num3);

    if(num1>num2)

        if(num1>num3)

            printf("%d is greatest",num1);

        else 

            printf("%d is greatest",num3);

    else 

         if(num2>num3)

            printf("%d is greatest",num2);

         else 

            printf("%d is greatest",num3);   

     getch();

    return 0;

}

1 c

// Average of  first N numbers

#include <stdio.h> 

#include<conio.h>

int main() 

   int n, i=0, s=0; 

   float avg; 

   clrscr();

   printf("Enter n\t"); 

   scanf("%d",&n); 

   addI: if(i>n) goto findAvg; 

   s=s+i; 

   i=i+1; 

   goto addI; 

   findAvg: avg= s / (float)n; 

   printf("Sum = %d, Average=%6.2f",s,avg); 

   return 0; 

1 d

// to check whether the given number is odd or even

#include <stdio.h>

#include<conio.h>

int main() 

{

    int num;

    clrscr();

    printf("Enter an integer: ");

    scanf("%d", &num);

    // true if num is divisible by 2

    if(num % 2 == 0)

        printf("%d is even.", num);

    else

        printf("%d is odd.", num);

    getch();

    return 0;

}

C Functions

We can divide a large program into the basic building blocks known as function​.

The function definition contains the set of programming statements enclosed by {}. ​

A function can be called multiple times to provide reusability and modularity to the C program. ​

The function is also known as procedure or subroutine in other programming languages.​

Advantages of C functions​

By using functions, we can avoid rewriting same logic/code again and again in a program.​

We can call C functions any number of times in a program and from any place in a program.​

We can track a large C program easily when it is divided into multiple functions (modules).​

Reusability is the main achievement of C functions.​

However, Function calling is always a overhead in a C program.​

Types of functions​

There are two types of functions in C programming:​

Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.​

User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.​

Function Aspects​

 

Different aspects of function calling

A function may or may not accept any argument.

It may or may not return any value. Based on these facts, There are four different aspects of function calls.

function without arguments and without return value

function without arguments and without return value

function with arguments and without return value

function without arguments and with return value

function with arguments and with return value


/* print hello C

    function without arguments and without return value     */

#include <stdio.h> 

void hello();  // function declaration 

void main() 

    hello(); // calling the function

}

//function definition

void hello()

{

     printf("hello c");

}

/* calculate the sum of two integers 

    function with arguments and without return value*/

#include <stdio.h> 

// Function declaration

void add(int a, int b); 

void main() 

int a, b; 

print f("\n Enter Any 2 Numbers: "); 

scanf("%d %d",&a,&b); 

// Calling the function

add(a,b); 

}


// Function defination

void add(int a , int b) 

int c;

c = a + b; 

printf("\n Addition is: %d",c);

OUTPUT:

Enter Any 2 Numbers: 23 6 

Addition is: 29

// C program to generate an random number between 0 to 99 using function

//function without arguments and with return value

#include <stdio.h>

#include <stdlib.h> // for rand() function


// Function declaration

int generateRandomNumber();


int main() {

    int randomNumber;

    // Calling the function

    randomNumber = generateRandomNumber();

    printf("Random Number: %d\n", randomNumber);

    return 0;

}

// Function definition

int generateRandomNumber()

{

    return rand() % 100; 

    /* Generates a random number     between 0 and 99 */

}

/* write a C program to find the area of a circle using function that uses a parameter and returns a value - example of function with arguments and with return value

#include<stdio.h>

#define PI 3.14

float getArea(float radius);

int main()

{

    float radius, area;

    printf("Enter the radius of Circle: ");

    scanf("%f", &radius);

    area = getArea(radius);

    printf("Area of Circle with %f radius is : %6.2f \n", radius, area);

     return 0;

}


float getArea(float radius)

{

    // area = pi * r^2

    return PI * radius * radius;

}


Recursion

Recursion is the process which comes into existence when a function calls a copy of itself to work on a similar problem. 

Any function which calls itself is called recursive function, and such function calls are called recursive calls. 

Recursion involves several numbers of recursive calls.

A recursive function performs the tasks by dividing it into the subtasks. 

There is a termination condition defined in the function which is satisfied by some specific subtask. 

After this, the recursion stops, and the final result is returned from the function. 

/* Program to demonstrate function recursion. */ 

#include<stdio.h> 

#include<stdlib.h> 

void recursion() 

int no; 

printf("\n\n Enter Number: "); 

scanf("%d",&no);

if (no==3) 

     exit(0); 

else 

    recursion(); 

}

void main() 

     recursion(); 

}


Call by value and Call by reference

There are two methods to pass the data into the function in C language:

call by value 

call by reference.


call by value

The value of the actual parameters is copied into the formal parameters. 

We can not modify the value of the actual parameter by the formal parameter.

Different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.

The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.


/* Program to demonstrate function call by passing a value.*/ 

#include <stdio.h> 

void modify(int a); /* function prototype */ 

void main() 

   int a = 2; 

   printf("\na = %d (from main, before calling the function ) " , a ) ; 

   modify(a); 

   printf("\na = %d (from main, after calling the function ) " , a ) ; 

}

void modify (int a) 

   a = a * 3; 

   printf("\n\na = %d (from the function, after being modified)", a ) ; 

}

call by reference

the address of the variable is passed into the function call as the actual parameter.

The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.

the memory allocation is the same for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.


/* Program to demonstrate function call by passing reference.*/ 

#include <stdio.h> 

void modify(int *a); /* function prototype */ 

void main ( ) 

int a = 2; 

printf ( " \na = %d (from main, before calling the function ) " , a ) ; 

modify(&a); 

printf ( " \na = %d (from main, after calling the function ) " , a ) ; 

}

void modify (int *a) 

*a = *a * 3; 

printf ( " \n\na = %d (from the function, after being modified)", *a ) ; 

}

Difference between call by value and call by reference

 

C Library Functions

Using stdio.h – scanf(), printf() functions

Using conio.h – clrscr(), getch()  functions

Using stdlib.h - rand() function

Using ctype.h

Using math.h

Using string.h

Using ctype.h

#include<stdio.h>

#include<ctype.h>

 int main()

{

    char ch;

    printf("Enter character to test : ");

    scanf(" %c", &ch);

 

    if(isalpha(ch)) 

        printf("%c is alphabet..\n",ch);

    else if(isdigit(ch))

        printf("%c is digit..\n",ch);

    else

        printf("%c is special symbol..\n",ch);

     return 0;

}

Using math.h

#include <stdio.h>

#include <math.h>


int main() {

    double x = 10.0;

    printf("square root of %f is %f. \n", x, sqrt(x));

    printf("squared value of %f is %f. \n", x, pow(x,2));

    printf("exp of %f is %f. \n", x, exp(x));

    return 0;

}

Storage Classes in C

In the C programming language, storage classes are used to define the scope, visibility, and lifetime of variables. 

There are four primary storage classes in C: 

auto, 

register, 

static, and 

extern. 

Each storage class serves a specific purpose and is used in different situations. 


auto: The auto storage class is the default for all local variables declared within a function. It is rarely used explicitly because local variables are automatically considered "auto" by default. 

Variables with the auto storage class have a local scope, which means they are only accessible within the block in which they are defined. They are also automatically destroyed when the control leaves the block.

Example:

void f() {

    auto int x; // 'auto' is optional, as it's the default for local variables

    // ...

}


register: The register storage class is used to suggest to the compiler that a particular variable should be stored in a CPU register for faster access. 

However, the use of register is generally obsolete in modern C programming. 

Like auto variables, register variables also have local scope and lifetime.

example

void f() {

    register int x; // Suggests the compiler to store 'x' in a register

    // ...

}



static: The static storage class is used for variables that need to retain their values across function calls. 

Static variables are initialized only once, and their values persist throughout the program's execution. 


#include <stdio.h>  

int func();

int main()  

{  

 printf("%d",func());  

 printf("\n%d",func());  

 printf("\n%d",func());  

 return 0;  

}  

int func()  

{   

    static int count=0; // variable initialization  

    count++; // incrementing counter variable  

    return count; 


extern: The extern storage class is used to declare a variable that is defined in another file. 

It tells the compiler that the variable is defined elsewhere, allowing multiple source files to share the same variable. 

extern variables are typically used in header files to provide a declaration for a variable defined in a separate source file.

// header.h 

extern int sharedVar; // Declaration of a variable defined in another file

// source.c

int sharedVar = 42; // Definition of the variable

Pre-processor Statements

Some common preprocessor statements in C:

include directive

#include <stdio.h> // Includes the standard I/O library header

define directive

#define PI 3.14159265359

Conditional Compilation Directives (#ifdef, #ifndef, #else, #elif, #endif):

#ifdef DEBUG

// Debugging code here

#else

// Release code here

#endif


Pragma Directive (#pragma): Pragma directives used to suppress specific compiler warnings.

#pragma warning(disable : 1234) // Disable warning 1234

Error Directive (#error): The #error directive is used to generate a compilation error message with a custom message.

#ifdef OLD_VERSION

#error "This code is not compatible with the old version."

#endif










References:

 

Programming with C by Byron Gottfried, Tata McGRAW-Hill , 2nd Edition

Programming Logic and Design by Joyce Farell , Cengage Learning , 8th edition

“C” Programming” by Brian W. Kernighan and Denis M. Ritchie, PHI ,2nd edition           

Let us C  by Yashwant P. Kanetkar , BPB publication         

C for beginners  by Madhusudan Mothe , X-Team Series , 1st edition

21st Century C by Ben Klemens , OReilly , 1st edition

https://www.computerhope.com/jargon/num/1gl.htm

 


Comments