C keyboard input – Input Output Functions C Programming

Input Output Functions C Programming

Input and Output in C programming language are accomplished through library functions. C programming language has defined many library functions for input and output.

In C programming, scanf() and printf() functions are most commonly used standard library function for taking input form keyboard and printing output on screen respectively.

Here, when we are say Input that means feeding data into C program using the keyboard and output means printing data on screen. We will discuss file Input and Output in separate section.

Most of the standard library function for Input and Output is defined in stdio.h header file.
C keyboard input: C programming language treats all the I/O devices and files as stream of data. A C program reading data from keyboard is similar to reading data from a file similarly printing data on screen is similar to writing data on a file. Three streams gets automatically attached when a program starts execution.

Stream File Pointer I/O Device
Standard Input stdin Keyboard
Standard Output stdout Screen
Standard Error stderr Screen

Standard Library Functions for Input & Output of a Character

Formatted input and output functions in c: Header file stdio.h provides two in-built functions for reading a character from keyboard and writing/printing a character on screen.

Function Description
getchar() Returns a character from stdin stream(keyboard).
putchar() Writes a character to stdout stream(screen).

C Program for Input and Output of a Character

Input Output Functions C Programming

#include<stdio.h>
#include<conio.h>
  
int main(){
   char c;
  
   printf("Enter a character\n");
   /* Reading a character from keyboard */
   c = getchar();
   printf("You Entered \n");
   /* Printing a character on screen */
   putchar(c);
    
   getch();
   return(0);
}

Program Output

Enter a character
J
You Entered 
J

<h3″>Standard Library Functions for Input & Output of Strings

Function Description
gets() Reads a line from stdin(keyboard) and stores it into given character array.
puts() Writes a string to stdout(screen) stream excluding null terminating character.

C Program for Input and Output of a String

C Program for Input and Output of a String

#include <stdio.h>
#include <conio.h>
  
int main(){
   char string[50];
  
   printf("Enter your name\n");
   gets(string);
  
   printf("You name is : ");
   puts(string);
     
   getch();
   return(0);
}

Output

Enter your name
Jack
You name is : Jack

Standard Library Functions for Formatted Input & Output

The stdio.h Library function printf() and scanf() are used to print and read formatted data in a C program respectively. Function printf and scanf both can be used for Input and output of all in-built data types as well as user defined data types.

Function Description
printf() Print formatted data to stdout(screen).
scanf() Writes a character to stdout stream(screen).

C Program to shows the use of printf function

C Program to shows the use of printf function

#include <stdio.h>
#include <conio.h>
  
int main(){
  
    printf("Printing characters\n");
    printf("%c %c %c %c\n\n", 'a', 'A', '#', '1');
      
    printf("Printing integers\n");
    printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015);
      
    printf("Printing floating point numbers\n");
    printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412);
      
    printf("Printing string\n");
    printf("%s\n\n", "TechCrashCourse");
      
    printf("Printing radicals\n");
    printf ("%d %x %o %#x %#o\n\n", 2105, 2015, 2015, 2015, 2015);
      
    getch();
    return 0;
}

Output

Printing characters
a A # 1

Printing integers
2015 2015       2015 0000002015

Printing floating point numbers
1.414120  1.41 +1e+000 1.414120E+000

Printing string
TechCrashCourse

Printing radicals
2105 7df 3737 0x7df 03737

C Program to shows the use of scanf function

C Program to shows the use of scanf function

#include <stdio.h>
#include <conio.h>
  
int main(){
    int a, b, sum;
    printf("Enter to integers to add\n");
    /* Taking formatted input from user using scanf */
    scanf("%d %d", &a, &b);
    sum = a + b;
    /* Printing formatted output */
    printf("%d + %d = %d", a, b, sum);
     
    getch();
    return 0;
}

Output

Enter to integers to add
5 3
5 + 3 = 8

fgetc() function in c – fgetc C Library Function

fgetc C Library Function

fgetc() function in c: The function int fgetc(FILE *stream); gets the next character from the input stream from the current position(pointed by the internal file position indicator) and increment the current position indicator. The character is read as unsigned char and type casted to an integer before returning.

Function prototype of fgetc

int fgetc(FILE *stream);
  • stream : A pointer to a FILE object which identifies a stream.

Return value of fgetc

fgetc in c: This function fgetc returns the character read(type casted to an int value) or EOF on end of file or error.

C program using fgetc function

fgetc c: The following program shows the use of fgetc function to read the content of a file. Let file “textFile.txt” contains “fgetc C Standard Library function” string. The content of this file will get printed by the following program.

fgetc C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   int c;
   
   file = fopen("textFile.txt", "r");
   if(file == NULL){
      perror("Error: Unable to open a file");
   } else {
       /* Read characters from a file using fgetc */
       while(!feof(file)){
          c = fgetc(file);
          printf("%c", c);
       }
       fclose(file);
   }
    
   return(0);
}

Output

fgetc C Standard Library function

pow() in c – pow C Library Function

pow C Library Function

pow() in c: The function double pow(double base, double exponent); returns base raised to the power of exponent (baseexponent).

Function prototype of pow

double pow(double base, double exponent);
  • base : A floating point value of base.
  • exponent : A floating point value of exponent.

Return value of pow

pow.c: It returns base raised to the power of exponent. If the result of pow function is too large or too small to be represented by a return type value, it causes a range error.

C program using pow function

The following program shows the use of pow function to calculate xy.

pow C Library Function

#include <stdio.h>
#include <math.h>
 
int main ()
{
  double base, exponent, result;
  printf("Enter base and exponent\n");
  scanf("%lf %lf", &base, &exponent);
   
  result = pow(base, exponent);
  printf("%lf^%lf = %lf\n", base, exponent, result);
   
  return 0;
}

Output

Enter base and exponent
2 5
2.000000^5.000000 = 32.000000
Enter base and exponent
5 0
5.000000^0.000000 = 1.000000

Remove extra spaces python – C Program to Remove Extra Space Characters From a String

C program to remove or delete extra spaces from string
  • Write a C program to delete extra space characters from a string.

Given a string containing multiple space characters, we have to remove extra spaces from string. If a string contains more than one consecutive space, then we should remove all consecutive spaces except one.

For Example
If input string is “Tech Crash Course”
Output string should be “Tech Crash Course”.

C program to remove or delete extra spaces from string

We first take a string as input from user using gets function. Using a for loop, we iterate from first character to last character of input string and check whether current character is a space character or not. If last character was not a space character then we copy this space character to output string otherwise skip this space character. At last we add a null character at the end of output string. In this program we are using an extra character array of same size as input array, the space complexity of this algorithm is O(n) and as we are traversing input array only once the time complexity also becomes O(n).

C program to remove or delete extra spaces from string

/*
* C Program to remove extra spaces
*/
#include <stdio.h>
#include <conio.h>
#include <string.h>
 
int main(){
    char inputString[100], outputArray[100];
    int readIndex = 0, writeIndex;
    printf("Enter a String \n");
    gets(inputString);
    /* Skips all spaces before first characters */
    while(inputString[readIndex] == ' '){
        readIndex++;
    }
 
    for(writeIndex = 0;inputString[readIndex] != '\0'; readIndex++){
      if(inputString[readIndex]==' ' && inputString[readIndex-1]==' '){
          continue;
      }
      outputArray[writeIndex] = inputString[readIndex];
      writeIndex++;
    }
    outputArray[writeIndex] = '\0';
    printf("String without extra spaces\n%s", outputArray);
 
    getch();
    return 0;
}

Program Output

Enter a String 
Tech   Crash    Course
String without extra spaces
Tech Crash Course

We can also solve this problem without using any extra output character array. In this case we can modify and remove extra spaces from input array.

Electronic devices & circuits pdf – Electronic Devices and Circuit Notes PDF Free Download

edc-notes

Electronic Devices and Circuit Notes: Electronic Devices and Circuit notes can be extremely significant for students who wish to gain a complete understanding of the various topics and concepts included in this subject and subsequently perform well in the B.Tech first semester examinations.

The EDC lecture notes have been designed accurately by experts and professionals in the field of electronics engineering and provide entirely reliable sources of study material for students to enhance their conceptual background regarding the subject and achieve the highest marks in exams.

The EDC notes provide students with a head start in the sense that they can assess their preparations for exams in an easier way utilizing the various aids provided by these notes. This article provides students with several sources of information and study material so that they can increase their effectiveness and efficiency while studying. The notes are in accordance with the latest versions of the syllabus as per the first semester of the B. tech course. The article also includes several important questions to aid students in forming habitual instinct when it comes to problem-solving.

The Following provides the various sources of study material included in this article.

Introduction to Electronic Devices and Circuits Notes

Electronic devices & circuits pdf: In the most basic sense, electronic engineering deals with the flow of electrons in semiconductors, gas, and vacuum tubes. The various applications of electronics include medical and home appliances, computer and mobile communications, robotics, etc.

The movement of electrons through a conveyor gives us electric flow. This electric flow can be delivered with the assistance of batteries and generators. The gadget which controls the progression of electrons is called an electronic device. These gadgets are the fundamental structure squares of electronic circuits. Gadgets have different branches incorporating analog electronics, digital electronics, microelectronics, nanoelectronics, optoelectronics, coordinated circuit, and semiconductor gadget.

All circuit branch engineers require the basic knowledge of this subject to function properly in this area. Electronic Devices and Circuits aim to familiarize students and aspirants with amplifier circuits, design and analysis of junction diode, the principle of operation, and BJT as well as FET transistors. In addition to this, the subject intends for the understanding of the diode as a rectifier to propagate the basic principle of the filter of circuits along with its various types.

Electronic Devices and Circuits Notes PDF Free Download

The EDC notes provide step by step explanation of all of the concepts and topics that are included in the subject so that students develop a better understanding and strengthen their core knowledge along with building conceptual foundations for any future prospects towards electronics engineering.

The Electronic Devices and Circuits notes have been designed in a very comprehensive and easy to understand language along with help of several diagrams and charts so that students get to utilize their maximum potential and enhance their abilities and make the most of their time.

The following provides the various formats of the notes and other study material for Electronic Devices and circuits that students can easily download for free.

  • EDC Question bank with answers PDF.
  • Electronic Devices and Circuits Lecture Notes PDF.
  • Electronic Devices and Circuits handwritten notes PDF.
  • EDC previous year question papers PDF.
  • EDC 1st semester B. Tech notes PDF.
  • Electronic Devices and Circuits PPT.

Electronic Devices and Circuits Reference Books

Books are considered to be the best source of information when it comes to gaining a complete understanding of a subject. Books provide students with theoretical as well as practical knowledge for better prospects in future as well as bagging excellent grades in exams. There are numerous reference books on the subject matter of Electronic Devices and Circuits that are available in the market providing an abundance of extensive information on EDC.

Following refers to a list of some of the most popular reference books on the subject of Electronic Devices and Circuits as prescribed and recommended by some of the leading experts and professionals in the field of electronics engineering. Students may choose from this list according to their needs.

  • Electronic Devices and Circuits (B.S Publications), written by K.Lal Kishore
  • Electronic Devices and Circuits (I.K. International Publications, New Delhi, 2006), written by G.S.N. Raju
  • Electronic Devices and Circuits (Technical Publications), written by A.P Godse, and U.A Bakshi,
  • Electronic Devices and Circuits (Anuradha Agencies), written by K.S. Srinivasan
  • Electronic Devices and Circuits, published by McGraw Hill and written by Venkata Rao
  • Millman’s Electronic Devices And Circuits (Sie), published by McGraw Hill, written by Jacob Millman.
  • Electronic Devices and Circuits (6th Edition), written by Theodore F. Bogart, Jeffery S. Beasley, and Guillermo Rico.
  • Electronic Devices and Circuits (5th Edition), Oxford Publications, written by David A. Mill
  • A reference guide to Useful Electronic Circuits And Circuit Design Techniques, written by Kervin Mathew
  • Electronic devices and circuits, written by Anil K. Maini and Varsha Agarwal.
  • Electronic Devices and Circuits, written by Er. N.B.L. Mathur.

Electronic Devices and Circuits Updated Syllabus

The curriculum for B. Tech 1st semester 1st year contains five mutually exhaustive units containing a plethora of knowledge on the subject matter of the basics for Electronics Engineering.

Students can adhere to the syllabus provided here which is updated according to the latest versions as mandated for the 1st year 1st semester of the B. Tech course to efficiently and effectively organise and plan their preparations. This will help you in properly allotting time and effort for each chapter and unit to secure excellent grades in exams.

The following provides the updated syllabus for Electronic Devices and Circuits for 1st-semester 1st year B. Tech.

UNIT TOPICS
UNIT-I: P.N. Diode Characteristics P-N Junction Diode

  • Qualitative Theory of P – N Junction
  • P – N Junction as a diode
  • Diode equation
  • Volt – ampere characteristics
  • temperature dependence of V – I characteristic
  • Ideal versus practical – resistance levels( static and dynamic)
  • Transition and diffusion capacitances, diode equivalent circuits
  • Load line analysis
  • Breakdown mechanisms in semiconductor diodes
  • Zener diode characteristics.

Special Purpose Electronic Devices

  • The principal of operation and Characteristics of Tunnel Diode with the help of energy band diagrams
  • Varactor Diode
  • SCR
  • Photodiode
UNIT-II: Rectifiers and Filters
  • P – N Junction as a rectifier
  • Half wave rectifier
  • Full wave rectifier
  • Bridge rectifier
  • Harmonic components in a rectifier circuit, Inductor filter
  • Capacitor filter
  • L – section filter
  • – section filter and comparison of various filter circuits
  • Voltage regulation using Zener diodes.
UNIT-III: Bipolar Junction Transistor
  • R: The Junction transistor
  • Transistor current components
  • Transistor as an amplifier
  • Transistor construction
  • Input and Output characteristics of a transistor in Common Base
  • Common Emitter
  • Common collector configurations.
  • α and β Parameters and the relation between them
  • BJT Specifications
  • BJT Hybrid Model
  • h – parameter representation of a transistor
  • Analysis of a single stage transistor amplifier using h – parameters
  • Voltage gain
  • Current gain
  • Input impedance and Output impedance.
  • Comparison of transistor configurations in terms of Ai, Ri, Av and Ro
UNIT-IV: Transistor Biasing and Stabilisation
  • Operating point
  • The D.C and A.C Load lines
  • Need for biasing
  • Criteria for fixing
  • Operating point
  • B.J.T biasing
  • Fixed bias
  • Collector to base bias
  • Self bias techniques for stabilization
  • Stabilization factors, (s, s I, s II )
  • Bias Compensation using diode and transistor
  • Compensation against variation in V BE, I CO
  • Thermal runaway
  • Condition for Thermal stability.
UNIT-V: Field Effect Transistor and FET Amplifier Field Effect Transistor

  • JFET (Construction, principal of Operation
  • Volt – Ampere characteristics)
  • Pinch – off voltage – Small signal model of JFET
  • FET as Voltage variable resistor, Comparison of BJT and FET
  • MOSFET (Construction, principal of Operation and symbol)
  • MOSFET characteristics in Enhancement and Depletion modes.

FET Amplifiers :

  • FET Common source Amplifier
  • Common Drain Amplifier
  • Generalized FET Amplifier
  • FET biasing.

List of Important Questions for EDC

Students may develop a habit of practicing questions for Electronic Devices and Circuits to form a concise and comprehensive understanding of the topics and concepts included in the subject.

Familiarising yourself with the question pattern can prove to be of exceeding significance so that you answer questions appearing in exams more precisely and accurately in less time.

Following is a list of some of the most important questions that students may practice to increase their efficiency.

  • What is meant by a Semiconductor?
  • Define Barrier Potential.
  • Explain in detail the dynamic resistance of the Diode.
  • Compare Avalanche Breakdown with Zener Breakdown.
  • What are the Voltage Regulators? Explain its various types.
  • Use a diagram to explain the working of the LED and its construction.
  • What do you understand by holding current in an SCR?
  • Explain Thyristors and it’s various triggering devices.
  • Briefly examine Amplifiers.
  • What are the CS amplifiers? Explain with the help of a circuit diagram.
  • Differentiate between the multiple features of the different configurations of BJT amplifiers.
  • Explain Cross over distortion.
  • What is the difference between a difference mode and a common mode?
  • How are power amplifiers efficient?
  • Briefly examine the various techniques of Hazeltine neutralization.
  • What do you understand by Feedback and Feedback amplifiers?
  • What is sensitivity?
  • Explain Oscillators and their various classifications.
  • Use an example to define a shunt feedback amplifier as well as voltage series.
  • Differentiate between Positive feedback and Negative feedback.
  • What are the various advantages of crystal oscillators?

Frequently Asked Questions on Electronic Devices and Circuits

Question 1.
What is meant by a Zener Diode?

Answer:
At the point when the reverse voltage arrives at breakdown voltage in ordinary PN junction diode, the current through the intersection and the force dispersed at the intersection will be high. Such activity is ruinous and the diode gets harmed. While diodes can be planned with sufficient power dissipation abilities to work in a separate district. One such diode is known as the Zener diode.

Question 2.
What are the different Transistor Configurations?

Answer:
The different Transistor configurations are as follows:

  • CB (Common bank) configuration.
  • CE (Common emitter) configuration.
  • CC (Common collector) configuration.

Question 3.
Can one utilize these notes for revision during exams?

Answer:
The EDC notes have been formulated with a chief agenda of securing good scores in the B. Tech 1st semester exams. They are extremely comprehensive and provide detailed explanations with the accurate organisation of the different topics. Students can completely rely on these notes for revision during exams.

Question 4.
Explain the limitations of h-parameters.

Answer:
The 2 chief limitations of h-parameters are as follows:

  • It provides the right answers only for A.C signals. This is due to the reason that a transistor behaves as a linear device only for small signals.
  • For a particular transistor, finding the exact values for h-parameters can prove to be reasonably difficult. This is because parameters are subject to the unit to unit variation, due to change in temperature and change in operating point.

Blender hotkeys – Keyboard Shortcuts | List of Keyboard Shortcut Keys | Benefits of Using Shortcuts in Keyboard

Keyboard Shortcuts: Due to the pandemic situation and high technological leaving conditions, everyone is handling computers, iPad, smartphones, tablets, and smart devices to perform their daily work and boost up their productivity. In these busy lives, people are choosing to go with smart work and executing their tasks in a short way. If you are a daily computer user then you must utilize keyboard shortcuts to save your time and make it done quickly.

By using keyboard shortcut keys, improves efficiency and productivity within few steps. Shortcut keys are mostly like a mouse that lessens your work & makes it faster. Copy and Paste Keyboard Shortcut Keys are the most common keys used everywhere. Just have a look at this guide to learn and use keyboard shortcuts & save your valuable time.

Keyboard Shortcuts List

Blender hotkeys: We’ve compiled a list of keyboard shortcuts for various windows, operating systems, applications, etc. that are classified into categories for easy access to our readers, students, software employees. If we missed some Shortcuts for Keyboard in this list, please make us familiar with them through the comments section below. Meanwhile, check out our comprehensive shortcuts keyboard list and boost your productivity.

5 Reasons Why You Should Be Using Keyboard Shortcuts

What is the advantage of using shortcuts: The following are some of the reasons that aid you to replace or at least reduce mouse habits and start using shortcut keys extensively:

  1. Efficiency
  2. Multitasking
  3. Complementarity
  4. Health issues
  5. Precision

Benefits of Using Shortcuts of Keyboard

Every topic has advantages and disadvantages. Finding the advantages and making use of them in our daily life changes you totally in and out. So, here we are going to find some of the benefits of using the keyboard shortcuts:

  • Using the mouse will develop the possibility of inflammation of the tendons so it’s better to learn and use keyboard shortcuts.
  • Work faster with keyboard shortcut keys.
  • Increase productivity.
  • Boost up your memory power.
  • Helps to perform plenty of tasks smoothly in hectic times.

FAQs on Shortcuts in Keyboard

1. What are the Keyboard Shortcuts?

In Computing, a series of one or more keys that invoke a software program to execute a preprogrammed action is called Keyboard Shortcut. Keyboard Shortcut meaning may differ based on the software manufacturer. You will find different shortcut keys for different keyboards like Windows, Mac, Youtube, WordPress, etc.

2. How to Use Keyboard Shortcuts in Windows? 

Here we will teach you how to use Windows keyboard shortcuts easily and quickly:

  1. Understand how key shortcuts work.
  2. Use general key shortcuts to access Windows features.
  3. Use keyboard shortcuts to help with typing, copying, and pasting.
  4. Use keyboard shortcuts in File Explorer.
  5. Use key shortcuts with the mouse.

3. How to change keyboard shortcut keys in windows 10? 

There is no native way to change the keyboard shortcuts in Windows 10. Don’t worry at all, because we have a great tool called AutoHotKey to made the process of keyboard shortcuts change quite easy.

4. How to Disable keyboard shortcuts?

There are three ways to disable keyboard shortcuts and they are listed below:

  1. Use a script to tweak your Registry
  2. Turn off hotkeys
  3. Disable all Windows shortcut keys using the Registry Editor

5. How to find keyboard shortcuts?

In various applications, you’ll get the list of keyboard shortcuts next to menu items. Hardly, in some applications such as Microsoft Word, you should hover over a button to display the list of the MsWord keyboard shortcuts.

Passing array to function c – Passing Array to Function in C Programming

Passing Array to Function in C Programming

Passing array to function c: How to pass array to a function in C ?
In C programming, an array element or whole array can be passed to a function like any other basic data type. We can pass an array of any dimension to a function as argument. Passing an array to a function uses pass by reference, which means any change in array data inside will reflect globally.

Passing Single Element of an Array to Function
How to pass an array to a function c: We can pass one element of an array to a function like passing any other basic data type variable.

C program to pass one element of an array to function

Passing Array to Function in C Programming

#include <stdio.h>
#include <conio.h>
 
int getSquare(int num){
    return num*num;
}
 
int main(){
   int array[5]={1, 2, 3, 4, 5};
   int counter;;
   for(counter = 0; counter < 5; counter++){
       /* Passing individual array elements to function */
       printf("Square of %d is %d\n", array[counter], getSquare(array[counter]));
   }
    
   getch();
   return 0;
}

Output

Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

Passing one dimensional array to function
C passing array to function: We can pass a one dimensional array to a function by passing the base address(address of first element of an array) of the array. We can either pas the name of the array(which is equivalent to base address) or pass the address of first element of array like &array[0]. Similarly, we can pass multi dimensional array also as formal parameters.
Different ways of declaring function which takes an array as input.

  • Function argument as a pointer to the data type of array.
    int testFunction(int *array){
    /* Function body */
    } 
    
  • By specifying size of an array in function parameters.
    int testFunction(int array[10]){
    /* Function body */
    }
    
  • By passing unsized array in function parameters.
    int testFunction(int array[]){
    /* Function body */
    }
    

C Program to Pass One Dimensional Array as Parameter to a Function

C Program to Pass One Dimensional Array as Parameter to a Function

#include <stdio.h>
#include <conio.h>
 
/* This function takes integer pointer as input */
void printArrayOne(int *array, int size){
    int i;
    for(i=0; i<size; i++){
        printf("%d ", array[i]);
    }
    printf("\n");
}
 
/* This function takes sized array as input */
void printArrayTwo(int array[5], int size){
    int i;
    for(i=0; i<size; i++){
        printf("%d ", array[i]);
    }
    printf("\n");
}
 
/* This function takes unsized array as input */
void printArrayThree(int array[], int size){
    int i;
    for(i=0; i<size; i++){
        printf("%d ", array[i]);
    }
    printf("\n");
}
 
int main(){
   int array[5]={1, 2, 3, 4, 5};
   printArrayOne(array, 5);
   printArrayTwo(array, 5);
   printArrayThree(array, 5);
    
   getch();
   return 0;
}

Output

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

What is scanf – What is printf and scanf function in C

What is printf and scanf function in C

Interview Questions

What is printf() function in C

What is scanf: The function int printf(const char *format, …); writes a formatted string to stdout(standard output device). If format contains format specifiers (subsequences beginning with %), the additional arguments following format are inserted after formatting in the resulting string by replacing their respective format specifiers.
Function prototype of printf:

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

format : This is a null-terminated string containing the text to be written to stdout. It may contains some embedded format specifiers.
additional arguments : These arguments will substitute the value of format specifiers in output string.

What is printf and scanf function in C

#include <stdio.h>
 
int main(){
 
    printf("Printing characters");
    printf("%c %c %c %c\n\n", 'a', 'A', '#', '1');
     
    printf("Printing integers");
    printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015);
     
    printf("Printing floating point numbers");
    printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412);
     
    printf("Printing string");
    printf("%s\n\n", "TechCrashCourse");
     
    return 0;
}

Output

Printing characters
a A # 1
Printing integers
2015 2015       2015 0000002015
Printing floating point numbers
1.414120  1.41 +1e+000 1.414120E+000
Printing string
TechCrashCourse

What is scanf() function in C

The function int scanf(const char *format, …); reads formatted data from stdin(standard input device) and stores them in the variables pointed by the additional arguments. Additional arguments must point to variables of the same type as specified in the format.

Function prototype of scanf

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

format : This is a null terminated string that contains Whitespace character, Non-whitespace character and Format specifiers.
additional arguments : As per the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the data read from stdin to be stored.

Return value of scanf
On success, scanf function returns the total number of objects successfully read, it may or may not be same as the expected number of items specified in format string.

What is scanf() function in C

#include <stdio.h>
 
int main(){
    int a, b, sum;
    printf("Enter to integers to add\n");
    /* Taking input from user using scanf */
    scanf("%d %d", &a, &b);
    sum = a + b;
     
    printf("%d + %d = %d", a, b, sum);
 
    return 0;
}

Output

Enter to integers to add
3 9
3 + 9 = 12

How to find area and perimeter of a parallelogram – C++ Program to Find Area and Perimeter of Parallelogram

How to find area and perimeter of a parallelogram: In the previous article, we have discussed C++ Program to Find Area and Circumference of a Circle. In this article, we will see C++ Program to Find Area and Perimeter of Parallelogram.

C++ Program to Find Area and Perimeter of Parallelogram

Find perimeter of parallelogram: In this C++ program, we will calculate perimeter and area of parallelogram. Before jumping to C++ program, let’s first discuss about parallelogram and it’s properties.

A parallelogram is quadrilaterals(having four sides) with opposite sides parallel and equal in length. Opposite angles of a parallelogram are also equal.
Properties of Parallelogram

  • Opposite angles of a parallelogram are equal.
  • Diagonals of a parallelogram divides each other in two equal half.
  • Opposite sides of a parallelogram are parallel and equal in length.
  • The sum of any two adjacent angles of a parallelogram are 180 degrees.

C++ Program to Find Area of Parallelogram

How to find perimeter of a parallelogram: To calculate the area of parallelogram we need length of Base and Height.

  • Base : We can choose any side of a parallelogram as base to calculate area of parallelogram.
  • Height : Height of a parallelogram is the perpendicular distance between the base and it’s opposite side.

Area of Parallelogram
How to calculate the perimeter of a parallelogram: The area of a parallelogram can be calculated by multiplying Base and Height.

Area of Parallelogram = B X H
Where,

  • B is the length of base of parallelogram.
  • H is the length of height of parallelogram.

C++ Program to Find Area of Parallelogram
C++ Program to Find Area of Parallelogram

// C++ Program to calculate area of Parallelogram
 
#include <iostream>
using namespace std;
  
int main(){
    float base, height, area;
    cout << "Enter the base and height parallelogram\n";
    cin >> base >> height;
     
    // Area of parallelogram = base X height 
    area = base * height;
    cout << "Area of parallelogram : " << area;
      
    return 0;
}

Output

Enter the base and height parallelogram
8 5
Area of parallelogram : 40

C++ Program to find Perimeter of parallelogram

The perimeter of a parallelogram can be calculated by adding the length of all four sides of parallelogram. As we know the length of opposite sides of parallelogram are equal, we can add any two adjacent sides of parallelogram and then multiply it with 2 to get perimeter of parallelogram.

Perimeter of parallelogram

Perimeter of Parallelogram = 2X(S1 + S2)
Where, S1 and S2 are length of adjacent sides of parallelogram.
C++ Program to find Perimeter of parallelogram

// C++ Program to calculate perimeter of Parallelogram
 
#include <iostream>
using namespace std;
  
int main(){
   float side1, side2, perimeter;
   cout << "Enter the length of adjacent sides of parallelogram\n";
   cin >> side1 >> side2;
   // Perimeter of parallelogram = 2X(side1 + side2)
   perimeter = 2*(side1 + side2);
   cout << "Perimeter of parallelogram : " << perimeter;
 
   return 0;
}

Output

Enter the length of adjacent sides of parallelogram
10 4
Perimeter of parallelogram : 28

The comprehensive list of C++ Programs Examples covered in our pages are very useful for every beginners and experienced programmers. So, make use of these C++ Coding Exercises & hold a grip on the programming language.

Reverse a number – C Program to Reverse Digits of a Number

C Program to Reverse Digits of a Number
  • Write a c program to reverse digits of a number
  • Write a c program to reverse a number.

This program first take an integer as input form user, then reverse it’s digits using modulus(%), division(/) and multiplication(*) operator inside loop. After reversing it prints the reversed number. Inside loop, we first get the least significant digit(right most digit) of number using (number % 10) then append it at the end of reverse number. Finally we remove right most digits from number in number = number/10 statement.

C program to reverse digit of a number using loop

Algorithm to reverse digits of a number

  • Get the least significant digit(right most digit) of the number.
    rightDigit = number%10;
  • Append it at the end of reverse number.
    reverse = (reverse * 10) + rightDigit;
  • Remove right most digit from number.
    number = number/10;
  • Repeat this process till number is greater than zero.

This program used while loop, we can similarly use for loop.

C Program to Reverse Digits of a Number

/*
* C Program to reverse the digits of a number
*/
#include <stdio.h>
#include <conio.h>
 
int main(){
    int number, reverse = 0, rightDigit;
    printf("Enter a number \n");
    scanf("%d", &number);
    while(number != 0){
        rightDigit = number % 10;
        reverse = (reverse * 10) + rightDigit;
        number = number/10;
    }    
    printf("Reversed number : %d\n", reverse);
     
    getch();
    return 0;
}

Program Output

Enter a number : 12345
Reversed number : 54321

C program to reverse digits of a number using recursion

Reverse a number: We can use recursion to reverse the digits if a number because it follows recursive sub-problem property.

getReversedNumber(1234) = (4*1000) + getReversedNumber(123)
This program uses a function getReversedNumber which takes a number as input and returns reversed number.
Recursive algorithm to reverse a number

  • N%10 returns the least significant digit of N(354%10 = 4).
  • N/10 return the number after removing least significant digit of N(2345/10 = 234).
  • log10(N) + 1 returns the number of digits in N. log10(N) is logarithm of N with base 10(log10(2311) + = 4).
  • Let getReversedNumber(N) is a function, which returns reverse of N. Then, we can use recursion to reverse the digits if a number using below mention recursive equation.
    • getReversedNumber(N) = (N%10)X pow(10, (log10(N/10) + 1)) + getReversedNumber(N/10)

C program to reverse digits of a number using recursion

/*
* C Program to reverse the digits of a number using recursion
*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
  
int getReversedNumber(int number);
int main(){
    int number, reverse = 0;
    printf("Enter a number :");
    scanf("%d", &number);
    
    reverse = getReversedNumber(number);
    
    printf("Reversed number : %d\n", reverse);
    getch();
    return 0;
}
  
/*
 * Function to reverse the digits of a number
 */
int getReversedNumber(int number){
    int lastDigit, numberOfDigits, sign = 1;
    
    if(number < 0){
        number = number * -1;
        sign = -1;
    }
    if(number < 10)
        return number*sign;
        
    lastDigit = number % 10;
    number = number / 10;
    /* log10(number) + 1 gives number of digits in number */
    numberOfDigits = log10(number) + 1;
    /*
     * for Example: getReversedNumber(1234) = ((4*1000) + getReversedNumber(321))*1
     */
    return (lastDigit*pow(10,numberOfDigits) + getReversedNumber(number)) * sign;
}

Program Output

Enter a number : 23148
Reversed number : 84132