C-Unit 1 Answer
C-Unit 1 Answer
NO Q&A
PART- A
1 Father of c language is ___________.
a. Steve Jobs
b. James Gosling
c. Dennis Ritchie
d. Rasmus Lerdorf
2 __________many bits make a byte?
a) 2 bits
b) 4 bits
c) 8 bits
d) 12 bits
3 C was developed at:
a. Bell Labs
b. Microsoft
c. IBM
d. Apple
4 C is__________
a. A high-level programming language
b. A low-level programming language
c. A markup language
d. A scripting language
5 The purpose of the 'main' function in a C program
a. To declare variables
b. To include header files .
c. To define constants
d. To serve as the program's entry point
6 _________is the correct way to include a standard library header file in C
a. #include <library.h>
b. #include "library.h"
c. #include (library.h)
d. #import "library.h"
7 An interpreter for C code, how is the code executed?
a. It is first compiled and then executed
b. It is executed directly line by line
c. It is executed in a separate virtual machine.
d. It is executed after converting it to assembly code
8 __________preprocessor directive is used to include a standard C library header file?
a. #import
b. #include <stdio.h>
c. #include "stdio.h"
d. #define
9 Syntax for a single-line comment in C.
a. /* This is a comment */
b. ' This is a comment
c. // This is a comment
d. # This is a comment
10 The primary role of a compiler in C programming.
a. To execute C programs
b. To convert C source code into machine code or assembly language
c. To debug C programs
d. To interpret C code line by line
11 In the context of C, what is an "object file"?
a. A file containing the C source code
b. A file containing the compiled machine code
c. A file containing documentation for the program
d. A file containing debugging information
PART-B
1. Analyze and explain the importance of the structural elements in C programming, including the role of header
files, functions, and control structures, in creating efficient and maintainable software solutions with example
program.
A C program has a structured format that includes key components. Here's an overview of these components along
with simple examples to illustrate their functionality:
STRUCTURE OF C PROGRAM:
Documentation Section:
It consists of set of command lines used to specify the name of the program, the author of the program and
other details etc..
Comments:
Comments are very helpful in identifying the program features and underlying logi of the program. The lines
with ‘/*’ and ending with ‘*/’ are known as comment lines. These are not executable, the compiler is ignored
anything in between /* and */
Preprocessor Section:
It is used to link system library files, for defining the macros and for defining the conditional inclusion.
Ex : include <stdio.h>
DefintionSection:
The definition section defines all symbolic constants.
Ex: # define pi 3.14
Global Declaration Section:
The variable that are used in more than one function throughout the program are called global variable and
are declared outside of all the function. Ie.m main() function.
Main Function:
Every C program must have one main function, which specify the starting of C program
Declaration Part:
This part is used to declare all the variables that are used in the executable part of the program and these are
called local variables
Executable Part:
It contains at least one valid C statements
The execution of a program begins with opening brace ‘{‘ and ends with ‘}’
First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.
To write the first c program, open the C console and write the following code:
#include <stdio.h>
#include <conio.h>
void main()
{
printf("Hello C Language");
getch();
}
#include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h .
#include <conio.h> includes the console input output library functions. The getch() function is
defined in conio.h file.
void main() The main() function is the entry point of every program in c language. The void keyword
specifies that it returns no value.
getch() The getch() function asks for a single character. Until you press any key, it blocks the screen.
2.Compare and contrast the roles of compilers and interpreters in programming languages, providing real-
world examples to illustrate their strengths and weaknesses.
Compilers and interpreters are both tools used in programming to convert high-level source code into machine code or execute
it directly. They have different approaches and characteristics, each with its own strengths and weaknesses. Let's compare and
contrast them, using real-world examples to illustrate their roles.
Compilation:
Compilers translate the entire source code into machine code before execution.
Errors are reported after the entire code is compiled, which may be frustrating for developers.
The compiled code can be more efficient as it is optimized for the target architecture.
Example: The C and C++ languages are typically compiled. The GNU Compiler Collection (GCC) is a well-known compiler
for these languages.
Interpretation:
Interpreters execute the code line-by-line, translating and running it as they go.
Interpreted code may be slower compared to compiled code due to the ongoing translation process.
Example: Python and JavaScript are typically interpreted. Python's CPython interpreter or Node.js for JavaScript are common
examples.
2. Portability:
Compilation:
Compiled code is usually platform-specific, meaning it may not run on different architectures without
recompilation.
Example: A C program compiled on a Windows machine may not run on a Linux machine without recompilation.
Interpretation:
Interpreted code is generally more portable as the interpreter abstracts the underlying system. It is often "write
once, run anywhere."
Example: Python scripts are highly portable as long as the target system has a compatible interpreter.
3. Development Cycle:
Compilation:
Example: Developing large C++ applications may involve waiting for lengthy compilation times.
Interpretation:
Development cycle is faster since there's no need for a separate compilation step.
Example: Rapid application development in Python or web development with JavaScript can be very fast thanks to
interpretation.
4. Performance:
Compilation:
Generally, compiled code is faster and more efficient since it is optimized for the target platform.
Example: High-performance software like video games or system-level software is often written in compiled languages like C+
+.
Interpretation:
Interpreted code is usually slower due to the runtime translation and lack of low-level optimizations.
Example: Web applications written in interpreted languages like JavaScript might not be as performant as natively compiled
software.
5. Memory Usage:
Compilation:
Compiled code tends to have lower memory overhead since it doesn't need the source code present during
execution.
Example: Standalone desktop applications are often compiled to minimize memory usage.
Interpretation:
Interpreted code often consumes more memory due to the need to keep the source code in memory during
execution.
Example: A Python script may consume more memory than an equivalent C program.
3.Design and implement an efficient algorithm in C to determine whether a given number is prime or not.
#include <stdio.h>
int main() {
int prime = 1;
number = 11;
if((number % loop) == 0) {
prime = 0;
if (prime == 1)
else
return 0;
4. Analyze the significance of the main() function in a C program, explaining its role as the program's entry point and
detailing how it interacts with the operating system. Provide examples of situations where the main() function's design
can impact program execution and functionality.
The main() function plays a critical role in a C program as it serves as the program's entry point and is responsible for
controlling the execution of the entire program. Here's an analysis of its significance and how it interacts with the operating
system:
The main() function is the starting point of execution for any C program. When you run a C program, the operating
system initiates execution by invoking main().
It's mandatory in every C program and must have the exact signature: int main(). The return type int signifies that it
should return an integer status code upon completion.
When the program is run, the operating system loads it into memory and transfers control to the main() function.
The operating system may also pass command-line arguments to main() to provide input or configuration to the
program.
The main() function defines the high-level logic and flow of the program. It contains the instructions that determine
what the program does.
Inside main(), you can call other functions, perform calculations, make decisions, and control the overall behavior of
the program.
4. Return Value:
main() is expected to return an integer value when the program terminates. A return value of 0 typically signifies
successful execution, while non-zero values indicate an error or a specific exit code.
The return value can be used by the calling process (e.g., a shell or another program) to determine if the C program
executed successfully or encountered an issue.
Command-Line Arguments: The design of main() can impact how command-line arguments are processed.
Depending on how you parse these arguments, you can enable different program behaviors or options. For example,
you might write a command-line utility that accepts filenames as arguments and performs different operations based
on those filenames.
Flow Control: The logic within main() determines the program's behavior and execution flow. How you structure the
program in main() can significantly impact its functionality. For example, you could design a menu-driven application
where the user selects options from a menu, each leading to different functionality.
Error Handling: The return value of main() is essential for error handling and reporting. A well-designed main()
should handle and report errors effectively, making it clear to the user what went wrong.
Program Termination: The main() function should handle program cleanup, such as releasing resources and closing
files, before returning. Proper cleanup is crucial for a well-behaved program.
Concurrency: In multi-threaded programs, the design of main() may impact how threads are created and
coordinated.
5.Analyze and explain the importance of adhering to the general rules for constructing variable names in
programming, and provide specific examples that demonstrate how meaningful and well-structured variable names
can enhance code readability and maintainability
Syntax:
Data_Type variable name;
Example: Int age;
Char m;
Float s;
Initializing variables:
Variables declared can be assigned or initialized using an assignment operator =
The declaration and initialization can also be done in the same line
Syntax:
Variable_name = constant;
Or Data_type variable_name = constant;
Example: Y=2;
Int x=15;
Char ch=’c’;
Dynamic initialization:
The initialization of variable at run time us called dynamic initialization
The C initialization can be done at any place in the program
Example:
Swapping of two number
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a; a=b; b=c;
printf(“After swapping value a=%d, b=%d”,a,b); }
Constant variable:
The constant variables are used to remain unchanged value during the execution of the program. It can be done
only by declaring the variable as a constant
Syntax: const data_type variable_name=value;
Example: const int m=10;
Volatile variable:
The volatile variables are those variables that are changed at any time by other external program
Keyword : volatile
Syntax: volatile data_type variable_name
Example:
volatile int d;
6.Examine a C program's code to identify potential issues related to data types when performing addition operations.
#include <stdio.h>
int main() {
int x = 10;
double y = 5.5;
float z = 3.25;
double result1 = x + y;
float result2 = y + z;
int result3 = x + z;
return 0;
7.Explore the fundamental concept of character sets in programming, distinguish between different types of character
sets, and elucidate how their usage can impact the development and functionality of software applications.
The character set is the fundamental raw material of any language and they are used to represent information. The set of
characters used in a language is known as its character set. These characters can be represented in the computers. C programs
are basically of two types, namely
Digits
Source
Character set
Special
Characters
Character set
White Space
Executable Escape
Character setSequence
They are used to construct the statements in the source programs Alphabets - A to Z,a to z.
Decimal Digits - 0 to 9
line
Trigraph Characters:
??= -> # ??( -> [ ??) -> ] ??< -> { ??> -> } ??! -> |
8.Examine the syntax principles for declaring variables in programming languages, and demonstrate the real-world
importance of following these principles with specific examples that underscore their role in writing efficient and
maintainable code.
Declaration of Variables : A variable can be used to store a value of any data type. The declaration of variables must be done
before they are used in the program. The general format for declaring a variable.
Variables are separated by commas and declaration statement ends with a semicolon.
Ex : int x,y,z;
Assigning values to variables : values can be assigned to variables using the assignment operator (=). The general format
statement is :
a= 12.25;
m=‟f‟;
we can also assign a value to a variable at the time of the variable is declared. The general format of declaring and assigning
value to a variable is :
Types of Variables in C
1. local variable
2. global variable
3. static variable
9.Examine the nuances of variable scope in programming languages, delving into how scope affects program design and
debugging. Support your analysis with practical examples from real-world scenarios
In the C programming language, variables have different scopes, which determine where in the code those variables can be
accessed. There are three main types of variable scope in C: local, global, and block scope. Let's explore each of them with
practical examples.
1. Local Scope:
Local variables are declared within a specific code block, such as a function, and can only be accessed within
that block.
#include <stdio.h>
int main()
int x = 10; // 'x' has local scope within the 'main' function
2. Global Scope:
Global variables are declared outside of any function, making them accessible from anywhere in the code.
They have a program-wide scope.
#include <stdio.h>
void anotherFunction()
3. Block Scope:
In C, block scope variables are declared within a code block, such as an if statement or a loop. They are only
accessible within that block.
#include <stdio.h>
int main()
int x = 10; // 'x' has block scope within the 'main' function
if (x > 5)
{
int y = 20; // 'y' has block scope within the 'if' block
Function parameters have a local scope within the function they are defined in.
#include <stdio.h>
int main()
printSum(5, 7); // 'a', 'b', and 'sum' are not accessible here return 0;
Understanding variable scope in C is crucial for writing maintainable and bug-free code. Properly managing the scope of
variables ensures that you can control where variables are accessible, reducing the risk of unintended changes or conflicts in
your code.
10.Analyze the processes of reading and writing characters in programming, including their significance and potential
challenges. Provide real-world examples where character input and output play a critical role in program functionality.
In C, reading and writing characters is typically done using standard input and output functions from the <stdio.h> library. The
primary functions for reading characters include getchar() and scanf(), while writing characters is often performed using
putchar() and printf(). Let's discuss these functions and provide examples for both reading and writing characters.
Reading Characters:
1. getchar(): This function reads a single character from standard input (usually the keyboard) and returns it as an integer,
which represents the ASCII value of the character. It reads characters including whitespace and newline characters.
#include <stdio.h>
int main()
char ch;
printf("Enter a character: ");
2. scanf(): The scanf() function can also be used to read characters, but it provides more control over formatting and error
handling. For reading a single character, you can use the %c format specifier.
#include <stdio.h>
int main()
{ char ch;
return 0;
Writing Characters:
1. putchar(): This function writes a single character to standard output (usually the console). It takes a character as an
argument and displays it.
#include <stdio.h>
int main()
{ char ch = 'A';
2. printf(): The printf() function is a versatile way to format and display characters and other data types. To display a
character, you can use the %c format specifier.
#include <stdio.h>
int main()
{ char ch = 'B';
return 0;
}
It's important to note that when reading characters, it's often a good practice to consume any extra characters, especially
newline characters, from the input buffer to prevent issues with subsequent input operations. In the examples provided, you can
see the space before %c in scanf() to skip whitespace, and getchar() reads and discards any newline characters.
Reading and writing characters in C are fundamental operations that allow you to interact with the user and display
information. These functions are building blocks for more complex I/O operations and text processing.
11. Evaluate the differences between formatted and unformatted input and output methods in programming, and
provide real-world examples that showcase their respective applications and advantages.
Reading data from input device, processing it, and displaying the result on the screen are the three
task of any program
The output data or result of an operation can be displayed from the computer to a standarad output
device ie., Monitor
Syntax:
Example:
main( )
Percentage = 69.200000
Format Specifications:
short unsigned %u
unsigned hexadecimal %x
unsigned octal %o
Real Float %f
Double %lf
unsigned character %c
String %s
Optional Specifiers:
Specifier Description
. Decimal point separating field width from precision (precision stands for
- Minus sign for left justifying the output in the specified field width
Example:
main( )
{
}
Output:
int weight = 63 ;
printf ( "\nweight is %d kg", weight ) ; printf ( "\nweight is %2d kg", weight ) ; printf ( "\nweight is
%4d kg", weight ) ; printf ( "\nweight is %6d kg", weight ) ; printf ( "\nweight is %-6d kg",
weight ) ;
main( )
printf ( "\n%10.1f %10.1f %10.1f", 5.0, 13.5, 133.9 ) ; printf ( "\n%10.1f %10.1f %10.1f", 305.0, 1200.9,
3005.3 );
Output:
Escape Sequences :
The scanf() function is usd to read information the standarad input device
Syntax:
Example:
scanf ( "%d %f %c", &c, &a, &ch ) ;
& denotes the address of the variable. The values received from keyboard must be dropped into
variables corresponding to these addresses
Example:
These statements are used to I/O a single / group of characters from the I/O Device
Here the user can’t specify the type of data that is going to be Input / Ouptput
The character entered through getch() is not displayed in the screen (monitor).
Syntax:
variable_name = getch();
getche() also accepts only single character, but unlike getch(), getche() displays the entered
character in the screen.
Syntax:
variable_name = getche();
It requires Enter key to be typed following the character that you typed
Example:
void main( )
char ch ;
printf ( "\nPress any key to continue" ) ; getch( ) ; /* will not echo the character */ printf ( "\nType any character" ) ;
ch = getche( ) ; /* will echo the character typed */ printf ( "\nType any character" ) ;
Output:
It accepts any line of string including spaces from the standard Input device (keyboard).
It stops reading character from keyboard only when the enter key is pressed.
Syntax:
gets(variable_name);
Example:
Syntax:
putch(variable_name);
Example:
Syntax:
putchar(variable_name);
Example:
Syntax:
Puts(variable_name);
Example:
puts(a);getch ();
Output:
Abcd efgh
Abcd efgh
UNIT-1
12. Discuss the role of the escape sequences like "\n" and "\t" in formatted output with the printf
function.
Escape sequences, such as "\n" and "\t," play a crucial role in formatted output when using the printf
function in C and many other programming languages. These escape sequences allow you to control the
formatting and presentation of text when displaying it to the console or in other output mediums. Here's
an explanation of their roles:
1. \n - Newline Character:
The "\n" escape sequence is used to insert a newline character into the output string. This
character represents the end of the current line and moves the cursor to the beginning of
the next line.
It is commonly used to create line breaks and improve the readability of the output.
#include <stdio.h>
int main()
{ printf("Hello, World!\n"); // This prints "Hello, World!" and moves to the next line.
return 0;
Output:
2. \t - Tab Character:
The "\t" escape sequence inserts a tab character into the output string. Tab characters are
used to create consistent horizontal spacing or indentation.
Tabs are often used when formatting tables, aligning text, or organizing data in a
structured way.
#include <stdio.h>
int main()
printf("Bob\t30\n");
UNIT-1
return 0;
Output:
Apart from "\n" and "\t," there are other escape sequences like "\b" (backspace), "\r"
(carriage return), "\a" (bell), and more, each serving a specific purpose.
These escape sequences are essential for controlling the formatting, alignment, and visual
appearance of text in output, and they improve the user experience and readability of the
displayed information.
Escape sequences are versatile tools that help you structure and format text in a way that makes it more
understandable and visually appealing. They are especially useful when creating tables, lists, or any
output that requires clear separation between lines and columns. Understanding how to use escape
sequences effectively is an important skill for programmers working with text-based output.
PART-C
1. Describe the key components of a C program's structure. Use simple examples to illustrate the
functionality of each component within a C program. Additionally, explain the significance of
maintaining a clear and organized structure in C programming
A C program has a structured format that includes key components. Here's an overview of these
components along with simple examples to illustrate their functionality:
STRUCTURE OF C PROGRAM:
UNIT-1
i. Documentation Section:
It consists of set of command lines used to specify the name of the program, the author of the program
and other details etc..
Comments: Comments are very helpful in identifying the program features and underlying logi of
the program. The lines with ‘/*’ and ending with ‘*/’ are known as comment lines. These are not
executable, the compiler is ignored anything in between /* and */
ii. Preprocessor Section: It is used to link system library files, for defining the macros and for defining
the conditional inclusion.
EX: #include<stdio.h>
iii. DefintionSection: Preprocessors are the programs that process our source code before the
process of compilation. There are multiple steps which are involved in the writing and execution of
the program. Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to
create a constant throughout the program. Whenever this name is encountered by the compiler, it
is replaced by the actual piece of defined code.
Ex: # define pi 3.14
iv. Global Declaration Section: The variable that are used in more than one function throughout the
program are called global variable and are declared outside of all the function. Ie.m main() function.
EX. int num = 18;
v. Main Function: Every C program must have one main function, which specify the starting of C
program Declaration Part: This part is used to declare all the variables that are used in the executable
part of the program and these are called local variables
UNIT-1
Executable Part: It contains at least one valid C statements. The execution of a program begins with
opening brace ‘{‘ and ends with ‘}’
vi. Sub Programs
User-defined functions are called in this section of the program. The control of the program is shifted to
the called function whenever they are called from the main or outside the main() function. These are
specified as per the requirements of the programmer.
Structure of C Program with example
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
UNIT-1
Sections Description
/**
* file: sum.c
* author: you
It is the comment section and is part of the description section of the code.
* description: program to
find sum.
*/
Header file which is used for standard input-output. This is the preprocessor
#include<stdio.h> section.
#define X 20 This is the definition section. It allows the use of constant X in the code.
This is the Global declaration section includes the function declaration that can be
int sum(int y) used anywhere in the program.
int main() main() is the first function that is executed in the C program.
{…} These curly braces mark the beginning and end of the main function.
printf(“Sum: %d”, sum(y)); printf() function is used to print the sum on the screen.
We have used int as the return type so we have to return 0 which states that the
return 0; given program is free from the error and it can be exited successfully.
int sum(int y)
{ This is the subprogram section. It includes the user-defined functions that are called
return y + X; in the main() function.
}
2. Suppose you work for a shipping company that is responsible for arranging packages in a warehouse. Each
package is identified by a unique number. The company wants to determine the number of ways they can
arrange a set of packages in a row for efficient storage. Write a C program that calculates the number of ways
to arrange a given number of packages in a row. Highlight the steps involved in compilation and execution,
aiming to showcase the importance of these processes in software development
Execution is the process of running the program, to execute a ‘C’ program, we need to follow the steps
given below.
i. Create the program
ALGORITHM
1.Start.
2.Initialize numPackages to 0.
3.Initialize ways to 1.
4,Display "Enter the number of packages."
UNIT-1
PROGRAM
#include <stdio.h>
int main() {
int numPackages, ways = 1;
return 0;
}
OUTPUT
Enter the number of packages: 5
Number of ways to arrange 5 packages in a row: 120
ii. Compiling the program: This is the process of converting the high level language program into
machine understandable form. For this purpose compiler is used. Usually this can be done in C language
by pressing ALT+F9 or compile from compile menu Here there are possibility to show errors ie., syntax
errors, means the statements written in program are not in proper syntax
iii. Linking the program with system library :C language program is the collection of predicted functions.
These functions are already written in some standard C header files, Therefore, before executing a C
program, we need to link system library This can be done automatically at the time of execution
iv. Executing the program: This is the process of running and testing the program with the sample data
At this time there is a possibility show two type of errors given below
Logical Error: These are the errors, in which conditional and control statements cannot end their match
after some sequential execution
Data error: These are the errors, in which the input data given, if not in a proper syntax as specified in
input statements
UNIT-1
3. Imagine you are working on a GPS navigation system. Write a c program to calculate the coverage
area and the perimeter of circular regions to optimize the routes and estimate the time it takes to
travel within those regions. Ensure the program handles different data types effectively
int main() {
double radius;
if (radius < 0) {
printf("Invalid input. Radius must be non-negative.\n");
} else {
// Calculate area and perimeter
double area = M_PI * radius * radius; // PI is a constant defined in math.h
double perimeter = 2 * M_PI * radius;
// Display results
printf("Coverage area of the circular region: %.lf \n", area);
printf("Perimeter of the circular region: %.lf \n", perimeter);
}
return 0;
}
Output:
Enter the radius of the circular region: 5
Coverage area of the circular region: 78.54
Perimeter of the circular region: 31.42
UNIT-1
4. Develop a C program that accepts two numerical inputs from the user, then proceeds to carry out basic
arithmetic operations (addition, subtraction, multiplication, division) on the given numbers. The program
should display the computed results using different data types
1. Start
14. End
program
#include <stdio.h>
int main() {
double num1, num2; // Declare variables for the user inputs
double result; // Declare a variable to store the result
return 0;
}
a)Write a C program to declare and initialize variables of different data types such as int, float, and char.
Print the values of these variables
b)Write a C program to demonstrate the use of constants. Define constants for pi (π) and the speed of
light. Print their values.
a) C program to declare and initialize variables of different data types and print their values:
#include <stdio.h>
int main()
{
// Declare and initialize variables of different data types
int integerVar = 42;
float floatVar = 3.14159;
char charVar = 'A';
// Print the values of the variables
printf("Integer Variable: %d\n", integerVar);
printf("Float Variable: %f\n", floatVar);
printf("Character Variable: %c\n", charVar);
return 0;
}
In this program, we declare and initialize variables of different data types (int, float, and char) and then
print their values.
UNIT-1
b) C program to demonstrate the use of constants for pi (π) and the speed of light:
#include <stdio.h>
int main()
{
// Define constants for pi (π) and the speed of light
const double PI = 3.14159;
const double SPEED_OF_LIGHT = 299792458;
// in meters per second
// Print the values of the constants
printf("Value of pi (π): %f\n", PI);
printf("Speed of Light: %lf meters per second\n", SPEED_OF_LIGHT);
return 0;
}
In this program, we define two constants (PI and SPEED_OF_LIGHT) and then print their values. The
const keyword is used to declare constants, and these constants are printed with their respective values.
6) Draft a Syntax, Flow chart using c program to find the sum of 10 non negative numbers entered
by the user
#include <stdio.h>
int main() {
int sum = 0;
int count = 0;
if (number < 0) {
printf("Error: Negative number entered. Skipping.\n");
continue; // Skip to the next iteration
}
sum += number;
count++;
}
return 0;
1. Start
UNIT-1
2. Initialize variables:
- sum = 0 (to store the sum of numbers)
- count = 0 (to keep track of the number of non-negative numbers entered)
3. Repeat the following 10 times:
a. Read a number from the user and store it in the variable 'number'.
b. If 'number' is negative:
- Display an error message ("Error: Negative number entered. Skipping.").
- Skip the rest of the current iteration (continue).
c. Add 'number' to 'sum'.
d. Increment 'count' by 1.
4. Display the sum of the 'count' non-negative numbers entered by the user.
5. End
#include <stdio.h>
int main()
{ char character;
// Prompt the user to enter a character
printf("Enter a character: ");
scanf(" %c", &character);
// Print the entered character
printf("You entered: %c\n", character);
return 0;
}
In this program, the user is prompted to enter a character, and then the program prints the entered
character.
Output:
Enter a character: A
You entered: A
b) C program to read and print the first character of a sentence:
#include <stdio.h>
int main()
{ char sentence[100];
// Prompt the user to enter a sentence
printf("Enter a sentence (up to 100 characters): ");
scanf(" %[^\n]s", sentence);
if (sentence[0] != '\0')
UNIT-1
{
// Print the first character of the sentence
printf("The first character of the sentence is: %c\n", sentence[0]);
}
else
{
printf("No characters entered.\n");
}
return 0;
}
Output:
Enter a sentence (up to 100 characters): The quick brown fox
The first character of the sentence is: T
8.
a) This program takes an integer as input, calculates and displays its square and cube:
#include <stdio.h>
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
int square = num * num;
int cube = num * num * num;
printf("You entered: %d\n", num);
printf("Square: %d\n", square);
printf("Cube: %d\n", cube);
return 0;
}