echo '' ;

All posts by Arun

Interview Question – 8051

 

An interview question about the uses of the 8051 microcontroller could assess a candidate’s understanding of embedded systems and their applications.

“Can you discuss some of the common applications of the 8051 microcontroller?”

Read more: Interview Question – 8051

This question invites the candidate to demonstrate their knowledge of the versatility of the 8051 microcontroller and its relevance in various industries. They might mention its use in:

  1. Consumer Electronics: The 8051 has been extensively used in consumer electronics such as television sets, washing machines, microwave ovens, and remote controls due to its low cost and reliability.
  2. Industrial Automation: It plays a crucial role in industrial automation systems for tasks like process control, monitoring, and data logging.
  3. Automotive Electronics: In automotive applications, the 8051 is employed in engine control units (ECUs), airbag systems, anti-lock braking systems (ABS), and dashboard displays.
  4. Medical Devices: Many medical devices utilize the 8051 microcontroller for tasks like patient monitoring, diagnostic equipment, and portable medical devices due to its low power consumption and compact size.
  5. Telecommunications: It’s used in telecommunication equipment for tasks like modems, caller ID systems, and telephone exchange systems.
  6. Security Systems: The 8051 is employed in security systems such as access control systems, surveillance cameras, and alarm systems.
  7. Educational Purposes: It’s widely used in educational institutions for teaching purposes due to its simplicity and availability of learning resources.

By elaborating on these applications, the candidate can demonstrate their understanding of the 8051’s significance in various domains.

8051 Interview Questions

Which technology for develop 8051?

  • CMOS, NMOS



8051 follows which Architecture?

  • Harvard Architechture



Difference Between Harvard Architecture and Von Neumann Architecture?


What is width of the 8051 Data Bus?

  • 8 Bit



What is the width of the 8051 Address Bus

16 Bit address



 How many I/O ports are in 8051 Microcontroller?

Answere Will Add Soon



How many SFRs are in 8051 MicroController?

Answere Will Add Soon



What is DPTR

Answere Will Add Soon



Wat is the capacity of internal RAM and internal ROM?

  • Internal RAM – 256bytes
  • Internal ROM – 64Kbytes



What is the purpose of  PSW register in 8051?

Answere Will Add Soon



What is the purpose of SFR register in 8051?

Answere Will Add Soon



What is the use of EA pin in 8051?

Answere Will Add Soon



NEXT

C Quiz and Interview Questions
Embedded Interview Questions
I2C Interview Question
UART Interview Questions
SPI Interview Questions
ESP8266 Resource
MQTT Interview Questions

8051 – Getting Started with Keil IDE

Keil, a German-based software development company, offers various development tools such as IDE, Project Manager, Simulator, Debugger, C Cross Compiler, Cross Assembler, and Locator/Linker. Evaluation boards are also provided. In this tutorial will discuss “8051 – Getting Started with Keil IDE”

Keil supports various processors and controllers, including ARM Cortex-M, C166, 8051, and 251. It also offers Debug Adapters and Evaluation boards. The tools include C/C++ compilers, integrated development environments, RTOS, middleware, as well as debug adapters. Moreover, Keil provides a comprehensive suite of development resources for embedded system development.

Download Keil IDE Tool : Keil IDE  tool for 8051


How to Create a Project in Keil?

 I chooses AT89S51 micro controller(You can select any other keil support micro controller) and demonstrated, this is very simple and follow this below steps,

Steps to follow

  • Open a Keil Tool
  • In Project select New uVision Project.
  • Select the directory, and enter File_Name in anywhere in your machine, then Save project
  • “Select Device for Target” AT89S51 form Popup window and click OK
  • If popup windows then “Copy STARTUP.A51 to Project Folder and Add File to Project”, then Yes.
  •  Done. You created the project ! 

 How to write a Program in keil ?

Steps to follow

  • Select Source Group 1, Right click and click Add New item to Group ‘Source Group 1’.
  • Select C File(.c), then enter Name “LED_Blink” and Click Add
  • write program in text editor and save
  •  Done! 

 How to Create a Hex file?

Steps to follow

  • Select Options for Target from the Project menu in Target
  • Select the Output tab, Make sure the Create HEX File check box is checked,click OK
Note : Select the proper HEX file format to create (typically this will be HEX-80 for 8051 programs and HEX-386 for large C16x programs).
  • open specified folder and click Objects (after build only you can get this object folder files)
  •  Done!

How to Build a Project in Keil?

Steps to follow

  • Select Build Target(F7) from Project menu.

Go to specified project saved Folder directory

Open specified folder and click Objects

  •  Done!

How Debug program

  1. Start the debugger.
  2. Click on Debug – Go to run the program.
  3. Make sure that View – Periodic Window Update is checked.

NEXT

8051 – Introduction
8051 – Program Methods
8051 – Flash HEX into 8051
8051 – USB ISP Programmer
8051 – Simulators
8051 Interface
8051 Interface – LED
8051 Interface – LCD
8051 Interface – 7 Segment
8051 Interface – Keypad
8051 Interface – Servo
8051 Protocol Interface
8051 – UART Bit banking
8051 – I2C Bit banking (Add Soon)
8051 Tutorials
8051 – 10Khz Square Wave
Others
8051 – Interview Questions

C Library – string.h

The C Library string.h provides various functions for handling strings in C programming. It includes functions for string manipulation, comparison, copying, concatenation, and searching. Some commonly used functions in string.h include strlen() for determining the length of a string, strcpy() for copying strings, strcat() for concatenating strings, and strcmp() for comparing strings. Additionally, string.h provides functions for searching for substrings within a string, such as strchr() and strstr(). The library also offers functions for converting strings to other data types and vice versa, like atoi() and itoa(). Overall, string.h is a crucial part of the C standard library, providing developers with efficient and convenient tools for working with strings in C programs. Its functions are widely used in various applications, from basic string manipulation to complex text processing tasks.

Read more: C Library – string.h

String Understanding

  • String is a collection of characters in between the double quotation “.
  • In C language does not have a data type like string, so we can get this from array of characters.
  • Last character of sting should be null characters ‘/0’.
  • Generally compiler will add the null characters when read a string from computer.
  • Dose not appear null characters ‘/0’ when print the string in computer display.
  • Data length is number of characters in the string with null characters.
  • string handling functions strlen() , strcpy()  , strcat()  , strcmp()  , strrev()  , strupr()   , strlwr()  , strrev()  ,
Read more… →
C Programming Language

C – Preprocessor and Macros

Before learning the C macro, you should know about C preprocessor directives in C language. In this post, you can clearly understand the following

  • what preprocess commands are available in C?
  • How do you declare the preprocessor command.?
  • what is a macro?
  • What is the macro syntax?
  • how to declare the macro?
  • how to assign the macro value?
  • how can use the macro function in c.

Here your answer, if you have any doubts please post in doubts about C Preprocessor and Macros.

Read more… →

Arduino Project – Servo Control Using Accelerometer ADXL345

This article is a continuation of the series on Arduino Project – Servo Control Using Accelerometer ADXL345 and carries the discussion on how to control the motor using the sensor.

Prerequisites

To continue with this tutorial, you must have read the below articles

Components Needed:

  • Arduino IDE (Web or Installed on the machine)
  • PC
  • Servo Motor
  • ADXL345 Accelerometer Sensor
  • Arduino Board (e.g., Arduino Uno)
  • Jumper wires
  • Breadboard

Connection Diagram

Arduino Project Servo Control Using Accelerometer ADXL345
Arduino Project Servo Control Using Accelerometer ADXL345

Wiring

  • Connect the VCC pin of the ADXL345 to the 3.3V pin on the Arduino.
  • Connect the GND pin of the ADXL345 to the GND pin on the Arduino.
  • Connect the SDA pin of the ADXL345 to the A4 pin on the Arduino.
  • Connect the SCL pin of the ADXL345 to the A5 pin on the Arduino.
  • Connect the signal wire of the servo motor to a digital pin on the Arduino (e.g., Pin 5).
  • Connect the power (VCC) and ground (GND) of the servo motor to the corresponding pins on the Arduino.

Arduino Library used List

Arduino libraries are collections of pre-written code that simplify complex tasks and allow users to easily integrate functionality into their Arduino projects. Libraries provide functions and routines that can be used to perform various tasks without the need for users to write the code from scratch. Arduino libraries are written in C or C++ and can be shared and reused by the Arduino community

Code

/* ArunEworld - @2024
Accelerometer connection pins (I2C) to Arduino are shown below:

Arduino     Accelerometer ADXL345
  A5            SCL
  A4            SDA
  3.3V          CS
  3.3V          VCC
  GND           GND
  
Arduino     Servo No. 1
  5V          5V  (Red Wire)
  GND         GND (Black Wire)
  D5          (last wire for control - might be white color)
  
Arduino     Servo No. 2
  5V          5V  (Red Wire)
  GND         GND (Black Wire)
  D6          (last wire for control - might be white color)
*/

#include <Wire.h>
#include <ADXL345.h>

#include <Servo.h>

Servo servo1;  // create servo object to control a servo
Servo servo2;

ADXL345 adxl; //variable adxl is an instance of the ADXL345 library

int x, y, z;
int rawX, rawY, rawZ;
int mappedRawX, mappedRawY;

void setup() {
  Serial.begin(9600);
  adxl.powerOn();
  servo1.attach(5);
  servo2.attach(6);
}

void loop() {
  adxl.readAccel(&x, &y, &z); //read the accelerometer values and store them in variables  x,y,z

  rawX = x - 7;
  rawY = y - 6;
  rawZ = z + 10;
  
  if (rawX < -255) rawX = -255; else if (rawX > 255) rawX = 255;
  if (rawY < -255) rawY = -255; else if (rawY > 255) rawY = 255;
   
  mappedRawX = map(rawX, -255, 255, 0, 180);
  mappedRawY = map(rawY, -255, 255, 0, 180);
  
  servo1.write(mappedRawX);
  delay(15);
  servo2.write(180 - mappedRawY);
  delay(15);
  
  Serial.print(" mappedRawX = "); Serial.print(mappedRawX); // raw data with offset
  Serial.print(" mappedRawY = "); Serial.println(mappedRawY); // raw data with offset
}

Testing

  1. Power up your Arduino board.
  2. Tilt the ADXL345 accelerometer in different directions to observe changes in the accelerometer data on the Serial Monitor.
  3. The servo motor should move in response to the accelerometer data, adjusting its position based on the tilt of the accelerometer.

Troubleshooting

  • If the servo doesn’t move as expected, check the wiring and make sure all connections are secure.
  • Adjust the servo angle mapping and constraints in the code if needed.
  • Ensure that the accelerometer is correctly connected and functioning.

That’s it! You should now have a working setup where the servo motor is controlled based on the tilt data from the ADXL345 accelerometer. Feel free to experiment with the code and make modifications to suit your specific requirements.

NEXT

Arduino-Get Start
Arduino Interface
Arduino Interface-LED
Arduino Interface-Button
Arduino Interface -Buzzer
Arduino Interface-ADC
Arduino Interface-UART(Serial)
Arduino Interface-PWM
Arduino Interface-RGB LED
Arduino Interface-LCD
Arduino Tutorials
Random Number Generator
Voltage Measurement
Arduino Projects
Therimine
Water Flow Meter
Servo Control Using Accelerometer ADXL345
Others
Arduino-Course
Arduino-Sitemap
Arduino-FAQ

Electronics Simulator – Proteus

Proteus is also the name of a popular software suite used for electronic design automation (EDA), particularly for schematic capture, simulation, and PCB (Printed Circuit Board) layout design. It’s widely used by engineers, hobbyists, and students for designing and testing electronic circuits before prototyping or manufacturing them.

Read more: Electronics Simulator – Proteus

Its consists of two main components:

  1. ISIS (Integrated Simulation Integrated Software): This part of this tool allows users to design and simulate electronic circuits using a schematic editor. It supports a wide range of electronic components and provides various simulation capabilities, including DC analysis, AC analysis, transient analysis, and more.
  2. ARES (Advanced Routing and Editing Software): ARES is the PCB layout module of this. It allows users to design PCB layouts for their circuits, including placing components, routing traces, and generating Gerber files for manufacturing.

Its user-friendly interface, extensive component library, and powerful simulation capabilities are known attributes. Educational settings commonly employ it for teaching electronics, while professional environments utilize it for designing and testing complex electronic systems.

Proteus 8.1 Installation

  • Open LICENSE.EXE
  • Browse for key -> Select Key.lxk
  • Install key
  • Close LICENSE.EXE
  • Install V8.1
  • Do not run after installation
  • Copy “BIN” To Instalation Folder (C:\Program Files (x86)\Labcenter Electronics\Proteus 8 Professional)
  • Copy “MODELS” To ProgramData (C:\ProgramData\Labcenter Electronics\Proteus 8 Professional)
  • Note : If you cant see the program data file in system, enable the show hidden files in folder option
  • Run Soft and enjoy!
  • Note : USB VSM Simulation now works. Tested in Windows 8.1 x64.

Uses

Overall, It’s plays a crucial role in the electronics design and development process, offering engineers and designers a powerful platform for designing, simulating, and testing electronic circuits and systems.

  1. Education: Universities, colleges, and technical schools extensively use it for teaching electronics, circuit design, and PCB layout. It provides students with a platform to learn about electronic components, circuit simulation, and PCB design in a hands-on manner.
  2. Electronic Circuit Design: Engineers and designers use this to design and simulate electronic circuits before prototyping or manufacturing them. It allows them to test the functionality of circuits, analyze performance, and identify potential issues early in the design process.
  3. Embedded Systems Development: Its supports simulation of microcontroller-based systems, making it a valuable tool for embedded systems development. Engineers can design and simulate microcontroller circuits, program them using various programming languages (such as C), and simulate the interaction between hardware and software.
  4. Product Prototyping: Its enables designers and engineers to create virtual prototypes of electronic products, including IoT devices, consumer electronics, medical devices, and more. By simulating the behavior of circuits and PCB layouts, they can validate designs, optimize performance, and reduce the time and cost associated with physical prototyping.
  5. Testing and Debugging: Its allows users to perform extensive testing and debugging of electronic circuits and systems. Engineers can simulate different operating conditions, analyze signal integrity, and troubleshoot issues to ensure the reliability and performance of their designs.
  6. Research and Development: Various industries, including aerospace, automotive, telecommunications, and renewable energy, actively utilize it in research and development projects. Researchers rely on its simulation capabilities to explore new technologies, develop innovative solutions, and validate theoretical concepts.

Electronic Devices – Capacitor

A capacitor consists of two conducting plates separated by an insulating medium. It can store electric charges, in the form of voltage in electric field. That blocks direct current. This opposes any sudden change of voltage applied to it. That only allows the Alternating current. That makes the time delay

C=Ԑ o Ԑr A / d farad A=area of each plate in m2,

  • d=distance between the plates in meter, Ԑr =relative dielectric constant(permittivity).
  • Ԑ o=dielectric constant(permittivity)of free space,
Read more… →
C Programming Language

C – Operators

Arithmetic +, -, *, /, %
Assignment=
Augmented Assignment+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Bitwise Logic~, &, |, ^
Bitwise Shifts<<, >>
Boolean Logic!, &&, ||
Conditional Evaluation: ? :
Equality Testing==, !=
calling functions( ) (function) -Every function has a pair of parentheses ()

 
main() – main is a function. Every function has a pair of parentheses (). Can a program be compiled without main() function?: Yes, it can be but cannot be executed, as the execution requires main() function definition.
increment and decrement++, —
member selection., ->
object sizesizeof
Order relations<, <=, >, >=
reference and dereference& (Address of Operator) – It cannot be used on constants. It cannot be used on a variable that is declared using the register storage class.

, *, [ ]
sequencing,
subexpression grouping( )
type conversion(typename)
Semicolon; (Semicolon) Any C statement always ends with a ;

Arithmetic OperatorsUnary Operators

Binary Operators
Unary Operators – Eg: +5 , -8 .

Binary Operators
X = 5+6; (Addition + Operator)
X = 20-10; (Subraction – Operator
X = 5*3; (Multiplication * Operator)
X = 5/3; (Division / Operator)
X = 5%3; (Modular % Operator) -remainder
Relational OperatorsA>B; (Greater than)
A<B; (lesser than)
A>=B; (Greater than equal to)
A<=B; (Lesser than equal to)
A==B; (equal to)
A!=B; (not equal to)
Logical OperatorA && B; (AND)
A || B; (OR)
!A=A; (NOT)
Increment and Decrements OperatorsIncrement Operator
++x; (pre increments)
x++; (post increments)

Decrements Operator
–x; (pre Decrements)
x–; (post Decrements)
S++; // ++, as it is single machine instruction (INC) internally.(recommended)
S = S+1; // ++, as it wil take two machine cycle internally.(not recommended)
Short hand assignment Operators
conditional operators (Ternary Operator)

C program structure model explanation

main() -functionmain() – main is a function. Every function has a pair of parentheses ()
Can a program be compiled without main() function?
Yes, it can be but cannot be executed, as the execution requires main() function definition.
{} scope or block
A local block is any portion of a C program that is enclosed by the left brace { and the right brace } .
anything between the two braces is contained in a local block.
() function() – function -Every function has a pair of parentheses ()
semicolon : ; Any C statement always ends with a ;
, Comma OperatorComma Operator – can be used to separate two or more expressions
Eg: printf(“hi”) , printf(“Hello”);
& Address of Operator Address of Operator – It cannot be used on constants. It cannot be used on a variable that is declared using the register storage class.

Incremental and Decremental Operators

  • S++; // ++, as it is single machine instruction (INC) internally.(recommended)
  • S = S+1; // ++, as it wil take two machine cycle internally.(not recommended)
Increment OperatorDecrements Operator
++x (pre increments)–x (pre Decrements)
x++ (post increments)x– (post Decrements)

Example:

Code:

#include<stdio.h>
int main()
{
	int a=5, b=6;
	printf("A : %d \n", a);
	printf("B : %d \n\n", b);
	int c = a++ + ++b;
	printf("A : %d \n", a);
	printf("B : %d \n\n", b);

	printf("C : %d \n", c);
	printf("A : %d \n", a);
	printf("C : %d \n", c);
	return 0;
}

Output:

A : 5
B : 6
A : 6
B : 7
C : 12
A : 6
B : 7


Relational Operator

Code-1:

#include <stdio.h>

int main()
{
	int y;
	int x = y ==10; //int x = y == y; or int x = y ;  
	printf("%d",x);
	
	return 0;
}


//Output : 0

Code-2:

#include<stdlib.h>
 
int main()
{
	int x =10;
	x ==10;
	printf("%d",x);
      return 0;
}
//Output : 1

Boolean Operator

  • == Equal
  • != Not equal
  • > Greater than
  • >= Greater than or equal
  • < Less than
  • <= Less than or equal
  • && Logical AND
  • || Logical OR
  • ! Logical NOT

Conditional operators (Ternary Operator)

syntax : expression 1 ? expression 2 : expression 3;

  • Rule
    • if expression 1 is true then expression 2 is executed
    • else expression 1 is false then expression 3 is executed
  • Advantage : Using ?: reduce the number of line codes and improve the performance of application.
  • Example Invalid:In this below example this is an error in this line i>45? return(*P): return (*q); We cannot use return keyword in the terenary operators.
    #include<stdio.h>
    int check (int, int);
    
    int main()
    {
        int c;
        c = check(10, 20);
        printf("c=%d\n", c);
        return 0;
    }
    int check(int i, int j)
    {
        int *p, *q;
        p=&i;
        q=&j;
        i>=45 ? return(*p): return(*q);
    }

  • Example Valid : In this below example a is lesser than b . so the b value
    a= 5;
    b=7;
    a>b?a:b;
  • More examples :
    • Find largest number among 3 numbers using ternary operator

Associativity

Associativity is only needed when the operators in an expression have the same precedence. Usually + and – have the same precedence.

Consider the expression 7 – 4 + 2. The result could be either (7 – 4) + 2 = 5 or 7 – (4 + 2) = 1. The former result corresponds to the case when + and – are left-associative, the latter to when + and – are right-associative.

Usually, the addition, subtraction, multiplication, and division operators are left-associative, while the exponentiation, assignment, and conditional operators are right-associative. To prevent cases where operands would be associated with two operators or no operator at all, operators with the same precedence must have the same associativity.

BIT Operations

Bit OperationsOperator usageExample
Set bitUse the bitwise OR operator (|)aew_value = aew_value | 1<< set_bit
Clear BitUse the bitwise AND operator (&) and NOT operator (~).aew_value = aew_value & (~(1<< set_bit)
Toggle BitUse the XOR operator (^)Use the bitwise AND operator (&) and NOT operator (~).

How do find the status of a particular bit is SET or NOT?

#include <stdio.h>

int main(void)
{
  //How to find the status of a particular bit is SET or NOT?
    int value = 5;
    int n = 2;
    if (value & (1 << (n - 1)))
        printf("SET");
    else
        printf("NOT SET");

    return 0;
}

Print the Multiplication of the given N number?

#include <stdio.h>
#define N 4
int main()
{
    
    printf("Method-1: 1*%d = %d\n",N,(N));
    printf("Method-1: 2*%d = %d\n",N,(N<<1));
    printf("Method-1: 3*%d = %d\n",N,(N<<1)+N);
    printf("Method-2: 3*%d = %d\n",N,(N<<2)-N);
    printf("Method-1: 4*%d = %d\n",N,(N<<2));
    printf("Method-1: 5*%d = %d\n",N,(N<<2)+N);
    printf("Method-1: 8*%d = %d\n",N,(N<<3));
    printf("Method-1: 9*%d = %d\n",N,(N<<3)+N);
    printf("Method-1: 10*%d = %d\n",N,(N<<3)+(N<<1));
    printf("Method-1: 15*%d = %d\n",N,(N<<4)-N);
    printf("Method-1: 16*%d = %d\n",N,(N<<4));
    printf("Method-1: 40*%d = %d\n",N,(N<<5)+(N<<3));
    return 0;
}

OutPut

Method-1: 1*4 = 4
Method-1: 2*4 = 8
Method-1: 3*4 = 12
Method-2: 3*4 = 12
Method-1: 4*4 = 16
Method-1: 5*4 = 20
Method-1: 8*4 = 32
Method-1: 9*4 = 36
Method-1: 10*4 = 40
Method-1: 15*4 = 60
Method-1: 16*4 = 64
Method-1: 40*4 = 160


...Program finished with exit code 0
Press ENTER to exit console.

NEXT

C - Basic
C - Operator
C - Decision making, Branching, Looping
C - Functions
C - Storage Class
C - Extern
C - Array
C - Pointer
C - Memory Allocation
C - Structure
C - Union
C - Structure and Union
C - Macros
C – Preprocessor and Macros
C - File Management
C - Coding Standard
C - Compilers
C - Compiling Process
C File Management
C Library
C Example

C Programming Language

C – Decision Making Branching Looping

This article will discuss “Decision Making Branching Looping in C program”.

Decision Making: This involves using conditions to make choices in code. For example, using an “if” statement to check if a certain condition is true or false, and then executing different blocks of code accordingly.

Branching: Branching is an extension of decision making. It involves creating multiple paths or branches in your code based on different conditions. This often includes using “else if” statements.

Looping: Looping allows you to repeat a certain block of code multiple times. There are different types of loops, but two common ones are “for” and “while” loops.

Read more… →

C Examples – Bitwise Operators

C Bitwise Operators (Can only be used on integrals, no floats, and doubles)

C BitWise Logic Operator

  • & AND
  • | OR
  • ^ XOR
  • ~ ONE’S COMPLEMENT (Unary Operator)
  •  

& AND

x = 193;            /*1100 0001*/
y = x & 0xf0;        /*1111 0000*/
y = 192;            /*1100 0000*/

| OR

x = 193;            /*1100 0001*/
y = x | 0xf0;        /*1111 0000*/
y = 241;            /*1111 0001*/

^ XOR

x = 193;            /*1100 0001*/
y = x ^ 0xf0;        /*1111 0000*/
y = 62;                /*0011 0001*/

~ ONE’S COMPLEMENT (Unary Operator)

x = 193;            /*1100 0001*/
y = ~x;                /*0011 1110*/
y = 62;                /*0011 1110*

Bit-wise Shift

  • << LEFT SHIFT
    x = 193; /*1100 0001*/
    y = x << 2;
    y = 4; /*0000 0100*/
  • >> RIGHT SHIFT
    x = 193;            /*1100 0001*/
    y = x >> 2;
    y = 48;                /*0011 0000*/
  • Example : A = 0101 1000 >>1 Output : 000010000 .
  • Reference Videos:
    1. https://www.youtube.com/watch?v=d0AwjSpNXR
  1. Special Operators


Exercise in C bitwise operators

1) Which is not a bit-wise operator?

  1. &
  2. |
  3. <<
  4. &&

Ans : 4


2) Predict the output of following program.

#include <stdio.h>
int main()
{
    int a=10;
    int b=2;
    int c;
    
    c=(a & b);
    printf("c= %d",c);
    return 0;
}
  1. c= 12   
  2. c= 10
  3. c= 2
  4. c= 0

Correct answer: 3
c= 2

Bitwise AND (&) operator copies bit(s), if they are exist both of the operands. Here, binary of a is “1010” and binary of b is “0010”. Thus, result of expression (a & b) is “0010” which is equivalent to 2 in Decimal.


3) Predict the output of following program.

#include <stdio.h>

#define MOBILE  0x01
#define LAPPY   0x02

int main()
{
    unsigned char  item=0x00;

    item |=MOBILE;
    item |=LAPPY;

    printf("I have purchased ...:");
    if(item & MOBILE){
        printf("Mobile, ");
    }
    if(item & LAPPY){
        printf("Lappy");
    }

    return 1;
}
  1. I have purchased …:
  2. I have purchased …:Mobile, Lappy
  3. I have purchased …:Mobile,
  4. I have purchased …:Lappy

Correct answer: 2
I have purchased …:Mobile, Lappy

Bitwise OR (|) operator copies bit(s), if they are exist either side of the operands (that means if any bit is exist in any operand). Here, binary of Macro MOBILE (0x01) is “0001” and binary of Macro LAPPY (0x02) is “0010”, then result of the expression item |=MOBILE; will be “0001” and second expression item |=LAPPY; will return “0011”. Thus, both conditions (item & MOBILE) and (item & LAPPY) will be true.


4) Predict the output of following program.

#include <stdio.h>

int main()
{
    char var=0x04;

    var = var | 0x04;
    printf("%d,",var);
    var |= 0x01;
    printf("%d",var);
    
    return 0;
}
  1. 8,9
  2. 4,5   
  3. 8,8
  4. 4,4

Correct answer: 2
4,5

Value of var is 0x04 (0100), Consider the expression var = var | 0x04 The OR (|) of 0100, 0100 is 0100, hence value will remain 0100. After the expression var |=0x01, value will be 0101 that is 0x05.


5) Predict the output of following program.

#include <stdio.h>

int main()
{
    char flag=0x0f;

    flag &= ~0x02;
    printf("%d",flag);

    return 0;
}
  1. 13
  2. d
  3. 22
  4. 10

Correct answer: 1
13

Consider the expression flag &= ~0x02 => flag = flag & (~0x02) => flag = 0x0f & (~0x02) => flag = D => flag =13.


6) Consider the given statement:

int x = 10 ^ 2What will be the value of x?

  1. 5
  2. 6
  3. 7
  4. 8

Correct answer: 4
8

XOR operator (^) copies bit(s), if one operand has 1 and other has 0, consider the given truth table:

a       b       (a^b)
_______________________

0       0       0
0       1       1
1       0       1
1       1       0

Here, binary of 10 is “1010” and binary of 2 is “0010”, then the result of statement (10 ^ 2) will be “1000”, which is equivalent to 8 in decimal.


7) Predict the output of following program.

#include <stdio.h>

int main()
{
    int x=10;
    
    x &= ~2;
    printf("x= %d",x);
    
    return 0;
}
  1. x= 10
  2. x= 8
  3. x= 12
  4. x= 0

Correct answer: 2
x= 8

The statement x &= ~2; will clear second bit from the value of 10, binary of x is “1010” and the binary of 2 is “0010”, thus this statement will clear second bit and returns “1000” that is equivalent to 8 in Decimal.


8) Which Bitwise Operator can be used to check whether a number is EVEN or ODD quickly?

  1. Bitwise AND (&)   
  2. Bitwise OR (|)
  3. Bitwise XOR (^)
  4. Bitwise NOT (~)

Correct answer: 1
Bitwise AND (&)

Bitwise AND (&) Operator can be used to check whether a number if EVEN or ODD, consider the statement (num & 1), this statement will return 1 if first bit of the number is High (1) else it will return 0. All ODD numbers have their firs bit 1 and ODD numbers have 0.

Consider the following program:

#include <stdio.h>

int main()
{
    int count;
    
    for(count=1; count<=10; count+=1)
        if(count & 1)
            printf("%2d is ODD number\n",count);
        else
            printf("%2d is EVEN number\n",count);
    
    return 0;
}

Output

 1 is ODD number
 2 is EVEN number
 3 is ODD number
 4 is EVEN number
 5 is ODD number
 6 is EVEN number
 7 is ODD number
 8 is EVEN number
 9 is ODD number
10 is EVEN number

9) Which statement is suitable to check 3rd (count from 0) bit is high (set) or not?

  1. (num & (1<<3))
  2. (num & 0x08)
  3. (num & 0x03)
  4. Both (1) and (2)

Correct answer: 4
Both (1) and (2)

The value of (1<<3) is 8 in Decimal and value of 0x08 is 8 in Decimal, both statements are suitable to check whether 3rd bit of num is High (set) or not.

Consider this program:

#include <stdio.h>

int main()
{
    int num;
    
    printf("Enter an integer number: ");
    scanf("%d",&num);
    
    if(num & (1<<3))
        printf("3rd bit is High (Set)\n");
    else
        printf("3rd bit is Low\n");
        
    return 0;
}

Output

First run:
Enter an integer number: 15 
3rd bit is High (Set) 

Second run:
Enter an integer number: 7
3rd bit is Low

Binary of 15 is: 1111 & Binary of 7 is: 0111, thus in first case 3rd bit is high and in second case 3rd bit is low. [Count from 0]


10) Left shift (<<) and Right shift (>>) operators are equivalent to _____________ by 2.

Choose the correct words…

  1. Multiplication and Division
  2. Division and Multiplication
  3. Multiplication and Remainder
  4. Remainder and Multiplication

Correct answer: 1
Multiplication and Division

Left shift by 1 return the multiplication by 2 and Right shift by 1 return the division by 2.

Consider this program:

#include <stdio.h>

int main()
{
    int num;
    
    printf("Enter an integer number: ");
    scanf("%d",&num);
    
    printf("Multiplication by 2 = %d\n", (num<<1));
    printf("Division by 2 = %d\n",(num>>1));
        
    return 0;
}

Output

Enter an integer number: 100
Multiplication by 2 = 200 
Division by 2 = 50


NEXT of C Bitwise Operators

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example

C – Union

In this post, you can learn about what a C union is, its syntax, how to declare a union, and how to initialize union members. If you have any doubts, feel free to mention them in the comments section.

Introduction

union is a keyword, used to create a structure like struct keyword. When we declare a union, memory allocated for a union variable of the type is equal to the memory needed for the largest member of it, and all members share this same memory space

Read more: C – Union

Syntax

union union_name 
{
    data_type_1 member_1;
    data_type_2 member_2; 
};

Declaration :

union union_name 
{
    data_type_1 member_1;
    data_type_2 member_2;
}uv_1,uv_2;

Example-1: C Union Understanding

Predict the output of the above program. Assuming an integer size of 4 bytes and a character size of 1 byte, and no alignment needed.

union test
{
    int x;
    char arr[4];
    int y;
};
 
int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s", t.arr);
    return 0;
}

The answer is that “nothing is printed”.

Explanation:

StatementExplanation
union test t;Declares a union variable t of type test.
t.x = 0;Sets the value of x member of union t to 0.
t.arr[1] = 'G';Assigns the character ‘G’ to the second element of the arr member array.
printf("%s", t.arr);Prints the string stored in the arr member of union t.
return 0;Indicates successful termination of the program.

Uses of unions in C

Unions offer versatility and efficiency in memory usage and data representation in C programming.

Use CaseDescription
Memory ConservationUnions allow multiple members to share the same memory location, conserving memory when only one member is needed.
Type ConversionUnions facilitate type punning, enabling conversion between different data types or accessing the same memory location with different interpretations.
Handling Variant DataUnions are suitable for representing variant data structures where different members represent different data types, but only one member is valid at a time.
Bit ManipulationUnions can be used for bit manipulation and manipulation of individual bits within larger data types.
Implementing Tagged UnionsTagged unions combine a discriminant (a tag) with a union, allowing the representation of values from different types while keeping track of their type.
Optimizing Memory LayoutUnions can optimize memory layout in structures by grouping related data fields together, especially when only one field is needed at a time.

Advantages and disadvantages of unions in C

Unions offer flexibility and efficiency in certain scenarios but require careful usage to avoid pitfalls such as type-related bugs and undefined behavior.

AdvantageDisadvantage
Memory ConservationLimited Type Safety: Unions can lead to type-related bugs if not used carefully.
Type ConversionPotential for Misuse: Unions can be misused, leading to undefined behavior.
Handling Variant DataComplex Initialization: Initializing unions with complex types can be challenging.
Bit ManipulationLimited Readability: Code using unions for bit manipulation may be less readable.
Implementing Tagged UnionsAdditional Bookkeeping: Tagged unions may require additional code to manage tags.
Optimizing Memory LayoutPotential for Undefined Behavior: Accessing inactive union members may result in undefined behavior.

Interview questions

These questions cover various aspects of unions in C and can help assess a candidate’s understanding of this concept during an interview.

  1. What is a union in C?
  2. How is a union different from a structure?
  3. How do you declare a union in C?
  4. Can a union contain members of different data types?
  5. What is the size of a union in C?
  6. How do you access members of a union?
  7. What is type punning in the context of unions?
  8. What are the advantages of using unions?
  9. Can you explain the concept of memory conservation using unions?
  10. How do unions facilitate type conversion?
  11. What are the potential pitfalls of using unions?
  12. Can you provide an example of using unions in a real-world scenario?
  13. How does the compiler handle memory allocation for unions?
  14. Can a union have functions as members?
  15. What is the utility of tagged unions and how are they beneficial?

NEXT

C Programming Language

C – Structure

C Structure is the group of heterogeneous data structure which can store data of different data types or Structure is a collection of variables of different types under a single name. 

In the case of array, we can store the data of same data type but what if we have to save data of different data type in structure. Can use single structure name for  more type of data in structure and union. Storage area is not reserved by the compiler to structure definition.

  • Keyword struct  is used for creating a structure.
  • Structure is a user defined data structure.

C Structure Syntax

struct tag_filed_name 
{
    data_type_1 member_1;
    data_type_2 member_2
    .
    .
    .
    data_type_N member_N
}

How to create a structure?

‘struct keyword is used to create a structure. Following is an example.

struct address
{
   char name[50];
   char street[100];
   char city[50];
   char state[20];
   int pin;
};

Rules

  • Use declare semicolon };at end of structure. (Don’t forget the semicolon in  the ending line.)
  • Referencing structure members : struct_var-name . member_variable
  • A structure variable can be assigned to other using =, but cannot be compared with other using ==
  • In Structure bit cant set in float variable.
  • Bit-fields are only part of structs or unions because that’s what the C standard allows

static members can’t allowed in structure

  • In C, struct and union types, we cannot have static members.
  • In C++, struct types are allowed to have static members, but in union cannot have static members in C++ also.
  • The Below C program output is compilation error.
#include<stdio.h>
struct st
{
    int x;
    static int y;
};
 
int main()
{
    printf("%d", sizeof(struct st));
    return 0;
}

How to declare structure variables?

Way 1:

struct struct_name
{
    data_type member_1;
    data_type member_2;
}var_1, var_2;

Way 2 : struct struct_name var_1, var_2;

struct struct_name
 var_1, var_2;

How to initialize structure members?

Note: Structure elements cannot be initialized. When we declare a structure or union, we actually declare a new data type suitable for our purpose. By default, structure member init with a NULL value. It means Zero.

static struct structure_name var-name = 
{
        var_1, var_2,...var_n
};

So we cannot initialize values as it is not a variable declaration but a data type declaration. The below program output is Compilation error.

#include‹stdio.h›
int main()
{
    struct site
    {
        char name[] = "ArunEworld";
        int no_of_pages = 20;
    };
    struct site *ptr;
    printf("%d ", ptr->no_of_pages);
    printf("%s", ptr->name);
    getchar();
    return 0;
}

In a school, we need to store data like name, roll no, address and percentage. But we are able to store only one data type at a time. So, C programming provides a structure data type that can store data of different types such as integer, float, character, etc. In the case of the above school, we can initialize structure as (refer below example)

struct info
{
    char name [10];
    int roll_no;
    char address [10];
    float per;
};

Read/write in Structure variables

  • . (colon) is the member of a structure
  • -> (arrow) is the member of a POINTED TO structure
  • x -> y and (*x).y are both the same

When to user ->  (arrow) operator.?

  • When the structure/union variable is a pointer variable, we use the arrow operator to access structure/union elements.

What is a self-referential structure?

  • We call a structure containing the same structure pointer variable as its element a self-referential structure.

Nested structure [structure with structure]

  • We refer to a structure containing an element of another structure as its member.

Example : School Data Base

The below example explains many things about the structure

  • This below code is the best example for structure array.
/*********************************
Date: 2016-06-04
Authur: Arun
********************************/

#include <stdio.h>
#include <stdint.h>

//The structure used to store the school student details
typedef struct student_Details
{
    uint8_t     Roll_no; 
    const char* studnt_Name;
    uint8_t    Tamil;
    uint8_t    English;
    uint8_t    Maths;
    uint8_t    Science;
    uint8_t    SocialScience;
    
}student_Details;

// Already declared structure can initialize, throw here.
static student_Details Entry[]=
{
  {1, "Arun", 0, 0, 0, 0, 0},
  {2, "Jhon", 0, 0, 0, 0, 0},
  {3, "Raja", 0, 0, 0, 0, 0},
  {4, "Gaurav", 0, 0, 0, 0, 0},
  {5, "Smith", 0, 0, 0, 0, 0},
  {6, "Jothi", 0, 0, 0, 0, 0},
};


//Printing the structure array
void printStudentDetails()
{
    printf("\n\r Total No of stundets : %ld", sizeof(Entry)/sizeof(student_Details));
    
    uint8_t i=0, No_of_students = sizeof(Entry)/sizeof(student_Details);
    
    printf("\n _________________________________________________________");
    printf("\n | ID | Name \t | S1 \t | S2 \t| S3 \t| S4 \t| S5 \t |");
    printf("\n _________________________________________________________");
    while(No_of_students != i)
    {
        printf("\n\r | %d | %s \t | %d \t | %d \t | %d \t | %d \t | %d \t | ",
        Entry[i].Roll_no, 
        Entry[i].studnt_Name, 
        Entry[i].Tamil,
        Entry[i].English,
        Entry[i].Maths,
        Entry[i].Science,
        Entry[i].SocialScience);
        
        i++;
    }
    printf("\n _________________________________________________________");
}

void UpdateStudentRecord(int Rn,int Sb, int Mrk)
{
    if(Sb == 1)     Entry[Rn-1].Tamil= Mrk;
    else if(Sb == 2) Entry[Rn-1].English= Mrk;
    else if(Sb == 3) Entry[Rn-1].Maths= Mrk;
    else if(Sb == 4) Entry[Rn-1].Science= Mrk;
    else if(Sb == 5) Entry[Rn-1].SocialScience= Mrk;
}

void PrintHelperMenu()
{
    printf("\n helper Menu ");
    printf("\n 1 - Print Student record");
    printf("\n 2 - Update the Student Only One subject mark Mark");
}

void helperMenu()
{
    int scanValue;
    
    PrintHelperMenu();
    
    while(1)
    {
        printf("\n");
        
        scanf("%d",&scanValue);
        
        if(scanValue == 2 )
        {
            int Rn,Sb,Mrk;
            
            printf("\n 1 - Tamil, 2 - English, 3 - Maths, 4 - Science, 5 - Social Science.");
            
            printf("\n Enter the Roll No, Subject and Mark : ");
            
            scanf("%d%d%d",&Rn, &Sb, &Mrk);
            
            UpdateStudentRecord(Rn,Sb,Mrk);
            
            printStudentDetails();
            
            PrintHelperMenu();
        }
        else if( scanValue == 1)
        {
            printStudentDetails();
            
            PrintHelperMenu();
        }
    }
}

int main()
{
    helperMenu();
    return 0;
}

Structure Padding

During struct memory allocation, the system adds empty bytes based on the controller/processor type (8/16/32/64 bit), which can lead to memory issues when working with large arrays of data.

Structure Packing

Reduce the amount of memory that your application requires by packing data into structures. This is especially important if you need to store and access large arrays of data.

pack() function can be use to packing the structure memory.

  • Syntax: #pragma pack(parameters)
  • Parameters: 1 – Aligns structure members on 1-byte boundaries, or on their natural alignment boundary, whichever is less.
  • Parameters: 2 – Aligns structure members on 2-byte boundaries, or on their natural alignment boundary, whichever is less.
  • Parameters: 4 – Aligns structure members on 4-byte boundaries, or on their natural alignment boundary, whichever is less.
  • Parameters: 8 – Reserved for possible future use.
  • Parameters: 16 – Reserved for possible future use.

  • Pack() function : Reference Link
  • Reference Link


C Programming Language

C – Memory Allocation

Memory allocation in C refers to the process of reserving memory space during the execution of a program for storing variables or data structures. There are mainly two types of memory allocation in C: stack allocation and heap allocation.

Stack Allocation:

  • Stack allocation is the default method for allocating memory for local variables within functions.
  • Memory allocated on the stack is automatically managed by the compiler.
  • Variables allocated on the stack have a fixed size and are deallocated when they go out of scope, typically when the function exits.
  • Stack memory is limited and generally smaller than heap memory.

Heap Allocation:

  • Heap allocation involves dynamically allocating memory during runtime from the heap, which is a larger pool of memory managed by the operating system.
  • Memory allocated on the heap must be explicitly requested and released by the programmer using functions like malloc(), calloc(), realloc(), and free().
  • Heap memory allows for dynamic data structures like linked lists, trees, and dynamic arrays.
  • Improper use of heap memory can lead to memory leaks or memory fragmentation.

Common memory allocation functions in C:

  • malloc(size_t size): Allocates a block of memory of specified size in bytes and returns a pointer to the allocated memory.
  • calloc(size_t num, size_t size): Allocates an array of elements initialized to zero, with the total size equal to num * size bytes, and returns a pointer to the allocated memory.
  • realloc(void* ptr, size_t size): Resizes the previously allocated memory block pointed to by ptr to the new size specified by size. It may move the memory block to a new location, and the contents of the original block may be copied to the new block.
  • free(void* ptr): Releases the memory block previously allocated by malloc, calloc, or realloc.

Proper memory management is crucial in C programming to prevent memory leaks, segmentation faults, and other memory-related issues. It’s essential to allocate memory dynamically only when necessary and deallocate it when no longer needed to ensure efficient memory usage.

Static Memory allocation

In the case of static memory allocation, memory is allocated at compile time and memory can’t be increased while executing the program. It is used in the array

Dynamic memory allocation

In the case of dynamic memory allocation, memory is allocated at run time and memory can be increased while executing the program. It is used in the linked list.

The following functions are used in Dynamic memory allocation

  • malloc() – allocates a single block of requested memory. It has garbage value initially.
  • calloc()  – allocates multiple blocks of requested memory. It initially initializes all bytes to zero.
  • realloc() – reallocates the memory occupied by malloc()  or calloc()  functions.
  • free()      – free the dynamically allocated memory.


Stack grows upwards or downwards

Write a C code to check whether a stack grows upwards or downwards

void main()
{
	int i=2;
	int j=3;
	
	if(&i > &j)
	{
		printf("stack grown downwards");
	}
	else
	{
		printf("stack grows upwards");
	}
}


Memory Layout & Storage Type understanding

char *getString()
{
   char *str = "Nice test for strings";
   return str;
}
 
int main()
{
   printf("%s", getString());
   getchar();
   return 0;
}

Output: “Nice test for strings”
Explanations:

  • The above program works because string constants are stored in Data Section (not in Stack Section). So, when getString returns *str is not lost.
  • string constants are stored in Data Section (not in Stack Section)
  • static variable and is stored in Data Section,
  • array variables are stored in Stack Section

C – Pointers

A C pointers is a variable that holds the memory address of another variable. Pointer variables are declared using the * operator, and they can point to various data types, including integers, characters, arrays, structures, and even other pointers. Manipulating pointers requires careful handling to avoid issues like memory leaks, dangling pointers, and segmentation faults.

  • int a; // An integer
  • int *a; //A pointer to an integer
  • int **a; //A pointer to a pointer to an integer
  • int a[10]; //An array of 10 integers
  • int *a[10]; //An array of 10 pointers to integers
  • int (a)[10]; //A pointer to an array of 1 integers
  • int (a)(int); //A pointer to a function a that take an integer argument and return an integer
  • int (*a[10]){int); //An array of 10 pointers to functions that take an integer argument and return an integer

Pointer

A pointer is a variable capable of holding the address of another variable. Dereferencing, accomplished with the (*) operator, allows accessing the value of the variable.

  • Syntax : Datatype * variable name ;
  • Syntax example : int *p;
  • Rule : That two variables should be same data type.

Example

Int x=10;

Int *p=&x;

(Or)

Int *p;

p=&x;
  • To access the value of x : printf(“%d ”,p); —> value of x is 10 Or printf(“%d”,(&x)) —->value of x is 10
  • To access addres of x: printf(“%d”,p); —–> address of x is printed Or printf(“%d”,&x);——> address of x
Read more… →
C Programming Language

C – Array

It is very difficult to define more variables’ names when using more data.  So can create a array to solve this difficult(single variable name and more data). If the index of the array size is exceeded, the program will crash. But the modern compilers will take care of this kind of errors. We cannot initialize the size of array dynamically. Constant expression is required. This tutorial about “C Array”

Array Rules

  • only store the same data types in array structures
  • Arrays are always passed by reference
  • Array list should be end expression with semicolon  ; . Otherwise it will show the error.
  •  
  • What is Base address of array??  Eg : a[10] = {0,1,2,3,4,5,6,7,8,9};     // The starting address of the array is called as the base address of the array. Consider the address of the array starts from 101. Here the variable 0(Zero) address is the base address and the base address of the array is 101.
  • When we pass an array as a function argument, the base address of the array will be passed.
  • Array three types
    1. One Dimensional Array
    2. Two Dimensional Array and
    3.  Multi Dimensional Array

One Dimensional Array

When declare one index value is called One dimensional array

Syntax: 

data_type array_name [ size];

  • data_type  – What kind of array data type
  • array_name  – name of the array
  • size  – array size

Syntax Declaration:

  • int a[100];  //Data type- int (2Byte), array_name – ‘a’, size – 100, Memory Occupies- 200 byte (100×2).
  • float s [50];  //Data type- float(4byte), array_name – ‘s’, size – 50, Memory Occupies- 200 byte (50×4).
  • char name[15];  // Data type- char(1byte), array_name – “name”, size – 15, Memory Occupies- 15 byte (15×1).

Declaration : int a[100];

  • Reading : for(i=0; i<100; i++) scanf(“%d”, &a[i]);
  • Writing : for(i=0; i<100; i++) printf(“%d”, a[i]);
  • Memory Representation :

Array initialization Syntax :

Synatx:  data_type array_name [size] = {list_of_values}; 

Examples

  • static int age [3] = {10,20,30};  //its means – a[0]=10; a[1]=20; a[3]=30;
  • static float salary[] = {1000,2200,3300};  //salary[0]=1000; salary[2]=3300;
  • static char a[10] = “ArunEworld”;  //its means – a[0]=’A’; a[1]=’r’; like… a[9]=’d’;

Array initialization with Zero:

When an automatic array is partially initialized, the remaining elements are initialized to 0.

Example-1:

#include<stdio.h>
int main()
{
    int awe[2];
    printf("%d, %d, %d, %d, %d, %d, %d, %d\n", awe[0], awe[1], awe[2], awe[3], awe[4], awe[5], awe[6], awe[7]);
    return 0;
}

/* Output:     0, 0, 0, 0, -467742907, 32525, 0, 0 */

Example-2:

#include<stdio.h>
int main()
{
    int awe[3]={1,2,3};
    printf("%d, %d, %d, %d, %d, %d, %d, %d\n", awe[0], awe[1], awe[2], awe[3], awe[4], awe[5], awe[6], awe[7]);
    return 0;
}

/* Output:     1, 2, 3, 0, 0, -2036674747, 32587, 0 */

Accessing the Array Element

#include<stdio.h>

int main()
{
    int arr_aew[2]={10,2};
    printf("%d\n", 1[arr_aew]);
    return 0;
}

/* Output: 2 */

Other Example Programs

Check this below examples list in this Links

  • C program to Find Smallest & Largest Number of N numbers in Array.c
  • C program to Ascending Order of N numbers in Array.c
  • C program to Descending Order of N numbers in Array.c
  • C program to fine Largest Number and Position of N numbers in Array.c
  • C program to Find Mean and Standard Deviation in Array Element.c

Two Dimensional Array

  • When declare two index value is called two dimensional array
  • Two dimensional arrays can consider as a table. size_1 is row size and size_2 is column size.

Syntax: data_type array_name [ size_1] [size_2];

    • data_type  – What kind of array data type
    • array_name  – name of the array
    • size_1 , size_2 – two dimensional array size

Syntax Declaration:

    • int a[100] [20];  //Data type- int (2Byte), array_name – ‘a’, size_1(row) – 100,size_2(column)-20, Memory Occupies- 200 byte (100×2).

Declaration : int a[10][15];

Reading : for(i=0; i<10; i++) for(j=0; j<15; j++) scanf(“%d”, &a[i][j]); 

Writing : for(i=0; i<10; i++) for(j=0; j<15; j++) printf(“%d”, a[i][j]); 

  • Memory Representation :

Array initialization Syntax : data_type array_name [size_1] [size_2] = {v1, v2,…..vn}; 

Examples

  • static int mark[3][2] = {60,70,80, 35,90,18};  //its means – a[0][0]=60; a[0][1]=70; a[0][3]=30; a[1][0]=35; a[1][1]=90; a[1][2]=18;
  • static mark[3][2] = {{50},{0},{35};  //a[0][0]=50; a[0][1]=50; a[0][3]=0; a[1][0]=0; a[1][1]=35; a[1][2]=35;

Example Programs

  • Two_dimensional_array_read_row_column.c
  • Two_dimensional_array_print_row_column.c
  • Matrix_transpose_using_two_dimensional_array.c
  • Diagonal_elements_using_two_dimensional_array.c
  • Sum_of_diagonal_elements_using_two_dimensional_array.c
  • Sum_of_all_matrix_elements_using_two_dimensional_array.c
  • Add_a_given_matrix_elements_using_two_dimensional_array.c
  • Multiply_matrix_elements_using_two_dimensional_array.c
  • Largest_and_smallest_elements_using_two_dimensional_array.c

Multi Dimensional Array

  • In C, can use 3 or more dimension called as multi dimensional array
  • Multi Dimension limit is based on the compiler

Syntax: data_type array_name [size-1][size_2]….[size_n]; 

  • data_type  – What kind of array data type
  • array_name  – name of the array
  • size  – array size

Example : 

  •  int a[10][10][10];  //Data type- int (2Byte), array_name – ‘a’, size – 2000(10x10x10x2), Memory Occupies- 2000bytes

 

Array disadvantage:

  • One disadvantage of using arrays to store data is that arrays are static structures and therefore cannot be easily extended or reduced to fit the data set.
  • Arrays are also expensive to maintain new insertions and deletions


Exercise

C Program to Find the Number of Elements in an Array

Method 1:

if you know then data type of the array then easily can find out the array elements one if its initialized using sifeof(variable or array name) predefined function.

/* * C Program to Find the Number of Elements in an Array */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    int array[] = {15, 50, 34, 20, 10, 79, 100};
    int n; 
    n = sizeof(array);
    printf("Size of the given array is %d\n", n/sizeof(int));
    return 0;
}

Method 2 :

if you don’t know then data type of the array then bit difficult to find out the array elements.


Find the size of array

#include <stdio.h>
int main()
{
  int size,i;
  printf("Enter the size of the array list");
 // scanf("%d",&size);
  int Arr[5]={88,97,65,43,77};
  size = 5;
   
  printf("\nBefore Array value\t:\t");
  for(i=0;i<size;i++)
    printf("%d\t",Arr[size]);
  /*
  for(i=0;i<size;i++)
  {
    if(Arr[size]>Arr[size+1])
      
  }
  */
  getchar();
  return 0;
}

Sum of the arrays 10 element

#include<stdio.h>
#include<conia.h>
int main()
{
	int num_array[10];
	int i,sum=0;
	int *ptr;
	printf("\n Enter 10 Elements")
	for(i=0; i<=10; i++)
		scanf("%d", num_array[i]);
	ptr = num_array;
	for(i=0; i<=10; i++)
	{
		sum = sum + *ptr;
		*ptr++;
	}
	printf("\n Sum of the arrays's 10 element : %d", sum);
	return 0;
}

NEXT

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example

C Programming Language

C – Storage Class specifiers Extern

  • The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else.
  • The extern declaration does not allocate storage for variables.
  • Used to resolve the scope of global symbol
  • Eg : Example Using extern in same file
main()
{
    extern int x;  //Tells compiler that it is defined somewhere else
    printf("%d",x);   
}
int x=10;    //Global variable x

Extern Variable Initializer

Extern as global variable initializer

  • The extern keyword variable can be initialize when its global

 

Example : External variable always initialize (Zero) ‘0’

#include "stdio.h"
extern int a;
main(){
    printf("a=%d",a);
    return 0;
}
int a;

/* Output : a=0 */

 

Example : variable initialize in  global variable

#include "stdio.h"
extern int a;
main(){
    printf("a=%d",a);
    return 0;
}
int a =5;

/* Output : a=5 */

 

Example :

#include <stdio.h> 
extern int a;
int main()
{
    void fun();
    printf("\n a=%d",a);
    fun();
    return 0;
}
int a=7;
    
void fun()
{
    printf("\n in fun a=%d",a);
}

/* Output : 
 a=7
 in fun a=7
*/

 

 

Example : variable initialize in  global variable

#include <stdio.h> 
extern int a=5;
int main()
{   
    printf("%d",a);
    return 0;
}

/* Output : 5*/
/* Explanation pritf function print a value as 5. */

 

Example : variable initialize in  global variable

#include <stdio.h> 
extern int a=5;
int main()
{
    void fun();
    printf("\n a=%d",a);
    fun();
    return 0;
}
int a;
    
void fun()
{
    printf("\n in fun a=%d",a);
}

/* Output : 
 a=5
 in fun a=5
*/

 

 

Example : Error while running Linker

#include <stdio.h> 
extern int a;
int main()
{
    printf("\na=%d",a);
    return 0;
}

/* Output : // Error */

/*
  Error[e46]: Undefined external "a" referred in main 
  Error while running Linker 
*/

 

Extern as local variable initializer

  • The extern keyword variable can not be initialize when its local or inside the function. (an initializer is not allowed on a local declaration of an extern variable)

EXample : an initializer is not allowed on a local declaration of an extern variable

#include <stdio.h> 
int main()
{
  extern int a=5;
  printf("%d",a);
  return 0;
}

/* Output */
// Error[Pe2442]: an initializer is not allowed on a local declaration of an extern variable main.c 

 

Embedded Compiler – IAR Workbench

IAR Embedded Workbench is a popular integrated development environment (IDE) for embedded systems development (compiler). It provides a complete set of development tools for building, debugging, and optimizing embedded applications for a wide range of microcontrollers.

Key features of IAR Embedded Workbench include:

  1. Compiler and Debugger: IAR Embedded Workbench comes with a highly optimizing C/C++ compiler and a powerful debugger that supports various debugging features such as breakpoints, watch windows, and real-time trace.
  2. Editor and Project Management: It offers a feature-rich code editor with syntax highlighting, code completion, and project management capabilities to organize your source files, libraries, and build configurations efficiently.
  3. RTOS Support: IAR Embedded Workbench provides support for various real-time operating systems (RTOS) commonly used in embedded applications, allowing developers to build and debug multitasking applications seamlessly.
  4. Peripheral Simulation: It includes built-in peripheral simulators for popular microcontrollers, enabling developers to simulate I/O operations and test their code without the need for physical hardware.
  5. Code Analysis and Optimization: The IDE offers advanced code analysis tools to identify potential issues, optimize code size and performance, and ensure code compliance with industry standards and best practices.
  6. Integration with Version Control Systems: It seamlessly integrates with version control systems such as Git and Subversion, allowing multiple developers to collaborate on projects and manage code revisions effectively.
  7. Support for Multiple Architectures: IAR Embedded Workbench supports a wide range of microcontroller architectures from leading semiconductor manufacturers, including ARM, AVR, MSP430, and more.

Overall, IAR Embedded Workbench provides a comprehensive development environment tailored for embedded systems developers, helping them streamline the development process, reduce time-to-market, and achieve high-quality, reliable embedded applications.

Read more: Embedded Compiler – IAR Workbench

how to print to debugger console in IAR?

  • you have to do is to #include <stdio.h>  and use printf() in your code.

Steps to follow

  • Project options -> Linker -> Output (tab)
  • In the “Format” section where you have selected “Debug information for C-SPY” you need to have “With I/O emulation modules” checked (this requires “with run-time control modules”)
  • Printf results you can see in View -> Terminal I/O from the top menu.

Reference

Getting Started with IAR Workbence for STM8

Procedure

  • 1. Projcet -> Create a new project -> Toolchain -> STM Series Praject Template -> Empty Projcet
    (then click “Ok”).
  • Save Your Project (File -> Save worksapce)
  • Notes : The project will appear in the Workspace window.
  • By default, two build configurations are created—Debug and Release
  • Before you add any files to your project, you should save the workspace.

See More

IAR Shortcuts

  • UNDO – CNTL + Z
  • REDO – CNTL + Y
  • CUT – CNTL + X
  • Copy – CNTL +C
  • Paste – CNTL + V
  • Select All – CNTL + ALL
  • Find and Replace
    • Comment Multiple Lines – CNTL + K
    • Find – CNTL + F
    • Find Next – F3
    • Find Previous – SHIFT +F3
    • Search with multiple condition – CNTL + SHIFT + F
  • Navigation
    • Navigate Forward – ALT + LEFT
    • Navigate backward – ALT + RIGHT
  • Go to Definition – F12
  • Auto Indent – CNTL + T
  • Debug
    • Go – F5
    • Stop debugging – CNTL + SHIFT + D
    • Step Over – F10
    • Step Into – F11
    • Step Out – SHIFT +F10

FAQ

if you know the answerer of the below question, Kindly help to add the solution in this website

  • How to View the two files side by side in IAR IDE?

Social Media – Facebook

Facebook Shortcut

Awesome Emoji shortcut in Commands


Find Friend on Facebook

I think from 2018 this feature was disabled due to some security update, But anyway you try once.

  • Search Facebook Accounts by Email Address
  • Search Facebook Accounts by Phone Number

 


Facebook Access your information

 

Facebook Contacts are sync or not?

 

Facebook stores Call history

 


Automatically like all Facebook posts

 


Find All the Photos Liked by…Anyone

  • Photos Liked by Anyone(Name in facebook)
  • Replace of anyone who wanna track them ID in this link : https://www.facebook.com/search/ID/photos-liked

 

 

 

Find All the Videos Liked by…Anyone

  • videos Liked by Anyone(Name in facebook)
  • Replace of anyone who wanna track them ID in this link : https://www.facebook.com/search/ID/videos-liked

 


see a relationship history with a different person on Facebook

 


Link Facebook page/profile to twitter

 


How to post weather in facebook page?

Go to Zapier and open new account or login if your already registered. Then find-out “Weather widget” in weather widget you can see Weather + Facebook page. Choose that app and set all settings.Now weather report automatically post to your selected Facebook page every day 07am.This https://www.facebook.com/AdalurWeather/ Facebook was successfully configured and till a date working well.

 


Reference

Electronics Circuit – LED Blink using Astable Multivibrator

In this article we will discuss and learn about Electronics Circuit – LED Blink using Astable Multivibrator. This is a simple two-LED blink example using the astable multi-vibrator circuit. This circuit generates two different not-stabled state output pulses. We can connect the LED in the two output pulse points and our LED blinks easily. This follows all instructions given to help those who are beginners in electronics. if you know skip what you know already.

Read more… →