Operators in C-4 | Programming and Data Structures - Computer Science Engineering (CSE) PDF Download

Results of comparison operations in C and C++

In C, data type of result of comparison operations is int. For example, see the following program.
#include<stdio.h>
int main()
{
    int x = 10, y = 10;
    printf("%d \n", sizeof(x == y));
    printf("%d \n", sizeof(x < y));
    return 0;
}
Output:
4
4

Whereas in C++, type of results of comparison operations is bool. For example, see the following program.
#include<iostream>
using namespace std;
int main()
{
    int x = 10, y = 10;
    cout << sizeof(x == y) << endl;
    cout << sizeof(x < y);
    return 0;
}
Output:
1
1

Execution of printf with ++ operators

Consider below C++ program and predict its output.
printf("%d %d %d", i, ++i, i++);
The above invokes undefined behaviour by referencing both ‘i’ and ‘i++’ in the argument list. It is not defined in which order the arguments are evaluated. Different compilers may choose different orders. A single compiler can also choose different orders at different times.
For example below three printf statements may also cause undefined behavior.
// All three printf() statements
// in this cause undefined behavior
#include <stdio.h>
int main()
{
    volatile int a = 10;
    printf("\n %d %d", a, a++);
    a = 10;
    printf("\n %d %d", a++, a);
    a = 10;
    printf("\n %d %d %d ", a, a++, ++a);
    return 0;
}
Therefore, it is not recommended Not to do two or more than two pre or post increment operators in the same statement.
This means that there’s absolutely no temporal ordering in this process. The arguments can be evaluated in any order, and the process of their evaluation can be intertwined in any way.

Sequence Points in C


In this post, we will try to cover many ambiguous questions like following.
Guess the output of following programs.
// PROGRAM 1
#include <stdio.h>
int f1() { printf ("Geeks"); return 1;}
int f2() { printf ("forGeeks"); return 1;}
int main()
{
  int p = f1() + f2();  
  return 0;
}
// Program 2
#include <stdio.h>
int x = 20;
int f1() { x = x+10; return x;}
int f2() { x = x-5;  return x;}
int main()
{
  int p = f1() + f2();
  printf ("p = %d", p);
  return 0;
}
// Program 3
#include <stdio.h>
int main()
{
   int i = 8;
   int p = i++*i++;
   printf("%d\n", p);
}
The output of all of the above programs is undefined or unspecified. The output may be different with different compilers and different machines. It is like asking the value of undefined automatic variable.
The reason for undefined behavior in Program 1 is, the operator ‘+’ doesn’t have standard defined order of evaluation for its operands. Either f1() or f2() may be executed first. So output may be either “GeeksforGeeks” or “forGeeksGeeks”.

Similar to operator ‘+’, most of the other similar operators like ‘-‘, ‘/’, ‘*’, Bitwise AND &, Bitwise OR |, .. etc don’t have a standard defined order for evaluation for its operands.
Evaluation of an expression may also produce side effects. For example, in the above program 2, the final values of p is ambiguous. Depending on the order of expression evaluation, if f1() executes first, the value of p will be 55, otherwise 40.
The output of program 3 is also undefined. It may be 64, 72, or may be something else. The subexpression i++ causes a side effect, it modifies i’s value, which leads to undefined behavior since i is also referenced elsewhere in the same expression.
Unlike above cases, at certain specified points in the execution sequence called sequence points, all side effects of previous evaluations are guaranteed to be complete. A sequence point defines any point in a computer program’s execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. Following are the sequence points listed in the C standard:

The end of the first operand of the following operators:
(a) logical AND &&
(b) logical OR ||
(c) conditional ?
(d) comma,
For example, the output of following programs is guaranteed to be “GeeksforGeeks” on all
compilers/machines.
// Following 3 lines are common in all of the below programs
#include <stdio.h>
int f1() { printf ("Geeks"); return 1;}
int f2() { printf ("forGeeks"); return 1;}
// Program 4
int main()
{
   // Since && defines a sequence point after first operand, it is
   // guaranteed that f1() is completed first.
   int p = f1() && f2();  
   return 0;
}  
// Program 5
int main()
{
   // Since comma operator defines a sequence point after first operand, it is
   // guaranteed that f1() is completed first.
  int p = (f1(), f2());
  return 0;
}
// Program 6
int main()
{
   // Since ? operator defines a sequence point after first operand, it is
   // guaranteed that f1() is completed first.
  int p = f1()? f2(): 3;  
  return 0;
}

The end of a full expression. This category includes following expression statements
(a) Any full statement ended with semicolon like “a = b;”
(b) return statements
(c) The controlling expressions of if, switch, while, or do-while statements.
(d) All three expressions in a for statement.

To find sum of two numbers without using any operator

Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used.
Solution: It’s a trick question. We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in printf() can be used to find the sum of two numbers. We can use ‘*’ which indicates the minimum width of output. For example, in the statement “printf(“%*d”, width, num);”, the specified ‘width’ is substituted in place of *, and ‘num’ is printed within the minimum width specified. If number of digits in ‘num’ is smaller than the specified ‘width’, the output is padded with blank spaces. If number of digits are more, the output is printed as it is (not truncated). In the following program, add() returns sum of x and y. It prints 2 spaces within the width specified using x and y. So total characters printed is equal to sum of x and y. That is why add() returns x+y.

C
#include <stdio.h>
int add(int x, int y)
{
    return printf("%*c%*c", x, ' ', y, ' ');
}
// Driver code
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}
Output:
Sum = 7

The output is seven spaces followed by “Sum = 7”. We can avoid the leading spaces by using carriage return. Thanks to krazyCoder and Sandeep for suggesting this. The following program prints output without any leading spaces.

C
#include <stdio.h>
int add(int x, int y)
{
    return printf("%*c%*c", x, '\r', y, '\r');
}
// Driver code
int main()
{
    printf("Sum = %d", add(3, 4));
    return 0;
}
Output:
Sum = 7

Another Method

C++
#include <iostream>
using namespace std;
int main()
{
    int a = 10, b = 5;
    if (b > 0) {
        while (b > 0) {
            a++;
            b--;
        }
    }
    if (b < 0) { // when 'b' is negative
        while (b < 0) {
            a--;
            b++;
        }
    }
    cout << "Sum = " << a;
    return 0;
}
// This code is contributed by SHUBHAMSINGH10
// This code is improved & fixed by Abhijeet Soni.

C
#include <stdio.h>
int main()
{
    int a = 10, b = 5;
    if (b > 0) {
        while (b > 0) {
            a++;
            b--;
        }
    }
    if (b < 0) { // when 'b' is negative
        while (b < 0) {
            a--;
            b++;
        }
    }
    printf("Sum = %d", a);
    return 0;
}
// This code is contributed by Abhijeet Soni

Java
// Java code
class GfG {
    public static void main(String[] args)
    {
        int a = 10, b = 5;
        if (b > 0) {
            while (b > 0) {
                a++;
                b--;
            }
        }
        if (b < 0) { // when 'b' is negative
            while (b < 0) {
                a--;
                b++;
            }
        }
        System.out.println("Sum is: " + a);
    }
}
// This code is contributed by Abhijeet Soni

Python 3
# Python 3 Code
if __name__ == '__main__':    
    a = 10
    b = 5
    if b > 0:
        while b > 0:
            a = a + 1
            b = b - 1
   if b < 0:
        while b < 0:
            a = a - 1
            b = b + 1
    print("Sum is: ", a)
# This code is contributed by Akanksha Rai
# This code is improved & fixed by Abhijeet Soni

C#
// C# code
using System;
class GFG {
    static public void Main()
    {
        int a = 10, b = 5;
        if (b > 0) {
            while (b > 0) {
                a++;
                b--;
           }
        }
        if (b < 0) { // when 'b' is negative
            while (b < 0) {
                a--;
                b++;
            }
        }
        Console.Write("Sum is: " + a);
    }
}
// This code is contributed by Tushil
// This code is improved & fixed by Abhijeet Soni.

PHP
<?php
// PHP Code
$a = 10;
$b = 5;
if ($b > 0) {
while($b > 0)
{
    $a++;
    $b--;
}
}
if ($b < 0) {
while($b < 0)
{
    $a--;
    $b++;
}
}
echo "Sum is: ", $a;
// This code is contributed by Dinesh
// This code is improved & fixed by Abhijeet Soni.
?>

Javascript
<script>
// Javascript program for the above approach
// Driver Code
    let a = 10, b = 5;
    if (b > 0) {
        while (b > 0) {
            a++;
            b--;
        }
    }
    if (b < 0) { // when 'b' is negative
        while (b < 0) {
            a--;
            b++;
        }
    }
    document.write("Sum = " + a);
</script>
Output:
sum = 15

The document Operators in C-4 | Programming and Data Structures - Computer Science Engineering (CSE) is a part of the Computer Science Engineering (CSE) Course Programming and Data Structures.
All you need of Computer Science Engineering (CSE) at this link: Computer Science Engineering (CSE)
119 docs|30 tests

Top Courses for Computer Science Engineering (CSE)

FAQs on Operators in C-4 - Programming and Data Structures - Computer Science Engineering (CSE)

1. What is C-4 GATE?
Ans. C-4 GATE is an exam conducted for candidates aiming to pursue higher studies or seek employment in the field of computer science. It tests their knowledge and understanding of various concepts related to computer science and engineering.
2. How can I apply for C-4 GATE?
Ans. To apply for C-4 GATE, candidates need to visit the official website of the conducting body and fill out the application form. They will be required to provide personal details, educational qualifications, and pay the application fee as specified. The detailed application process and important dates can be found on the official website.
3. What are the eligibility criteria for C-4 GATE?
Ans. The eligibility criteria for C-4 GATE include having a bachelor's degree in engineering or science, or a master's degree in any branch of science, mathematics, statistics, or computer applications. The specific eligibility criteria may vary depending on the conducting body, so it is important to refer to the official notification for accurate information.
4. What subjects are covered in the C-4 GATE exam?
Ans. The C-4 GATE exam covers various subjects including computer science and information technology, mathematics, and general aptitude. The syllabus for each subject is specified by the conducting body and can be found in the official notification or on the official website.
5. How can I prepare for the C-4 GATE exam?
Ans. To prepare for the C-4 GATE exam, candidates should start by understanding the exam pattern and syllabus. They can then create a study plan, allocate dedicated time for each subject, and focus on practicing previous year question papers and mock tests. Additionally, referring to standard textbooks and online resources specific to the exam can also be helpful in preparing effectively.
119 docs|30 tests
Download as PDF
Explore Courses for Computer Science Engineering (CSE) exam

Top Courses for Computer Science Engineering (CSE)

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Objective type Questions

,

Previous Year Questions with Solutions

,

Free

,

pdf

,

MCQs

,

study material

,

past year papers

,

Semester Notes

,

Important questions

,

Exam

,

shortcuts and tricks

,

Viva Questions

,

Summary

,

Operators in C-4 | Programming and Data Structures - Computer Science Engineering (CSE)

,

Sample Paper

,

ppt

,

Operators in C-4 | Programming and Data Structures - Computer Science Engineering (CSE)

,

video lectures

,

practice quizzes

,

Extra Questions

,

Operators in C-4 | Programming and Data Structures - Computer Science Engineering (CSE)

,

mock tests for examination

;