0% found this document useful (0 votes)
27 views58 pages

Fundamentals of C

This document provides an overview of the C programming language, including its history, structure, basic syntax, data types, operators, control statements, and input/output functions. It explains key concepts such as keywords, identifiers, and the use of various operators, as well as control flow mechanisms like if statements, loops, and switch-case statements. Additionally, it includes example programs and questions for practice.

Uploaded by

crisnasoby9c
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views58 pages

Fundamentals of C

This document provides an overview of the C programming language, including its history, structure, basic syntax, data types, operators, control statements, and input/output functions. It explains key concepts such as keywords, identifiers, and the use of various operators, as well as control flow mechanisms like if statements, loops, and switch-case statements. Additionally, it includes example programs and questions for practice.

Uploaded by

crisnasoby9c
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Module 1

C Fundamentals

Badharudheen P
Assistant Professor,
Dept. of CSE, MESCE, Kuttippuram
What is C?

➢ C is a general purpose programming language


developed at AT & T’s Bell Labs of USA in 1972.
➢ It was designed and written by Dennis Ritchie.

➢ Much later the American National Standard Institute


(ANSI) published the C language as a standard (1988).
➢ The portability of C program has been greatly enhanced
by ANSI standard.
Structure of C Program

/* My first C Program */
#include <stdio.h>
void main()
{
printf("Hello World \n");
}
Structure of C Program

➢Line 1: #include <stdio.h>

 As part of compilation, the C compiler runs a program


called the C preprocessor. The preprocessor is able to add
and remove code from your source file.
 In this case, the directive #include tells the preprocessor to
include code from the file stdio.h
 This file contains declarations for functions that the
program needs to use. A declaration for the printf function
is in this file.
Structure of C Program
➢Line 2: void main()

 This statement declares the main function.


 C program can contain many functions but must always
have one main function.
 A function is a self-contained module of code that can
accomplish some task.

 The "void" specifies the return type of main. In this case,


nothing is returned to the operating system.
Structure of C Program

➢Line 3: {

 This opening bracket denotes the start of the program.


Structure of C Program

➢Line 4: printf("Hello World\n");

 printf is a function from a standard C library that is used to


print strings to the standard output, normally your screen.
 The compiler links code from these standard libraries to the
code you have written to produce the final executable.
 The "\n" is a special format modifier that tells the printf to
put a line feed at the end of the line.
 If there were another printf in this program, its string would
print on the next line.
Structure of C Program

➢Line 5: }

 This closing bracket denotes the end of the program.


Tokens in C
◼ Smallest unit used in C Program.
Keywords
◼ Keywords are those words whose meaning is already
defined by Compiler.
◼ There are 32 Keywords in C
◼ C Keywords are also called as Reserved words.

◼ We cannot Use Keywords for:


◼ Declaring Variable Name

◼ Function Name

◼ Declaring Constant Variable


Keywords
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 an entity to
identify it during the execution of the program.

◼ For example:
◼ int age, rollno;
◼ float salary;
Identifiers

◼ Rules for writing an identifier


◼ A valid identifier can have letters (both uppercase and
lowercase letters), digits and underscores.
◼ The first letter of an identifier should be either a letter or an
underscore.
◼ There is no rule on length of an identifier. However, the first
31 characters of identifiers are used by the compiler.
Identifiers
◼ int result

◼ float area

◼ int num2

◼ int 1mark Invalid: Identifier started with number

◼ float _age

◼ int salary_1

◼ int roll# Invalid: identifier contains special symbol


Data Types
➢Basically, there are 5 primary data types in C:
• char
• int
• float
• void
• enum

➢We can derive any number of data types from these five.
Questions

1. Write a program to find the average of three given


numbers.
2. Write a program to find the area and circumference of a
circle with given radius.
Operators and Expressions
➢Types of operators in C are:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional (Ternary) Operators
• Bitwise Operators
• Special Operators
Arithmetic Operators

➢Different arithmetic operators are: *, /, %, +, -


➢Integer mode arithmetic: s = 5 + 3;
➢Real mode arithmetic: p = 5.0 * 2.5;
➢Mixed mode arithmetic: m = 24 / 10.0;
Relational Operators

➢Different relational operators used in C are:


==, !=, <, >, <=, >=
➢For eg:
if(a <= 10)
{
}
Logical Operators

➢Different logical operators are: !, &&, ||


➢For eg:
if(a == 10 && b == 100)
{
}
Assignment Operators

➢Assignment operators: =, +=, -=, *=, /=


➢To assign value to a variable.
➢For example: x += 20;
Increment & Decrement Operators

➢++ operator increments the operand by 1 and –- operator


decrements the operand by 1.
➢For example:
int i = 10, j;
j = i++; /* i = 11, j = 10 */
i = 20;
j = --i; /* i = 19, j = 19 */
Increment & Decrement Operators
main()
{
int c;
c = 5;
printf(“%d\n”, c); 5
printf(“%d\n”, c++); 5
printf(“%d\n\n”, c); 6

c = 5;
printf(“%d\n”, c); 5
printf(“%d\n”, ++c); 6
printf(“%d\n”, c); 6

}
Conditional Operators

➢Otherwise called Ternary operator.


➢Shortest way of coding the if…..else statement.
➢Uses the combination of ? and :
➢Sysntax: (test-exp) ? True-exp : False-exp;
➢Eg: q = (j==0)?0:(i/j);
➢Here q will be 0 if j = 0, else q will be the value of i/j
Bitwise Operators

➢The different bitwise operators are:


• ~ : 1’s complement
• << : Shift left
• >> : Shift right
• & : Bitwise AND
• ^ : XOR
• | : Bitwise OR
Special Operators

➢Comma operator: (,) used in for statement


➢Eg: for(i=10, j=20; i<100; i++)
➢The sizeof operator: gives the size of the given operand in
bytes
➢Eg: sizeof(float); will return 4
➢Address operator: &
➢Pointer operator: *
➢Eg: int *x = &b;
Order of Precedence

 Operator Associativity

 () left to right
 * / % left to right
 + - left to right
 < <= > >= left to right
 == != left to right
 = left to right
Questions
1. Program to check whether a given number is odd or even
using ternary operator
Input & Output Functions
◼ Reading input data, processing it and displaying the
results are the three tasks of any program.

◼ There are two ways to accept the data.


◼ a data value is assigned to the variable with an assignment
statement.
int year = 2005; char l = ‘a’;
int x = 12345;
◼ accepting data with functions.
Input & Output Functions
◼ There are a number of I/O functions in C, based on the
data type.

◼ The input/output functions are classified in two types.


◼ Formatted functions
◼ Unformatted functions

◼ With the formatted functions, the input or output is


formatted as per our requirement.
Input & Output Functions
◼ All the I/O function are defined as stdio.h header file.
◼ Header file should be included in the program at the
beginning.

Formatted Functions Unformatted Functions


• It read and write all types of • Works only with character data
data values. type
• Require format string to • Do not require format
produce formatted result conversion for formatting data
type
Input & Output Functions

Input and Output Functions

Formatted Functions Unformatted Functions

printf()
scanf()
getchar() putchar()
gets() puts()
getc() putc()
The printf()Function
◼ This function sents the formatted output to the screen. The
syntax is:
printf(“format string”, var1, var2, … );

◼ The “format string” specifies the field format such as %d,


%s, %c, %f and, optionally, some text and control
character(s).
◼ Example:
float a = 10.5; int b = 20;
printf(“Value at a = %f and b = %d \n”, a, b);
The scanf()Function
◼ This function provides for formatted input from the
keyboard.
◼ It is used for runtime assignment of variables.
◼ The syntax is:
scanf(“%d %f %c”, &var1, &var2, &var3);

◼ scanf statement requires ‘&’ operator called address


operator to indicate the memory location of the variable.
◼ Example:
float a; int b;
scanf (“%f %d”, &a, &b);
Unformatted Functions
◼ getchar();
◼ This function is used for getting exactly one character from the
keyboard.
char ch;
ch = getchar();

◼ putchar(char);
◼ This function is used for printing exactly one character to the
screen.
char ch;
ch = getchar(); /* input a character from kbd*/
putchar(ch); /* display it on the screen */
Unformatted Functions
◼ getc(*file);
◼ This function is similar to getchar() except the input can be
from the keyboard or a file.
char ch;
ch = getc(stdin);/* input from keyboard */
ch = getc(fileptr);/* input from a file */

◼ putc(char, *file);
◼ Similar to putchar() except the o/p can be to the screen or a file.
ch = getc (stdin); /* input from keyboard */
putc(ch, stdout); /* output to the screen */
putc(ch, outfileptr); /*output to a file */
CONTROL STATEMENTS IN C
if Statement
❑ General syntax: ❑ Example

if(ctrl statement) if(a > b)


{ {
statement 1; printf(“a is largest”);
statement 2; }
...;
...;
}
if – else Statement
❑ General syntax: ❑ Example
if(ctrl statement) if(a > b)
{ {
statement 1; printf(“a is biggest”);
...; }
} else
else {
{ printf(“b is biggest”)
statement1; }
...;
}
Questions
1. Write a program to check whether a given number is odd
or even.
2. Write a program to find the biggest of three numbers.
3. A commercial bank has introduces an incentive policy of
giving bonus to all its deposit holders. The policy is as
follows: A bonus of 2% of the balance is given to
everyone, irrespective of their balances, and a 5% is given
to female account holders if their balance is more than
Rs.5000. Write a program to calculate the current balance
of the account holder.
while Statement
❑ General syntax: ❑ Example

initialize ctrl_var; int i = 1;


while(ctrl_stmt) while(i < 10)
{ {
statement 1; printf(“%d\n”, i);
statement 2; i++;
...; }
inc/dec ctrl_var;
}
do - while Statement
❑ General syntax: ❑ Example

initialize ctrl_var; int i = 12;


do do
{ {
statement 1; printf(“%d\n”, i);
statement 2 i++;
...; }while(i < 10);
inc/dec ctrl_var;
}while(ctrl_stmt);
Questions
1. Write a program to print the sum of first 10 numbers.
2. Write a program to find the value of x^n.
3. Write a program to find the sum of digits of a given
number.
4. WAP to print the multiplication table of a given number.
5. WAP to print the numbers between 100 and 200 which
are divisible by 6.
for Statement
❑ General format: ❑ Example

for(init;check;inc/dec) for(i=1; i<10; i++)


{ {
statement 1; printf(“%d\n”, i);
statement 2 }
...;
}
Questions
1. Write a program to print the sum of first 10 numbers.
2. Write a program to find the factorial of a number.
3. Write a program to print the Fibonacci numbers up to a given
limit.
4. WAP to print the numbers between 100 and 200 which are
divisible by 6.
5. WAP to print the pattern
+
+ +
+ + +
+ + + +
Additional features of for Statement
❑ Case 1: Multiple initialization is possible in for loop statement

The statement
p = 1;
for (n = 0; n < 50; n++)
{
}
can be rewritten as
for (p = 1, n = 0; n < 50; n++)
{
}
Additional features of for Statement
❑ Case 2: The test condition may have any compound relation and
the testing need not be limited only to the loop control variable.

for (i = 1; i < 20 || sum < 100; i++)


{
sum = sum + i;
printf(“%d %d\n”, i, sum);
}
Additional features of for Statement
❑ Case 3: It is permissible to use expressions in the assignment
statements of initialization and increments sections.

for (x = (m + n)/2; x > 0; x = x / 2)


{
}
Additional features of for Statement
❑ Case 4: One or more sections can be omitted, if necessary.

m = 5;
for ( ; m ! = 100; )
{
printf(“%d\n”,m);
m = m + 5;
}
switch-case-break Statements
❑ It is a multi-way decision making method.

❑ It tests a control expression, the control will be then transferred to


one of the several alternatives.

❑ The value of the expression may be of int or char but not of


type float or double.

❑ Generally used for menu driven options.


switch-case-break Statements
❑ Syntax: ❑ Example
switch(ctrl expression)
scanf(“%d”, &num);
{
switch(num)
case constant1:
{
statements;
case 1:
break;
printf(“input is 1”);
case constant2:
break;
statements;
case 2:
break;
printf(“input is 2”);
default:
break;
statements;
}
break;
}
switch-case-break Statements
❑ All case expressions must be different.
❑ The case labeled default is executed if none of the other cases
are satisfied.
❑ Here the same statements can be executed for two or more
different case constants.
❑ For example: switch(num)
{
case 1:
case 2:
case 3:
printf(“Hello……”);
break;
}
Questions
1. Write a program to check whether the input character is a
vowel or not.
2. Write a menu driven program to perform all arithmetic
operations.
3. Write a program to find the grade of a student based on the
total marks in 5 subjects(out of 500).
Grade A: 400 – 500
Grade B: 300 – 399
Grade C: 200 – 299
Grade D: 100 – 199
Failed: < 100
break Vs continue Statements
❑ Sometimes, when executing a loop it becomes desirable to skip a
part of the loop or to leave the loop as soon as a certain condition
occurs.

❑ The break statement is used to exit from a loop.


❑ The continue statement is used to transfer the control to the
beginning of the loop.
break Vs continue Statements
for (i = 1; i< = 10000; i++)
{
if (i <= 50)
{
printf(“Hi\n”);
continue;
printf(“%d\n”, i);
}
if (i == 51)
{
break; //exit from loop, not from if block
}
}
goto and Lablels
❑ The goto statement is used to transfer the control from one
statement to other statement in the program.

goto label;
Statement(s);
…………….
label: statement(s);

❑ The goto statement is classified into two types


❑ Unconditional goto

❑ Conditional goto
Unconditional goto Conditional goto
The control transfer from one block The control transfer from one block to
to another block without checking another by checking a test condition.
the test condition. void main()
{
Example: int a, b;
#include <stdio.h> printf (“Enter Two Values”);
scanf (“%d%d”, &a, &b);
void main() if (a > b)
{ goto output_1;
else
Start: goto output_2;
printf(“Welcome\n”); output_1:
printf (“A is Biggest”);
goto Start; goto Stop;
} output_2:
printf (“B is Biggest”);
goto Stop;
Stop:
}
Question

1. Write a program to check whether the given number is prime


or not.
2. Program to add numbers until user enters zero
3. Display prime numbers between two intervals
4. Program to check whether given number is palindrome or not

You might also like