0% found this document useful (0 votes)
48 views

Programming With C-1

MAC - SEM 1 - KSOU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Programming With C-1

MAC - SEM 1 - KSOU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

PROGRAMMING WITH C

5 marks questions

1. Briefly discuss machine language.


Machine Language:Machine language is a collection of binary digits (bits) that the computer reads and interprets. Machine language is
the only language that computers understand. It is the lowest. level and named as first generation of programming language. It is a language
that supports the machine side of programming but difficult for human beings to write and remember the bits. pattern. It consists of
(binary) zeros and ones. Each instruction in a program is represented by a numeric code, and numerical addresses are used throughout the
program to refer to memory. locations in the computer’s memory.
Eg; 101100111 is considered as a machine language instruction.
Advantages of machine level language:
Machine level languages are directly interacting with computer system.
There is no requirement for language translators.
It takes very less time to execute a program, because there is no conversion take place.
Disadvantages of machine language:
Its machine dependent language i.e. individual program required for each machine.
To develop a program in machine language, it’s too hard to understand and program.
It’s time consuming to develop new programs.
Debugging process is very hard because of finding errors process is typical.
Machine language is not portable language.
2. Write the advantages of C programming.
Procedural Language: C follows a procedural programming paradigm, which means it is organized around functions or procedures that
manipulate data. It doesn't support. object-oriented features like classes and inheritance, unlike languages such as C++ or Java.
2. Portability: C programs can be written once and run on multiple platforms with minimal
modifications, making it highly portable. This portability was crucial for the development of UNIX and other cross-platform software.
3. Efficiency and Performance: C allows direct memory manipulation through pointers, which gives developers fine-grained control
over memory usage and performance? optimizations. This efficiency makes it a popular choice for systems programming, embedded
systems, and resource-constrained environments.
4. Static Typing: C is statically typed, which means variable types need to be explicitly declared during the compilation phase. This
feature helps catch type-related errors at compile time, leading to more robust code.
5. Rich Standard Library: C comes with a standard library that provides essential functions for tasks like input/output operations, string
manipulation, memory allocation, mathematical computations, and more. It makes C programs more concise and efficient.
6. Pointers: C is known for its powerful pointer arithmetic, allowing developers to work directly with memory addresses and data
structures. While powerful, pointers can also be a source of bugs and require careful management.
7. Modularity and Reusability: C supports modularity through functions and user-defined data types, promoting code reusability and
maintainability.
8. Widespread Adoption: Due to its historical significance, efficiency, and portability, C has been used in various domains, such as
operating systems, embedded systems, game development, system-level programming, and more.

Although C has stood the test of time and remains relevant, it is not without its challenges. Being a low-level language, C exposes
developers to potential pitfalls, such as buffer overflows and undefined behavior, which require careful coding practices and testing.
Despite these challenges, C continues to be a vital language in the software industry, and many modern languages and frameworks have
been influenced by its design principles and syntax. Learning C provides a solid foundation for understanding programming concepts and
working closer to the hardware.
3. Explain goto statement.
A goto statement in C programming language provides an unconditional jump from the goto to a labeled statement in the same
function.goto.
Syntax:
goto label.
label: statement.
The label can be any plain text except C keyword and also it can be set anywhere in the C
program above or below to goto statement

Statement 1
Label 1

Statement 2 Go to
Label 2 Lable 3

LAL

Statement 3 L
Lable 3
la

laato
Shows Flowchart of go to statement. ttttto t
Example:
#include <stdio.h>
int main ()
{
int x = 10;
LOOP: do
{
if( x == 15)
{
x = x + 1;
goto LOOP;
}
printf("value of x: %d\n", x);
x++;
}while( x < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of x: 10
value of x: 11
value of x: 12
value of x: 13
value of x: 14
value of x: 16
value of x: 17
value of x: 18
value of x: 19

4. Discuss briefly pointer declaration.


In c a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has
an address that can be used to access that location so a pointer variable point to a memory location we can access and change the
contents of this memory location via the pointer.
A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. We start by specifying the
type of data stored in the location identified by the pointer. The asterisk tells the compiler that we are creating a pointer variable. Finally,
we give the name of the variable.
type * variable name.
Example:
int *ptr;
float *string.
5. Discuss structure in C.
C language is a very popular language among all the languages. The structure of a C program is a protocol (rules) to the programmer,
while writing a C program. The general basic structure of the C program is shown in the figure below. The whole program is controlled
within main ( ) along with left brace denoted by “{” and right braces denoted by “}”. If you need to declare local variables and executable
program structures are enclosed within “{” and “}” is called the body of the main function. The main ( ) function can be preceded by
documentation, preprocessor statements and global declarations.
Documentations
The documentation section consist of a set of comment lines giving the name of the program,
another name and other details, which the programmer would like to use later.
Preprocessor Statements
The preprocessor statements begin with # symbol and are also called the preprocessor directive.
These statements instruct the compiler to include C preprocessors such as header files and
symbolic constants before compiling the C program. Some of the preprocessor statements are
listed below.
# include <stdio.h>
# include <math.h> Heaader files
# include <stdlib.h>
# include <CONIO.h>

# define P L 3.1412.
# define TRVE 1 Symbolic Constants
# define FALSE φ
Global Declarations
The variables are declared before the main ( ) function as well as user defined functions are called global variables. These global variables
can be accessed by all the user defined functions including main ( ) function.
The main ( ) function
Each and Every C program should contain only one main ( ). The C program execution starts with main ( ) function. No C program is
executed without the main function. The main ( ) function should be written in small (lowercase) letters and it should not be terminated
by semicolon. Main ( ) executes user defined program statements, library functions and user defined functions and all these statements
should be enclosed within left and right braces.
Braces
Every C program should have a pair of curly braces ({, }). The left braces indicates the beginning of the main ( ) function and the right
braces indicates the end of the main ( ) function.
These braces can also be used to indicate the user-defined functions beginning and ending. These two braces can also be used in compound
statements.
Local Declarations
The variable declaration is a part of C program and all the variables are used in main ( ) function
should be declared in the local declaration section is called local variables. Not only variables,
we can also declare arrays, functions, pointers etc. These variables can also be initialized with
basic data types.
197
For Example
Main ( )
{
int sum = 0;
int x;
float y;
}
Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int and float and these
variables inside any function are called local variables.
Program statements.
These statements are building blocks of a program. They represent instructions to the computer to perform a specific task (operations).
An instruction may contain an input-output statements, arithmetic statements, control statements, simple assignment statements and any
other statements and it also includes comments that are enclosed within /* and */. The comment statements are not compiled and executed,
and each executable statement should be terminated with semicolon.
User defined functions
These are subprograms, generally, a subprogram is a function, and these functions are written by the user are called user, defined functions.
These functions are performed by user specific tasks, and this also contains set of program statements. They may be written before or
after a main () function and called within main () function. This is an option for programmers.

6. Explain arrays in C.
We belong to an era where it is impossible to long for a progressive world without Information Technology. And when
we talk about Information Technology, Computer Programming readily comes into our mind. An Array is one of the
essential facets of programming languages and software development. This is because an array is of great utility in
maintaining extensive datasets, sorting, and identifying variables.In its simplest terms, an array can be defined as a
formation of digits, images, or objects arranged in rows and columns in accordance with their types. Comprehending
the concept of array facilitates your tedious work and allows you to make it concise as arrays illustrate numerous data
elements of similar type using a sole name
In Computer Programming, an array assembles equivalent data elements stored at adjacent memory locations. This
easiest data structure helps to determine the location of each piece of data by simply using an offset to the base value.
An offset is a number that illustrates the distinction between two index numbers for instance, if you want to keep a
record of the marks obtained by a student in 6 subjects, then you don’t need to determine the variables individually.
Rather, you can determine an array that will store each piece of data factors at a contiguous memory location. Arrays
are one of the oldest and most essential data structures used in almost every program. Arrays are also useful in
implementing other data structures such as lists, heaps, hash tables,deques, queues, stacks, and strings.
In C, arrays have a strong relationship to pointers.Consider the following declaration.
int arr[ 10 ] ;
You might think from the above statement that arr is of type int. However, arr, by itself, without any index subscripting,
can be assigned to an integer pointer.Do you know, however, that arr[ i ] is defined using pointer arithmetic?
In particular:
arr[ i ] == * ( arr + i )
Let's take a closer look at arr + i. What does that mean? arr is a pointer to arr[ 0 ]. In fact, it is
defined to be & arr[ 0 ].
A pointer is an address in memory. arr contains an address in memory---the address.
where arr[ 0 ] is located.
What is arr + i? If arr is a pointer to arr[ 0 ] then arr + i is a pointer to arr[ i ].
Perhaps this is easier shown in a diagram.
We assume that each int takes up 4 bytes.
7. Briefly discuss assembly language.
Assembly language is easier to use than machine language. It is a middle level and named as second generation
programming language. An assembler is useful for detecting programming errors. Programmers do not have the
absolute address of data items. Assembly language encourage modular programming. It uses mnemonic codes instead
of bit patterns for instructions. The programs written are machine dependent. Here assemblers are used to translate
assembly language code to machine language.Example for assembly language program:
Move a,b
Add c
Store b
Advantages of Assembly language:
It is easily understood by humans because it uses statements instead of binary digits.
To develop a program takes less time.
Debugging is easy.
Disadvantages of Assembly language:
It is a machine dependent language, hence the program designed for one machine is
not usable for another machine. Say the assembly code for microprocessor 8085 is
different from that of microprocessor 8086.
Programmers should learn the mnemonic codes of each machine.
8. Explain if-else statement.
If-Else statement:
The If-else statement is a two-way branching statement. It consists of two blocks of statements if block and else block enclosed inside the
If-else statement. If the condition inside statement is true, statements inside if block are executed, otherwise statements inside the else
block are executed. Else block is optional, and it may be absent in a program.

Start

Expression ----false---------------

True

Statements in if branch Statements in else branch

stop

Shows flowchart of If-else statement


Syntax:
if (condition)
243
{
True Statement.
}
Else
{
False Statement;
}
Example:
#include<stdio.h>
#include<conio.h>
int main ()
{
int x;
printf (“enter a number:”);
scanf (“%d”, &x);
If (x<40)
{
printf (“the value is less than 40”);
}
Else
{
printf(“the value is greater than 40”);
}
Return 0;
}
Output: enter a number:12
The value is less than 20

9. Explain & and * operators.


10. Discuss accessing members of a function.
There are two types of operators used for accessing members of a structure.
Member operator(.)
Structure pointer operator(->) (will be discussed in respective chapter of structure and pointers)
Any member of a structure can be accessed as: structure_variable_name.member_nameSuppose, if we want to access salary for variable
p2. Then, it can be accessed as: p2.salaryConsider following Example of structure
#include <stdio.h>
struct Distance{
int feet;
float inch;
}d1,d2,sum;
int main(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet); //input of feet structure for d1
printf("Enter inch: ");
scanf("%f",&d1.inch); //input of inch structure for d1
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet); //input of feet for structure variable d2
printf("Enter inch: ");
scanf("%f",&d2.inch); //input of inch for structure variable d2
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if (sum.inch>12){ //If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch=sum.inch-12;
}
printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); //printing sum of distance d1 and d2
return 0;
}
Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the
information about person about his/her name, citizenship number and salary. You can create this information separately but, better
approach will be collection of these information under single name because all these information are related to person.
Keyword typedef while using structure
Programmers generally use typedef while using structure in C language.
For example:
typedef struct complex {
int imag;
float real;
}comp;
comp c1,c2;
Here, typedef keyword is used in creating a type comp (which is same type as struct complex). Then, two structure variables c1 and c2
are created by this comp type.
11. Discuss linked list.

12. Briefly discuss high level language.


High level language:
High level language is a language that supports the human and the application sides of the programming. It is known as third generation
programming language. Here the instructions are English like statements. Unlike assembly language, which is a machine dependent
language, High level language programs are machine independent. A line in a high-level language can execute powerful operations and
corresponds to tens, or hundreds, of instructions at the machine level. Examples of high-level languages are BASIC, FORTRAN, C,
COBOL, PASCAL, C ++, JAVA.

Advantages of high-level language:


Its logic and structure are much easier to understand.
Debugging is easier compared to other languages.
Less time consuming to writing new programs.
HLL are described as being a portable language.
Disadvantages of high-level language:
HLL programming language take more space compare to other MLL (machine level
language) and/or ALL (Assembly level language).
This programming language execute slowly.
Example:
#include<stdio.h>
Int a;
Scanf(“%d”, &a);
13. Explain while loop.
While loop
Syntax:
while(condition)
{
Statement 1;
Statement 2;
The test condition can be any expression. when we wish to do something a fixed number of times but not knowing about the number of
iteration, in a program then whileloop will be used.Initialy first condition is checked and if it is true then body of the loop is executed else,
control will be come out of loop.
Example: -
/* write a program to print 5 times welcome to C” */#include<stdio.h>
void main ()
{
int p=1; While(p<=5)
{
printf(“Welcome to C\n”);P=p+1;
}
}
Output: Welcome to C
Welcome to C
Welcome to C
Welcome to C
Welcome to C
Welcome to C
So as long as the condition remains true statements within the body of while loop will get executed repeatedly.

14. Explain pointer arithmetic.


C has the speed and efficiency of assembly language combined with readability of assembly language. In other words, it's just a glorified
assembly language.It's perhaps too harsh a judgment of C, but certainly one of the reasons the language was invented was to write operating
systems. Writing such code requires the ability to access addresses in memory in an efficient manner. This is why pointers are such an
important part of the C language. They're also a big reason programmers have bugs.If you're going to master C, you need to understand
pointer arithmetic, and in particular, the relationship between arrays and pointers.
Arbitrary Pointer Casting
Because most ISAs use the same number of bits as integers, it's not so uncommon to cast integers as pointers.
Here's an example.
// Casting 32 bit int, 0x0000ffff, to a pointer
char * ptr = reinterpret_cast<char *>( 0x0000ffff ) ;
char * ptr2 = reinterpret_cast<char *>( 0x0000ffff ) ;
In general, this is one of the pitfalls of C. Arbitrary pointer casting allows you to point anywhere in memory.Unfortunately, this is not
good for safe programs. In a safe programming language (say, Java), the goal is to access objects from pointers only when there's an object
there. Furthermore, you want to call the correct operations based on the object's type.Arbitrary pointer casting allows you to access any
memory location and do anything you want at that location, regardless of whether you can access that memory location or whether
the data is valid at that memory location.
15. Discuss structure variable declaration.
When a structure is defined, it creates a user-defined type but, no storage is allocated. You can use structure variable using tag name in
any part of program. For example:
struct person.
{
char name[50];
int cit_no;
float salary;
};
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];
In the above cases, 2 variables p1, p2 and array p having 20 elements of type struct person are created.
16. Write the basic operations on a singly linked list.

10 Marks

17. Explain algorithm with example.


Algorithm is a finite sequence of instructions, each of which has a clear meaning and can beperformed with a finite amount of effort in a
finite length of time. No matter what the input values may be, an algorithm terminates after executing a finite number of instructions. We
represent an algorithm using a pseudo language that is a combination of the constructs of a programming language together with informal
English statements. The ordered set of instructions required to solve a problem is known as an algorithm. The characteristics of a good
algorithm are:
Precision – the steps are precisely stated (defined).
Uniqueness – results of each step are uniquely defined and only depend on the input and the result of the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.
Example Q. Write an algorithm to find out whether the given number is odd or even.
Ans.
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0 then print "number even" else print "number odd" endif
step 5:stop
FLOWCHART
Flowchart is a pictorial representation of logic of the program. Flowchart is very helpful in writing program and explaining program to
others. It uses several standard symbols in the diagram.Symbols Used In Flowchart Different symbols are used for different statements in
flowchart, For example: Input/output and decision making has different symbols. The table below describes all the symbols that are used
in making flowchart

18. Write a short note on data types in C.


The area of the program where that variable is valid, the amount of time that a variable is retained, as well as where it can be accessed
from, depends on its specified location and type. The life span of the variable, i.e. the length of time that the variable remains in memory.
The programmer has to be very much aware of the type of the variable he/she going to use. Each and every sort of scenario requires
different type of scope. For example suppose the variable which should remain constant and also required by external functions then it is
not good practice to declare same variable again and again instead of that it may be called as a global variable On the other hand, for the
sake security reason some variable has be visible in only one function can be treated and declared as static variable.This section of the
unit will be discusses thoroughly in forth coming units when we introduce storage class and different types of variables.The basic data
structure used in C programs is a number. C provides for two types of numbers -integers and floating point. Computer operations that
involve text (characters, words or strings) still manipulate numbers. Each data item used by a program must have a data type. The basic
data types provided by C are shown in Table 1. Each data type represents a different kind of number. You must choose an appropriate
type for the kind of number you need in the variable declaration section of the program.
In c, there are three types of data-primary, derived and user-defined
In C language the system has to know before-hand, the type of numbers or characters being used in the program. These are called data
types. There are many data types in C language.
A C programmer has to use appropriate data type as per his requirement.C language data types can be broadly classified as
a) Primary data type-int, char, float, double
b) Derived data type(secondary)- array, function, pointer, structure, union
c) User-defined data type-typedef, enum
02
Primary Data types:
char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single precision.
double: It is used to store decimal numbers (numbers with floating point value) with double precision.Integer Data Type
Integers are numbers without decimal point
Integers are whole numbers with a range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767 (that is, -215 to +215-1).
The following table provides the details of standard integer types with their storage sizes and value ranges –

19. Describe library function.


Library functions are built-in functions that are grouped together and placed in a common location called library.Each function here
performs a specific operation. We can use this library functions to get the pre-defined output.All C standard library functions are declared
by using many header files. These library functions are created at the time of designing the compilers.We include the header files in our
C program by using #include<filename.h>. Whenever the program is run and executed, the related files are included in the C
program.Header File Functions Some of the header file functions are as follows −
stdio.h − It is a standard i/o header file in which Input/output functions are declared
conio.h − This is a console input/output header file.
string.h − All string related functions are in this header file.
stdlib.h − This file contains common functions which are used in the C programs.
math.h − All functions related to mathematics are in this header file.
time.h − This file contains time and clock related functions.Built functions in stdio.h
Advantages of Using C library functions
1. They work
One of the most important reasons you should use library functions is simply because they work. These functions have gone through
multiple rigorous testing and are easy to use.
2. The functions are optimized for performance
Since, the functions are "standard library" functions, a dedicated group of developers constantly make them better. In the process, they
are able to create the most efficient code optimized for maximum performance.
3. It saves considerable development time
Since the general functions like printing to a screen, calculating the square root, and many more are already written. You shouldn't worry
about creating them once again.
4. The functions are portable
With ever-changing real-world needs, your application is expected to work every time, everywhere. And, these library functions help you
in that they do the same thing on every computer.
Example: Square root using sqrt() function Suppose, you want to find the square root of a number.
To compute the square root of a number, you can use the sqrt() library function. The function is defined in the math.h header file.
#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
// Computes the square root of num and stores in root.
root = sqrt(num);
printf("Square root of %.2f = %.2f", num, root);
return 0;
}
When you run the program, the output will be:
Enter a number: 12
Square root of 12.00 = 3.46

20. Briefly explain writing strings to the screen.


To write strings to the terminal, we use a file stream known as stdout. The most common function to use for writing to stdout in C is the
printf function, defined as follows:Sample Code int printf(const char *format, ...);To print out a prompt for the user you can:Sample Code
printf("Please type a name: \n");
The above statement prints the prompt in the quotes and moves the cursor to the next line.If you wanted to print a string from a variable,
such as our fname string above you can do
this:
Sample Code
printf("First Name: %s", fname);
You can insert more than one variable, hence the "..." in the prototype for printf but this is sufficient. Use %s to insert a string and then
list the variables that go to each %s in your string you are printing. It goes in order of first to last. Let's use a first and last name printing
example to show this:
Sample Code
printf("Full Name: %s %s", fname, lname);
The first name would be displayed first and the last name would be after the space between
the %s's

21. With example explain printf() function.


The printf() function is the most used function in the C language.

This function is defined in the stdio.h header file and is used to show output on the console (standard output).Following is how the printf()
function is defined in the C stdio.h library.

int printf(const char )*format, ...);

Copy

It writes the C string pointed by the format pointer to the standard output (stdout).

On success, the total number of characters written is returned.

This function is used to print a simple text sentence or value of any variable which can be of int, char, float, or any other datatype.

printf() Code Examples

Let's start with a simple example.

1. Print a sentence

Let's print a simple sentence using the printf() function.


#include <stdio.h>

int main() {

// using printf()

printf("Welcome to Studytonight");

return 0;

Copy

Welcome to Studytonight

This one is a very common code example.

To understand the complete code and structure of a basic C language program, check Hello

22. Explain briefly flowchart.

23. Describe C identifiers.


• Identifiers are the names given to variables, classes, methods and interfaces.
• It must be a whole word and starts with either an alphabet or an underscore.
• They are case sensitive.
• No commas or blanks are allowed in it
• No special symbol other than an underscore can be used in it.
Ex.: marks gracesem1_rollno alpha
24. Explain general rules for graphical representation of data.
General Rules for Graphical Representation of Data
There are certain rules to effectively present the information in the graphical representation.
They are:
Suitable Title: Make sure that the appropriate title is given to the graph which indicates the subject of the presentation.
Measurement Unit: Mention the measurement unit in the graph.
Proper Scale: To represent the data in an accurate manner, choose a proper scale.
Index: Index the appropriate colours, shades, lines, design in the graphs for better understanding.
Data Sources: Include the source of information wherever it is necessary at the bottom of the graph.
Keep it Simple: Construct a graph in an easy way that everyone can understand.
Neat: Choose the correct size, fonts, colours etc in such a way that the graph should be a visual aid for the presentation of information.
Graphical Representation in Maths
In Mathematics, a graph is defined as a chart with statistical data, which are represented in the form of curves or lines drawn across the
coordinate point plotted on its surface. It helps to study the relationship between two variables where it helps to measure the change in
the variable amount with respect to another variable within a given interval of time. It helps to study the series distribution and frequency
distribution for a given problem. There are two types of graphs to visually depict the information. They are:
Time Series Graphs – Example: Line Graph
Frequency Distribution Graphs – Example: Frequency Polygon Graph
Principles of Graphical Representation
Algebraic principles are applied to all types of graphical representation of data. In graphs, it is represented using two lines called coordinate
axes. The horizontal axis is denoted as the x-axis and the vertical axis is denoted as the y-axis. The point at which two lines intersect is
called an origin ‘O’. Consider x-axis, the distance from the origin to the right side will take a positive value and the distance from the
origin to the left side will take a negative value. Similarly, for the y-axis, the points above the origin will take a positive value, and the
points below the origin will a negative value.
25. Explain reading strings from terminal.
Reading words from user
char name[20];
scanf("%s",name);
String variable, name can only take a word. It is because when white space is encountered,
the scanf() function terminates.
C program to illustrate how to read string from terminal.
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Here, program will ignore Ritchie because, when the scanf() function takes only string before the white space
Reading a line of text
C program to read line of text manually.
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n') //terminates if user hit enter
{
ch=getchar();
name[i]=ch;
i++;
}
name[i]='\0'; //inserting null character at end
printf("Name: %s",name);
return 0;
}
This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively.
#include<stdio.h>
int main(){
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Both, the above program has same output below:
Output
Enter name: Anil Ross
Name: Anil Ross
Passing Strings to Functions
String can be passed in similar manner as arrays as, string is also an array (of characters).
#include <stdio.h>
void Display(char ch[]);
int main(){
char c[50];
printf("Enter string: ");
gets(c);
Display(c); //Passing string c to function.
return 0;
}
void Display(char ch[]){
printf("String Output: ");
puts(ch);
}
Here, string c is passed from main() function to user-defined function Display(). In function declaration in line 10, ch[] is the formal
argument. It is not necessary to give the size of array in function declaration.

26. With example scanf() function in C.


When we want to take input from the user, we use the scanf() function and store the input value into a variable.
Following is how the scanf() function is defined in the C stdio.h library.
int scanf(const char *format, ...);
It reads data from stdin and stores it according to the parameter format into the locations pointed by the additional arguments.
On success, the function returns the number of items of the argument list successfully filled.
The scanf() function can be used to take input of any type from the user.
All you have to take care of is that the variable in which you store the value should have the same data type.
Here is the syntax for scanf():
scanf("%x", &variable);
where, %x is the format specifier.
Using the format specifier, we tell the compiler what type of data to expect from the user.
The & is the address operator which tells the compiler the address of the variable sothat the compiler can store the user input value at
that address.
scanf() Code Examples
Let's start with a simple example.
1. Input Integer value
If we have to take an integer value input from the user, we have to define an integer variable and then use the scanf() function.
#include <stdio.h>
int main() {
// using scanf()
int user_input;
printf("Please enter a number: ");
scanf("%d", &user_input);
printf("You entered: %d", user_input);
return 0;
}
Please enter a number: 7
You entered: 7
NOTE: If you use our compiler, then while running the code example above, there is a button for Input at the top-right corner of the editor,
you can click on it and provide custom value for input.
In the above code example, we have used %d format specifier to inform the scanf() function that user input will be of type int.
And we have also used & symbol before the name of the variable, because &user_input refers to the address of the user_input variable
where the input value will be stored.
2. Input Float valueJust like integer value, we can take input for any different datatype. Let's see an example of float type value.
#include <stdio.h>
int main() {
// using scanf()
float user_input;
printf("Please enter a decimal number: ");
scanf("%f", &user_input);
printf("You entered: %f", user_input);
return 0;
}
Output:
Please enter a decimal number: 7.007
You entered: 7.007
We have used the %f format specifier and defined a float type variable.
Try doing the same for taking a double type value as user input.
The format specifier for double is %lf.
Input Character value
Let's see how we can take a simple character input from the user.
#include <stdio.h>
int main() {
// using scanf()
char gender;
printf("Please enter your gender (M, F or O): ");
scanf("%c", &gender);
printf("Your gender: %c", gender);
return 0;
}
Copy
Please enter your gender (M, F or O): M
Your gender: M
4. Take Multiple Inputs from the User
In the below code example, we are taking multiple inputs from the user and saving them into
different variables.
#include <stdio.h>
int main() {
// using scanf() for multiple inputs
char gender;

int age;
printf("Enter your age and then gender(M, F or O): ");
scanf("%d %c", &age, &gender);
printf("You entered: %d and %c", age, gender);
return 0;
}
Output:
Enter your age and then gender(M, F or O): 32 M
You entered: 32 and M
Return Value of printf() & scanf()
The printf() function returns the number of characters printed by it,
and scanf() function returns the number of characters read by it.
int i = printf("studytonight");
printf("Value of i is: %d", i);
studytonightValue of i is: 12
In this program printf("studytonight"); will return 12 as a result, which will be stored in the variable i, because the word studytonight
has 12 characters.
The first printf() statement will print the statement studytonight on the output too.

27. Explain algorithm with example.


Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be performed with a finite amount of effort in a
finite length of time. No matter what the input values may be, an algorithm terminates after executing a finite number of instructions. We
represent an algorithm using a pseudo language that is a combination of the constructs of a programming language together with informal
English statements. The ordered set of instructions required to solve a problem is known as an algorithm. The characteristics of a good
algorithm are:
Precision – the steps are precisely stated (defined).
Uniqueness – results of each step are uniquely defined and only depend on the input and the result of the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.
Example Q. Write an algorithm to find out whether the given number is odd or even.
Ans.
step 1 : start
step 2 : input number
187
step 3 : rem=number mod 2
step 4 : if rem=0 then print "number even" else print "number odd" endif
step 5:stop
FLOWCHART
Flowchart is a pictorial representation of logic of the program. Flowchart is very helpful in writing program and explaining program to
others. It uses several standard symbols in the diagram.Symbols Used In FlowchartDifferent symbols are used for different statements in
flowchart, For example: Input/output and decision making has different symbols. The table below describes all the symbols that are used
in making flowchart.

28. Describe C tokens.


Every word in C language is a keyword or an identifier/variable. Keywords in C language cannot be used as a variable name. They are
specifically used by the compiler for its own purpose and they serve as building blocks of a c program. A C program consists of various
tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. C tokens are the basic buildings blocks in C
language which are constructed together to write a C program. Each and every smallest individual unit in a C program is known as C
tokens. C tokens are of six types. They are
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: ―total‖, ―hello‖),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)
For example, the following C statement consists of five tokens:
printf("Hello, World! \n");
199
The individual tokens are:
printf
(
"Hello, World! \n"
)
;
Semicolons ;
In C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the
end of one logical entity.
For example, following are two different statements:
printf("Hello, World! \n");
return 0;
Comments
Comments are like helping text in your C program and they are ignored by the compiler. They
start with /* and terminates with the characters */ as shown below:
/* my first program in C */
You cannot have comments within comments and they do not occur within a string or character literals.
29. Discuss principles of graphical representation.
Graphical Representation is a way of analysing numerical data. It exhibits the relation
between data, ideas, information and concepts in a diagram. It is easy to understand and it is
one of the most important learning strategies. It always depends on the type of information in
a particular domain. There are different types of graphical representation. Some of them are
as follows:
Line Graphs – Line graph or the linear graph is used to display the continuous data
and it is useful for predicting future events over time.
107

30. Elucidate declaration and initialization of strings.

15 Marks
1. Explain algorithm with example.
2. Discuss principles of graphical representation.
3. Elucidate declaration and initialization of strings.
4. With example explain getchar() and putchar() function.
5. Briefly explain compilation process.
6. Explain relational and logical operators
7. Discuss user-defined function in detail.
8. Describe Calloc() method.
9. Describe structured programming.
10. Explain bitwise operators and arithmetic operators.
11. Discuss user-defined function in detail.
12. Briefly explain malloc() method.

You might also like