Blog

Loops Programs

  1. WAP to read a number and print all numbers from 1 to that number
    input: enter a number: 5
    output:
    1
    2
    3
    4
    5
  2. WAP to read number and print all even numbers from 1 to that number
    input: enter a number: 5
    output:
    2
    4
  3. WAP to print all number from 1 to 10 by using while, for and do -while loop.
  4. WAP to read a number and find sum of all numbers from 1 to that number
    input: enter a number: 5
    output: 1 + 2 + 3 + 4 + 5 = 15
  5. WAP to read a number and find factorial of that number
    input: enter a number: 5
    output: 1 * 2 * 3 * 4 * 5 = 120
  6. WAP to read a number and find reverse of that number
    input: enter a number: 1234
    output: 4321
  7. WAP to read a number and check if it is a prime number or not
    input: enter a number: 5
    output: 5 is a prime number
  8. WAP to print all prime number in range from 1 to 100
    output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
  9. WAP to print first 10 fibonacci number
    output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
  10. WAP to read a number and find sum of its digits
    input: 12345
    output: 1 + 2 + 3 + 4 + 5 = 15
  11. WAP to find a 3 digit armstrong number
    output: 153
  12. WAP to print all armstrong numbers from 1 to 999
    output: 153, 370, 371, 407
  13. WAP to print ASCII chars and values from 1 to 255
  14. WAP to print alphabets from A to Z using loop
  15. WAP to read a number and count all numbers which divides the given number perfectly
  16. WAP to read 2 numbers and print their common factors
  17. WAP to read 2 numbers and print HCF
  18. WAP to print factorial of all numbers from 1 to 10
  19. WAP to read 2 numbers a and b and print all numbers from a to b
  20. WAP to repeatedly read a number until it is in range from 10 to 20
  21. WAP to read a number and print all numbers which divides the given number perfectly
  22. WAP to find sum of series
    S = 1 + 2 + 3 + …. + N
  23. WAP to find sum of series
    S = 1 + 2! + 3! + …. N!
  24. WAP to find sum of series
    S = 1 + 1/2 + 1/3 + 1/4 + 1/5 + …. + 1/N
  25. WAP to find sum of series
    S = 1 – 1/2 + 1/3 – 1/4 + 1/5 – …. 1/N
  26. WAP to read a number and print tables from 1 to that number
  27. WAP to print following output
    • 12345
      1234
      123
      12
      1
    • 54321
      4321
      321
      21
      1
    • *****
      ****
      ***
      **
      *
    • 1234554321
      1234554321
      1234554321
      1234554321
      1234554321
    • 12345123451234512345
      12345123451234512345
      12345123451234512345
    • ABCDE
      ABCD
      ABC
      AB
      A
    • ABCDEFEDCBA
      ABCDE EDCBA
      ABCD   DCBA
      ABC     CBA
      AB       BA
      A         A
    • *********
      *******
      *****
      ***
      *
  28. WAP to print table of number in following format using 1 for loop
    input: enter a number: 5
    5 * 1 = 5 5 * 10 = 50
    5 * 2 = 10 5 * 9 = 45
    5 * 3 = 15 5 * 8 = 40
    5 * 4 = 20 5 * 7 = 35
    5 * 5 = 25 5 * 6 = 30
    5 * 6 = 30 5 * 5 = 25
    5 * 7 = 35 5 * 4 = 20
    5 * 8 = 40 5 * 3 = 15
    5 * 9 = 45 5 * 2 = 10
    5 * 10 = 50 5 * 1 = 5

Programs on If Statement

  1. WAP to read a number and check if it is even or odd
    input:
    Enter a number: 5
    output: number 5 is odd
  2. WAP to read 2 numbers and check if their last digits are same or not
    input:
    Enter number 1: 55
    Enter number 2: 45
    output: Last digits of 55 and 45 are same
  3. WAP to read 3 angles and check if triangle can be formed or not
    input:
    Enter value for angle a: 50
    Enter value for angle b: 60
    Enter value for angle c: 70
    output: Triangle can be formed
  4. WAP to read 3 angles and check if it is and equilateral triangle or not
    input:
    Enter value for angle a: 60
    Enter value for angle b: 60
    Enter value for angle c: 60
    output: Triangle is equilateral triangle
  5. WAP to read marks for 5 subjects and check if student is passed or not
    input:
    Enter marks for maths: 50
    Enter marks for science: 50
    Enter marks for history: 50
    Enter marks for english: 50
    Enter marks for marathi: 50
    output:
    Total Marks: 250
    Percentage: 50%
    Student is passed
  6. WAP to read 2 numbers and find the greatest of them
    input:
    Enter number 1: 50
    Enter number 2: 60
    output:
    60 is greater than 50
  7. WAP to read 3 numbers and find the greatest of them
    input:
    Enter number 1: 50
    Enter number 2: 60
    Enter number 2: 70
    output:
    70 is greater than 50 and 60
  8. WAP to read 3 digit number and check if the sum of cube of its digits is equal to that number or not
    input:
    Enter a 3 digit number: 153
    output:
    Success: Sum of cube of 153 is 153
  9. WAP to read 3 numbers and check their last digit is same or not
    input:
    Enter number 1: 50
    Enter number 2: 60
    Enter number 3: 70
    output:
    Last digits of 50, 60 and 70 are same
  10. WAP to read a number and check if it is palindrome number or not
    input:
    Enter a number: 121
    output:
    121 is palindrome number
  11. WAP to read marks of 5 subjects and print their total. Also print percentage and check if student is passed or not
    input:
    Enter marks for maths: 50
    Enter marks for science: 50
    Enter marks for history: 50
    Enter marks for english: 50
    Enter marks for marathi: 50
    output:
    Total Marks: 250
    Percentage: 50%
    Student is passed
  12. WAP to read 3 angles and check if triangle can be formed or not. If triangle can be formed then check it it is equilateral, isosceles or right angled triangle
    input:
    Enter value for angle a: 45
    Enter value for angle b: 45
    Enter value for angle c: 90
    output:
    Triangle can be formed
    The triangle is right angled triangle
  13. WAP to read age and gender of person and check if person is Eligible for marriage or not
    input:
    Enter gender M or F: M
    Enter your age: 30
    output:
    30 ka ho gaya ab to shadi kar le
  14. WAP to read a year and check if it is Leap year or not
    input:
    Enter year: 2004
    output:
    Year 2004 is a leap year
  15. WAP to read a Salary of Employee and print commission according to following Criteria
    SAL               Commission
    <10000             10%
    10000-20000   12%
    >20000             15%
    input:
    Enter Salary: 10000
    output:
    Your commission is 1000 Rupees
  16. WAP to read percentage of student and print Division
    >=75 : 1st class with distinction
    60-75: 1st class
    50-60: 2nd class
    40-50: 3rd class
    <40: fail
    input:
    Enter marks for maths: 75
    Enter marks for science: 75
    Enter marks for history: 75
    Enter marks for english: 75
    Enter marks for marathi: 75
    output:
    Total Marks: 375
    Percentage: 75%
    Student passed with 1st class Distinction

Basic Programs

  1. WAP to read radius of circle and calculate Area and Circumference
    i/p:
    Enter radius: 5
    o/p:
    Area of circle is 31.5
    Circumference of circle is 78.5
  2. WAP to read 3 numbers and find their mean
    i/p:
    Enter number 1: 5
    Enter number 2: 6
    Enter number 3: 7
    o/p:
    Mean of 5, 6 and 7 is 6
  3. WAP to read 2 numbers and find Sum of their last digit
    i/p:
    Enter number 1: 52
    Enter number 2: 65
    o/p:
    2 + 5 = 7
  4. WAP to read 4 digit number and sum of its digits
    i/p: Enter a number: 1234
    o/p:
    1 + 2 + 3 + 4 = 10
  5. WAP to read radius of Sphere and find its Volume
    i/p:
    Enter radius: 5
    o/p:
    Volume of sphere having radius 5 is 523.6
  6. WAP to read 3 digit number and sum of its digit
    i/p:
    Enter a number: 123
    o/p:
    1 + 2 + 3 = 6
  7. WAP to read 4 digit number and find reverse of that number
    i/p:
    Enter a number: 1234
    o/p:
    Reverse of 1234 is 4321
  8. WAP to read temperature in degree Celsius and convert it into Fahrenheit
    i/p:
    Enter temperature in Celsius: 38
    o/p:
    Temperature in Fahrenheit is 100.4
  9. WAP to read value in inches and print it in feet and inches
    i/p:
    Enter length in inches: 20
    o/p:
    20 inches is equal to 1 foot and 8 inches
  10. WAP to read marks of 5 subjects and print total and percentage
    i/p:
    Enter marks for maths: 50
    Enter marks for science: 50
    Enter marks for history: 50
    Enter marks for english: 50
    Enter marks for marathi: 50
    o/p:
    Total Marks: 250
    Percentage: 50%
  11. WAP to read 2 numbers and exchange their values using third variable
    i/p:
    Enter value for x: 5
    Enter value for y: 6
    o/p:
    After swapping value of x is 6 and value of y is 5
  12. WAP to read 2 numbers and exchange their values without using third variable
    i/p:
    Enter value for x: 5
    Enter value for y: 6
    o/p:
    After swapping value of x is 6 and value of y is 5
  13. WAP to read Lenght, Breadth and Height and find its volume and surface area
    i/p:
    Enter length: 5
    Enter breadth: 6
    Enter height: 7
    o/p:
    Volume of box is 210
    Surface are of box is 214

Escape Sequences and Formatted I/O Functions

Escape sequences

The following escape sequences allow special characters to be put into the source code.

Escape
Sequence
Name Meaning
\a Alert Produces an audible or visible alert.
\b Backspace Moves the cursor back one position (non-destructive).
\f Form Feed Moves the cursor to the first position of the next page.
\n New Line Moves the cursor to the first position of the next line.
\r Carriage Return Moves the cursor to the first position of the current line.
\t Horizontal Tab Moves the cursor to the next horizontal tabular position.
\v Vertial Tab Moves the cursor to the next vertical tabular position.
\’ Produces a single quote.
\” Produces a double quote.
\? Produces a question mark.
\\ Produces a single backslash.
\0 Produces a null character.
\ddd Defines one character by the octal digits (base-8 number)
\xdd Defines one character by the hexadecimal digit.

Examples:

p rintf(“\12”); – Produces the decimal character 10 (x0A Hex).

printf(“\xFF”); – Produces the decimal character – 1 or 255

printf(“\x123”); – Produces a single character

 

Formatted I/O Functions

printf Functions

int printf(const char * format,…);

int sprint(char *str, const char * format, …);

The printf functions provide a means to output formatted information to a stream.

printf sends formatted output to stdout

sprintf sends formatted output to a string

These functions take the format string specified by the format argument and apply each following argument to the format specifiers in the string in a left to right fashion. Each character in the format string is copied to the stream except for conversion characters which specify a format specifier.

 

A conversion specifier begins with the % character. After the % character come the following in this order:

[flags]                   Control the conversion (optional).

[width]                 Defines the number of characters to print (optional).

[.precision]        Defines the amount of precision to print for a number type (optional).

[modifier]           Overrides the size (type) of the argument (optional).

[type]                   The type of conversion to be applied (required).

 

Width:

The width of the field is specified here with a decimal value. If the value is not large enough to fill the width, then the rest of the field is padded with spaces. If the value overflows the width of the field, then the field is expanded to fit the value.

 

Precision:

The precision begins with a dob (.) to distinguish itself from the width specifier. The precision can be given as a decimal value or as an asterisk (*). If a * is used, then the next argument (which is an int type) specifies the precision.

 

scanf Functions

Declarations:

int scanf(const char * format, …);

int sscanf(const char * str, const char * format, …);

The scanf functions provide a means to input formatted information from a stream.

scanf reads formatted input from stdin

sscanf reads formatted input from a string

These functions take input in a manner that is specified by the format argument and store each input field into the following arguments in a left to right fashion. Each input field is specified in the format string with a conversion specifier which specifies how the input is to be stored in appropriate variable.

Char I/O

getchar : getchar reads a single character from standard input.

Syntax :                int getchar();

It requires the user to press enter after entering character.

Putchar : putchar writes a single character to standard output.

Syntax:                 int putchar(int value)

 

Variables, Datatypes and Elements in C

Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. It is defined by the following syntax.

Storage-class-specifier <space> type-specifier <space> variable-name,…

The Storage-class-specifier can be one of the following:

typedef The symbol name “variable-name” becomes a type-specifier of type “type-specifier”.
No variable is actually created, this is merely for convenience.
Extern Inticates that the variable is defined outside of the current file.
This brings the variables scope into the current scope. No variable is actually created by this.
Static Causes a variable that is defined within a function to be preserved in subsequent calls to the function.
Auto Causes a local variable to have a local lifetime (default).
register Request that the variable be accessed as quickly as possible. This request is not guaranteed.
Normally, the variable’s value is kept within a CPU register for maximum speed.

e.g. int I,j,k;

float x,y,z;

char ch;

 

Constants

ANSI C allows you to declare constants. When you declare a constants it is a bit like a variable declaration except the value cannot be changed.

 

The const keyword is to declare a constant, as shows below:

int const a = 1;

const int a = 2;

Note:

  • You can declare the const before or after the type.
  • It is usual to initialize a const with a value as it cannot get a value any other way.

The preprocessor #define is another more flexible method to define constants in a program.

 

Datatypes

Datatypes Details Format Specifier & Size Range
char, signed char Variable is large enough to store a basic character in character set.
May be either signed or nonnegative
%c 8 bits -128 to 127
unsigned char Same as char, but unsigned only %c 8 bits  0 to 255
short, signed short, short int, signed short int Defines a short signed int. %d 8 bits or 16 bits  -128 to 127

Or

-32,768 to 32,767

unsigned short, unsigned short int Defines an unsigned short integer. %d 8 bits or 16 bits  0 to 255 or

0 to 65,535

int, signed int Defines a signed integer %d 16 bits  -32,768 to 32,767
unsigned int Same as int, but unsigned values only. %u 16 bits  0 to 65,535
long, signed long, long int, signed long int Defines a long signed integer. %ld 32 bits  -2.147,483,648 to 2,147,483,647
unsigned long, unsigned long int Same as long, but unsigned values only. %lu 32 bits  0 to 4,294,967,295
Float A floating-point number. %f 32 bits  1.17549435 * (10^-38) to 3.40282347*(10^+38)
Double A more accurate floating-point number than float. %lf 64 bits  2.2250738585072014 *(10^-308 to 1.7976931348623157 * (10^+308)
long double Increase the size of double. %Lf 80 bits  3.4 * (10^-4932) to 1.1 * (10^4932)

 

Note: Size of datatype depends on different implementation of c by different compilers.

 

C Elements

Tokens

                In a C source program, the basic element recognized by the compiler is the “token”.

A token is source-program text that the compiler does not break down into component elements.

Tokens can be keyword, identifier, constant, string-literal, operator, punctuator.

Identifiers

“Identifiers” or  “symbols” are the names you supply for variables, types, functions and labels in your program.
Identifier names must differ in spelling and case from any keywords.

  • Must start with alphabet (a..z A…Z) or underscore(_).
  • Next letter can be alphabet (a…z A…Z), underscore(_) or digit.
  • You cannot use keywords as identifiers.

Literals

Invariant program elements are called “literals” or “constants”. The terms “literal” and “constant” are used interchangeably here. Literals fall into four major categories:

  • integer
  • character
  • floating-point
  • string literals

A “string literal” is a sequence of characters from the source character set enclosed in double quotation marks (“ “). String literals are also used to represent a sequence of characters which, taken together, from a null-terminated string. The characters of a literal string are stored in order at continuous memory locations. A null character (represented by the \0 escape sequence) is automatically appended to and marks the end of each string literal.

e.g.

  • 157 // integer constant
  • 0xFE // integer constant
  • ‘c’ // character constant
  • 2 // floating constant
  • 2E-01 // floating constant
  • “dog” string literal

Constants

                 A “constant” is a number, character or character string that can be used as a value in a program. Use constants to represent floating-point, integer, enumeration or character values that cannot be modified.

Keywords

                “Keywords” are words that have special meaning to the C compiler.

An identifier cannot have the same spelling and case as a C keyword.

The C language uses following keywords:

 

auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

 

Comments

Comments in the source code are ignored by the compiler. They are encapsulated starting with /* and ending with */. According to ANSI standard, nested comments are not allowed, although some implementations allow it.

Single line comments are becoming more common, although not defined in the ANSI standard. Single line comments begin with // and are automatically terminated at the end of the current line.

Punctuation and Special Characters

                The punctuation and special characters in the C character set have various uses, from organizing program text to defining the tasks that the compiler or the compiled program carries out. They do not specify an operation to be performed. Some punctuation symbols are also operators. The compiler determines their use from context.

Punctuator: one of [ ] ( ) { } * , : = ; … #

Introduction to C Programming Language

Prerequisites

  • Basics of Computer and Operating System
  • Mathematics
  • Binary Numbers and Decimal Numbers
  • Programs, Software, Internet, etc.

History of C

 

The development of Unix in the C language make it uniquely portable and improvable.

 

The first version of Unix was written in the low-level PDP-7 assembler language. Soon after, a language TMG was developed for the PDP-7 by R. M. McClure. Using TMG to develop a FORTRAN compiler, Ken Thompson instead ended up developing a compiler for a new high-level language he called B, based on the earlier BCPL language developed by Martin Richard. Where it might take several pages of detailed PDP-7 assembly code to accomplish a given task, the same functionality could typically be expressed in a higher level language like B in just a few lines. B was thereafter used for further development of the Unix system, which made the work much faster and more convenient.

When the PDP-11 computer arrived at Bell Labs, Dennis Ritchie built on B to create a new language called C which had a powerful mix of high-level functionality and the detailed features required to program an operating system. Most of the components of Unix were eventually rewritten in C in 1973. Because of its convenience and power, C went on to become the most popular programming language in the world over the next quarter century.

 

Introduction to C

C Basics

C is a middle level language where we can perform high level operation as well as low level operations.

 

Characteristics of C

We briefly list some of C’s characteristics that define the language and also have leads to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course.

  • Small size
  • Extensive use of function calls
  • Structured language
  • Low level (BitWise) programming readily available
  • Pointer implementation – extensive use of pointers for memory, array, structures and function.

C has now become a widely used professional language for various reasons.

  • It has high-level constructs.
  • It can handle low-level activities.
  • It produces efficient programs.
  • It can be compiled on a variety of computers.

Its main drawback is that it has poor error detection which can make it off putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of C we can break them. Not many languages allow this. This if done properly and carefully leads to the power of C programming.

 

The standard for C programs was originally the features set by Brian Kernighan. In order to make the language more internationally acceptable, an international standard was developed, ANSI C (American National Standards Institute).

 

C Program Structure

 

Preprocessor commands

Global declaration

int main() {

Statements

——-

——

}

  • Preprocessor Commands:

These are the instruction which we want to give to our compiler (Its preprocessor).
They indicate how the program is to be compiled.
A preprocessor commands Starts with the symbol #.
e.g. #include, #define, #ifdef

  • Global declaration:

In this section we can define variables, functions; structures etc.
Variables define in this section are accessible anywhere within the program.

  • Function main():

This is the entry point of our program.
Execution of the program begins with function main().

So a C program must contain at least one function i.e. main.

 

Sample C Program

 

#include <stdio.h>

int main() {

printf(“Hello World \n”);

exit(0);

}

 

NOTE:

  • C required a semicolon at the end of every statement.
  • printf() is a standard C function — called from main.
  • \n signifies new line. Formatted output – more later
  • exit() is also a standard function that causes the program to terminate. Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway.